Esempio n. 1
0
        static void Main(string[] args)
        {
            Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.Clear();

            //Attach a console listener
            System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());

            //Start server
            ServerSettings settings = new ServerSettings();
            StateServer server = new StateServer(settings, new SHA256_AESAuthenticator(settings["PeerPassword"]));
            server.Start();

            Console.WriteLine("[SERVER STARTED. PRESS ESCAPE KEY TO QUIT.]\r\n");

            //Wait for user signal to end server
            while (true)
            {
                if (Console.KeyAvailable)
                {
                    if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                    {
                        break;
                    }
                }
                else
                {
                    Thread.Sleep(500);
                }
            }

            //Stop server
            server.Stop();
        }
Esempio n. 2
0
        public AsteriskConnector()
        {
            InitializeComponent();
            try
            {
                //Trace.Listeners.Add(new TextWriterTraceListener("asteriskconnector.log"));
                log.Debug("Initializing asterisk connector...");
                string address  = Properties.Settings.Default.AsteriskServer;
                int    port     = Convert.ToInt32(Properties.Settings.Default.AsteriskPort);
                string user     = Properties.Settings.Default.AsteriskUser;
                string password = Properties.Settings.Default.AsteriskUserPassword;
                log.Debug("Creating new manager connection: " + address + ":" + port + " as " + user);
                manager = new ManagerConnection(address, port, user, password);
                manager.PingInterval    = Properties.Settings.Default.AsteriskPingInterval;
                manager.KeepAlive       = true;
                manager.FireAllEvents   = true;
                manager.UnhandledEvent += new ManagerEventHandler(manager_UnhandledEvent);

                log.Debug("Creating StateServer Proxy: ");
                ss = new StateServer(Properties.Settings.Default.StateServerUrl);

                log.Debug("Creating AsteriskCTIService...");
                acs  = new AsteriskCTIService(manager);
                host = new ServiceHost(acs);
                log.Debug("Hosting AsteriskCTIService...");
                host.Open();
            }
            catch (Exception e)
            {
                log.Debug("Error while initializing AsteriskConnector: " + e.Message);
            }
        }
Esempio n. 3
0
 protected override void OnStart(string[] args)
 {
     //Start server
     ServerSettings settings = new ServerSettings();
     server = new StateServer(settings, new SHA256_AESAuthenticator(settings["PeerPassword"]));
     server.Start();
 }
Esempio n. 4
0
        static void Main(string[] args)
        {
            Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.Clear();

            //Attach a console listener
            System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());

            //Start server
            ServerSettings settings = new ServerSettings();
            StateServer    server   = new StateServer(settings, new SHA256_AESAuthenticator(settings["PeerPassword"]));

            server.Start();

            Console.WriteLine("[SERVER STARTED. PRESS ESCAPE KEY TO QUIT.]\r\n");

            //Wait for user signal to end server
            while (true)
            {
                if (Console.KeyAvailable)
                {
                    if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                    {
                        break;
                    }
                }
                else
                {
                    Thread.Sleep(500);
                }
            }

            //Stop server
            server.Stop();
        }
Esempio n. 5
0
        protected override void OnStop()
        {
            RequestAdditionalTime(300000); //an extra five minutes -- this can be a lengthy process

            //stop server
            server.Stop();
            server = null;
        }
Esempio n. 6
0
        protected override void OnStart(string[] args)
        {
            //Start server
            ServerSettings settings = new ServerSettings();

            server = new StateServer(settings, new SHA256_AESAuthenticator(settings["PeerPassword"]));
            server.Start();
        }
Esempio n. 7
0
        protected override void OnStop()
        {
            RequestAdditionalTime(300000); //an extra five minutes -- this can be a lengthy process

            //stop server
            server.Stop();
            server = null;
        }
Esempio n. 8
0
 internal Booker(string connectionStr, BookExecutor bookExecutor)
 {
     this.connectionStr = connectionStr;
     this.bookExecutor  = bookExecutor;
     if (!StateServer.ShouldUserTransactionServer())
     {
         _bookWatcher = new BookWatcher(this);
     }
 }
Esempio n. 9
0
        protected void Application_Start(Object sender, EventArgs e)
        {
            try
            {
                //init State object
                if (this.IsTransactionAdapterServiceConfiged())
                {
                    log4net.Config.XmlConfigurator.Configure();
                    Task.Factory.StartNew(() =>
                    {
                        this.StartHost();
                    });
                }
                string stateServerID            = ConfigurationManager.AppSettings["StateServerID"];
                string connectionString         = ConfigurationManager.AppSettings["ConnectionString"];
                string securityConnectionString = ConfigurationManager.AppSettings["SecurityConnectionString"];
                string serverName = ConfigurationManager.AppSettings["ServerName"];
                if (string.IsNullOrEmpty(serverName))
                {
                    serverName = "StateServer";
                }
                //Check if data is tempered
                if (!Checker.VerifyHash())
                {
                    throw new ApplicationException("Data is tempered, please contact the vendor!");
                }

                string serviceUrl = this.GetLocalServiceUrl();

                Application["StateServer"] = Global.StateServer = new StateServer(stateServerID, connectionString, serviceUrl, securityConnectionString);

                //added by adam on 2009-02-05
                string workMode = ConfigurationManager.AppSettings["workMode"];
                if (String.Equals(workMode, "Filiale", StringComparison.CurrentCultureIgnoreCase))
                {
                    //create FilialeTransactionSwitcher instance, and begin send the failed transaction(if have) in new thread.
                    FilialeTransactionSwitcher.GetInstance();
                }

                AppDebug.LogEvent("StateServer", stateServerID + " started", EventLogEntryType.SuccessAudit);
                Application["LogManager"] = Global.LogManager = new LogManager(AppType.StateServer, connectionString, 60, serverName);
                Global.LogManager.LogServiceAction(Common.Log.ServiceAction.Start, DateTime.Now);
            }
            catch (Exception ex)
            {
                AppDebug.LogEvent("StateServer", ex.ToString(), EventLogEntryType.Error);
                throw;
            }
        }
Esempio n. 10
0
        private QuotationBroadcastHelper(StateServer stateServer, TransactionServer.Service transactionServerService)
        {
            this._StateServer = stateServer;
            this._TransactionServerService = transactionServerService;

            string host = new Uri(transactionServerService.Url).Host;
            string port = ConfigurationManager.AppSettings["iExchange.StateServer.TransactionServer.RealtimeQuotationServicePort"];

            this.realtimeQuotationProcessorServiceUrl = string.Format("net.tcp://{0}:{1}/TransactionServer/RealtimeQuotationProcessService", host, string.IsNullOrEmpty(port) ? "9090" : port);
            this.realtimeQuotationProcessorService    = CreateRealtimeQuotationProcessorService(this.realtimeQuotationProcessorServiceUrl);

            this._TransactionServerService.Timeout = 1800000;
            this._QuotationForBroadcastQueue       = new Queue <QuotationForBroadcast>();
            this._BroadcastThread = new Thread(this.Broadcast);
            this._BroadcastThread.IsBackground = true;
            this._BroadcastThread.Start();
        }
Esempio n. 11
0
 public static void Add(StateServer stateServer, TransactionServer.Service transactionServerService)
 {
     QuotationBroadcastHelper._QuotationBroadcastHeplers.Add(new QuotationBroadcastHelper(stateServer, transactionServerService));
 }
Esempio n. 12
0
 //short exportCount = 0;
 /// <summary>
 /// Initializes a new instance of the GetRequest class
 /// </summary>
 /// <param name="Data">The HTTPPartialData class to load this instance from</param>
 /// <param name="Service">State server instance</param>
 public GetRequest(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
     //Validate
     if (!isError)
     {
         //This message requires a resource
         if (verb.Resource == string.Empty)
         {
             isError = true;
         }
     }
 }
Esempio n. 13
0
 /// <summary>
 /// Initializes a new instance of the GetTransferMessage class
 /// </summary>
 /// <param name="Data">The HTTPPartialData class to load this instance from</param>
 /// <param name="Service">State server instance</param>
 public GetTransferMessage(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
     //Validate
     if (!isError)
     {
         //This message requires a resource, a maxForwards and an ID
         if (verb.Resource == string.Empty || maxForwards == null || id == null)
         {
             isError = true;
         }
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Initializes a new instance of the PeerMessage class
        /// </summary>
        /// <param name="Data">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public PeerMessage(HTTPPartialData Data, StateServer Service)
            : base(Data, Service)
        {
            maxForwards = null;
            if (headers["MAX-FORWARDS"] != null)
            {
                uint v;
                uint.TryParse(headers["MAX-FORWARDS"], out v);
                maxForwards = v;
            }

            id = null;
            if (headers["X-ID"] != null)
            {
                try
                {
                    id = new Guid(headers["X-ID"]);
                }
                catch
                {
                    id = null;
                }

            }

            if (headers["X-BROADCAST-ID"] != null)
            {
                try
                {
                    broadcastID = new Guid(headers["X-BROADCAST-ID"].Trim());
                }
                catch
                { isError = true; }
            }
            else
            {
                broadcastID = Guid.Empty;
            }
        }
Esempio n. 15
0
 /// <summary>
 /// Initializes a new instance of the BadMessage class
 /// </summary>
 /// <param name="Data">The HTTPPartialData class to load this instance from</param>
 /// <param name="Service">State server instance</param>
 public BadMessage(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
 }
Esempio n. 16
0
 //short exportCount = 0;
 /// <summary>
 /// Initializes a new instance of the ReleaseExclusiveRequest class
 /// </summary>
 /// <param name="Data">The HTTPPartialData class to load this instance from</param>
 /// <param name="Service">State server instance</param>
 public ReleaseExclusiveRequest(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
     //Validate
     if (!isError)
     {
         //This message requires a resource and a lock cookie
         if (verb.Resource == string.Empty || lockCookie == null )
         {
             isError = true;
         }
     }
 }
Esempio n. 17
0
        /// <summary>
        /// Initializes a new instance of the CompleteAuthRequest class
        /// </summary>
        /// <param name="Data">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public CompleteAuthRequest(HTTPPartialData Data, StateServer Service)
            : base(Data, Service)
        {
            string www_auth = headers["AUTHORIZATION"];

            if (www_auth != null)
            {
                //Split comma-delimited directives
                string[] directives = www_auth.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                //first check for and remove 'Digest' from the first line
                if (directives.Length > 0 && directives[0].Trim().ToUpperInvariant().StartsWith("DIGEST"))
                {
                    directives[0] = directives[0].Trim().Substring(6); //remove digest word

                    //Read realm, qop and nonce
                    foreach (string line in directives)
                    {
                        string key, value;
                        GetKeyValue(line, '=', out key, out value);

                        switch (key.ToUpperInvariant().Trim())
                        {
                            case "USERNAME":
                                username = Unquote(value).Trim();
                                break;

                            case "REALM":
                                realm = Unquote(value).Trim();
                                break;

                            case "QOP":
                                qop = Unquote(value).Trim();
                                break;

                            case "NONCE":
                                nonce = Unquote(value).Trim();
                                if (!IsValidBase64(nonce)) nonce = null;
                                break;

                            case "CNONCE":
                                cnonce = Unquote(value).Trim();
                                if (!IsValidBase64(cnonce)) cnonce = null;
                                break;

                            case "URI":
                                uri = Unquote(value);
                                break;

                            case "RESPONSE":
                                response = Unquote(value).Trim();
                                if (!IsValidBase64(response)) response = null;
                                break;

                            case "NC":
                                Int32.TryParse(Unquote(value),System.Globalization.NumberStyles.HexNumber,null, out ncount);
                                break;

                            case "ALGORITHM":
                                algorithm = Unquote(value).Trim();
                                break;

                        }

                    }

                }

            }

            //Validate
            if (!isError)
            {
                //This message requires username, realm, qop, nonce, cnonce, response and uri
                if (username == null || qop == null || nonce == null || cnonce == null || realm == null || response == null || uri == null)
                {
                    isError = true;
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Initializes a new instance of the SetRequest class
        /// </summary>
        /// <param name="Data">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public SetRequest(HTTPPartialData Data, StateServer Service)
            : base(Data, Service)
        {
            if (lockCookie == null) lockCookie = 0; //set 0 as default lock-cookie value

            //Validate
            if (!isError)
            {
                //This message requires a resource and a lock cookie
                if (verb.Resource == string.Empty || lockCookie == null )
                {
                    isError = true;
                }
            }
        }
Esempio n. 19
0
 /// <summary>
 /// Initializes a new instance of the BeginAuthRequest class
 /// </summary>
 /// <param name="Data">The HTTPPartialData class to load this instance from</param>
 /// <param name="Service">State server instance</param>
 public BeginAuthRequest(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
 }
Esempio n. 20
0
 /// <summary>
 /// Initializes a new instance of the ServiceUnavailableResponse class
 /// </summary>
 /// <param name="Data">The HTTPPartialData to create object from</param>
 /// <param name="Service">State server instance</param>
 public ServiceUnavailableResponse(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
     //Validate
     if (!isError)
     {
         //This message requires an empty content length
         if (body.Length != 0)
         {
             isError = true;
         }
     }
 }
Esempio n. 21
0
        /// <summary>
        /// Initializes a new instance of the ServiceResponse class
        /// </summary>
        /// <param name="Data">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public ServiceResponse(HTTPPartialData Data, StateServer Service)
            : base(Data, Service)
        {
            actionFlags = headers["ACTIONFLAGS"];
            aspNetVersion = headers["X-ASPNET-VERSION"];

            assocID = null;
            if (headers["X-ASSOC-ID"] != null)
            {
                try
                {
                    assocID = new Guid(headers["X-ASSOC-ID"]);
                }
                catch
                {
                    assocID = null;
                }

            }
        }
Esempio n. 22
0
        /// <summary>
        /// Initializes a new instance of the ServiceRequest class
        /// </summary>
        /// <param name="Data">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public ServiceRequest(HTTPPartialData Data, StateServer Service)
            : base(Data,Service)
        {
            extraFlags = headers["EXTRAFLAGS"];

            //ExtraFlags only accepts 0 and 1 -- if any other value is set, set it to null
            if (extraFlags != null)
            {
                extraFlags = extraFlags.Trim();
                if (extraFlags != "0" && extraFlags != "1")
                {
                    extraFlags = null;
                }
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Initializes a new instance of the PingReplyMessage class
 /// </summary>
 /// <param name="Data">The HTTPPartialData class to load this instance from</param>
 /// <param name="Service">State server instance</param>
 public PingReplyMessage(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
 }
Esempio n. 24
0
 /// <summary>
 /// Sends a GetTransferMessage to a list of ServiceSockets
 /// </summary>
 /// <param name="OriginHost">The Host name of the peer that originally initiated this message</param>
 /// <param name="sockets">List of target ServiceSockets</param>
 /// <param name="Service">Instance of state server</param>
 /// <param name="SessionKey">The requested session URI</param>
 /// <param name="MessageID">The unique message identifier</param>
 /// <param name="MaxForwards">The maximum number of nodes to forward the message to. This field is decremented by one for each forward</param>
 /// <param name="BroadcastID">The broadcast identifier. Used by peers to identify different broadcasts of the same message.</param>
 public static void Broadcast(string OriginHost, List<ServiceSocket> sockets, StateServer Service, string SessionKey,
     Guid MessageID, int MaxForwards, Guid BroadcastID)
 {
     Broadcast(OriginHost ,sockets, Service, SessionKey, MessageID, MaxForwards, BroadcastID, DateTime.MinValue, null, null);
 }
Esempio n. 25
0
        /// <summary>
        /// Initializes a new instance of the SetTransferRequest class
        /// </summary>
        /// <param name="Data">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public SetTransferRequest(HTTPPartialData Data, StateServer Service)
            : base(Data, Service)
        {
            lastModified = DateTime.MinValue;
            if (headers["LAST-MODIFIED"] != null)
            {
                long v;
                if (long.TryParse(headers["LAST-MODIFIED"], out v))
                {
                    try
                    {
                        lastModified = new DateTime(v);
                    }
                    catch
                    {
                        lastModified = DateTime.MinValue;
                    }
                }
            }

            lockDate = null;
            if (headers["LOCKDATE"] != null)
            {
                long v;
                if (long.TryParse(headers["LOCKDATE"], out v))
                {
                    try
                    {
                        lockDate = new DateTime(v);
                    }
                    catch
                    {
                        lockDate = null;
                    }
                }
            }

            lockAge = null;
            if (headers["LOCKAGE"] != null)
            {
                int v;
                if (int.TryParse(headers["LOCKAGE"], out v))
                {
                    try
                    {
                        lockAge = new TimeSpan(0,0,v);
                    }
                    catch
                    {
                        lockAge = null;
                    }
                }
            }

            id = Guid.Empty;
            if (headers["X-ID"] != null)
            {
                try
                {
                    id = new Guid(headers["X-ID"]);
                }
                catch
                {
                    id = Guid.Empty;
                }

            }

            //Validate
            if (!isError)
            {
                //This message requires a resource + modified date
                if (verb.Resource == string.Empty || lastModified == DateTime.MinValue)
                {
                    isError = true;
                }

                //Lockdate + LockCookie + LockAge must be set if any is set
                if ((((lockDate == null) && (lockCookie == null) && (lockAge == null)) ^
                    ((lockDate == null) || (lockCookie == null) || (lockAge == null))) == true)
                {
                    isError = true;
                }

                //LockCookie must be valid
                if (lockCookie.HasValue && LockCookie.Value > MAX_LockCookieValue) isError = true;

                //ID must be present
                if (id == Guid.Empty) isError = true;
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Initializes a new instance of the ServiceMessage class
        /// </summary>
        /// <param name="HTTPData">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public ServiceMessage(HTTPPartialData HTTPData, StateServer Service)
            : base(HTTPData)
        {
            service = Service;

            //Get other information
            timeout = null;

            if (headers["TIMEOUT"] != null)
            {
                int v;
                int.TryParse(headers["TIMEOUT"], out v);
                timeout = v;
            }

            lockCookie = null;
            if (headers["LOCKCOOKIE"] != null)
            {
                uint v;
                uint.TryParse(headers["LOCKCOOKIE"], out v);
                lockCookie = v;
            }

            int plainTextSize = -1;
            bool encrypted  = false;
            if (headers["CONTENT-TYPE"] != null)
            {
                string[] directives = headers["CONTENT-TYPE"].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                if(directives[0].Trim().ToUpperInvariant() == @"APPLICATION/X-ENCRYPTED") encrypted = true;
                foreach (string directive in directives)
                {
                    if (directive.Trim().ToUpperInvariant().StartsWith("PLAINTEXT-LENGTH"))
                    {
                        if (!int.TryParse(directive.Trim().Substring(16).Replace("=", string.Empty).Trim(), out plainTextSize))
                        {
                            isError = true;
                        }
                    }
                }

                if(encrypted && plainTextSize < 0) isError = true;
            }

            if (!isError)
            {
                if (socket.IsAuthenticated && service.Settings.EncryptPeerData)
                {
                    if (body.Length > 0 )
                    {
                        if (!encrypted)
                        {
                            Diags.LogMessageUnprotectedError(this);
                            isError = true;
                        }
                        else
                        {
                            try
                            {
                                body = service.Authenticator.Unprotect(body, socket.SessionKey, plainTextSize);
                            }
                            catch (Exception ex)
                            {
                                Diags.LogMessageContentCipherError(this, ex);
                                isError = true;
                            }

                        }
                    }
                }
                else
                {
                    if (encrypted)
                    {
                        Diags.LogMessageProtectedError(this);
                        isError = true;
                    }
                }
            }
        }
Esempio n. 27
0
        protected override void OnStart(string[] args)
        {
            try
            {
                //Trace.Listeners.Add(new TextWriterTraceListener("asteriskconnector.log"));
                log.Debug("Initializing tapi connector...");
                Calls   = new Hashtable();
                manager = new TapiManager("TALK TAPI CTI Service");
                if (manager.Initialize())
                {
                    log.Debug("Creating LineControlServer Proxy: ");
                    ss = new StateServer(Properties.Settings.Default.LineControlServerUrl);

                    log.Debug("Creating TAPICTIService...");
                    host = new ServiceHost(new TAPICTIService(manager));
                    log.Debug("Hosting TAPICTIService...");
                    host.Open();
                    log.Debug("Creating TAPISnapshotService...");
                    snapshotHost = new ServiceHost(new TAPISnapshotServer(manager));
                    log.Debug("Hosting TAPISnapshotService...");
                    snapshotHost.Open();
                    isInitialized = true;
                }
                else
                {
                    log.Debug("Unable to initialize TAPI Manager");
                }
            }
            catch (Exception e)
            {
                log.Debug("Error while initializing TAPIConnector: " + e.Message);
            }
            log.Debug("TAPI Connector starting");
            if (isInitialized)
            {
                manager.AddressChanged   += new EventHandler <AddressInfoChangeEventArgs>(manager_AddressChanged);
                manager.CallInfoChanged  += new EventHandler <CallInfoChangeEventArgs>(manager_CallInfoChanged);
                manager.CallStateChanged += new EventHandler <CallStateEventArgs>(manager_CallStateChanged);
                manager.LineAdded        += new EventHandler <LineAddedEventArgs>(manager_LineAdded);
                manager.LineChanged      += new EventHandler <LineInfoChangeEventArgs>(manager_LineChanged);
                manager.LineRemoved      += new EventHandler <LineRemovedEventArgs>(manager_LineRemoved);
                manager.LineRinging      += new EventHandler <RingEventArgs>(manager_LineRinging);
                manager.NewCall          += new EventHandler <NewCallEventArgs>(manager_NewCall);
                manager.PhoneAdded       += new EventHandler <PhoneAddedEventArgs>(manager_PhoneAdded);
                manager.PhoneRemoved     += new EventHandler <PhoneRemovedEventArgs>(manager_PhoneRemoved);
                manager.ReinitRequired   += new EventHandler(manager_ReinitRequired);

                foreach (TapiLine line in manager.Lines)
                {
                    line.Changed          += new EventHandler <LineInfoChangeEventArgs>(line_Changed);
                    line.AddressChanged   += new EventHandler <AddressInfoChangeEventArgs>(line_AddressChanged);
                    line.CallInfoChanged  += new EventHandler <CallInfoChangeEventArgs>(line_CallInfoChanged);
                    line.CallStateChanged += new EventHandler <CallStateEventArgs>(line_CallStateChanged);
                    line.NewCall          += new EventHandler <NewCallEventArgs>(line_NewCall);
                    line.Ringing          += new EventHandler <RingEventArgs>(line_Ringing);



                    if (!line.IsOpen)
                    {
                        try
                        {
                            log.Debug("Opening line: " + line.ToString() + " name: " + line.Name);
                            line.Open(line.Capabilities.MediaModes);

                            try
                            {
                                log.Debug("Parsing " + line.ToString() + " adresses");
                                foreach (TapiAddress address in line.Addresses)
                                {
                                    address.CallInfoChanged  += new EventHandler <CallInfoChangeEventArgs>(address_CallInfoChanged);
                                    address.CallStateChanged += new EventHandler <CallStateEventArgs>(address_CallStateChanged);
                                    address.Changed          += new EventHandler <AddressInfoChangeEventArgs>(address_Changed);
                                    address.NewCall          += new EventHandler <NewCallEventArgs>(address_NewCall);

                                    ss.SetLineControl(GetLineControl(address));
                                }
                            }
                            catch (Exception e)
                            {
                                log.Error("Error while parsing " + line.ToString() + " addresses: " + e.Message);
                            }

                            //linedevspecific etrali
                            try
                            {
                                log.Debug(line.ToString() + " device specific data : " + System.Text.Encoding.ASCII.GetString(line.Status.DeviceSpecificData));
                                line.NegotiateExtensions(Properties.Settings.Default.DevSpecificMinVersion, Properties.Settings.Default.DevSpecificMaxVersion, new EventHandler <DeviceSpecificEventArgs>(line_DevSpecific));
                            }
                            catch (Exception lne)
                            {
                                log.Error("Unable to negotiate dev specific extensions for " + line.ToString() + " " + lne.ToString());
                            }
                        }
                        catch
                        {
                            log.Error("Error while opening line: " + line.ToString());
                        }
                    }
                }
            }
        }
Esempio n. 28
0
        //Timeout action needs to be very short as it can be chained in a long call list of time out actions
        /// <summary>
        /// Sends a BeginAuthRequest message to a specified ServiceSocket
        /// </summary>
        /// <param name="socket">The target ServiceSocket</param>
        /// <param name="Service">The state server instance</param>
        /// <param name="SuccessAction">The Action to call if the message was accepted</param>
        /// <param name="FailAction">The Action to call if the message transmission failed or was refused</param>
        /// <param name="TimeoutAction">The Action to call if the transfer timed out This Action's processing time should be very short because a long list of Timeout actions can be daisy-chained and called one after the other</param>
        /// <param name="Timeout">The timeout time span</param>
        public static void Send(ServiceSocket socket, StateServer Service, Action<ServiceSocket> SuccessAction, Action<ServiceSocket> FailAction, System.Threading.WaitCallback TimeoutAction, TimeSpan Timeout)
        {
            ResponseData rdata = new ResponseData(Encoding.UTF8.GetBytes("GET \\AUTH HTTP/1.1\r\nHost: " + (Service.ServerIP ?? socket.LocalIP) + "\r\n\r\n"), typeof(BeginAuthRequest));

            //Create new AsyncResultActions object to hold delegates for actions based on the outcome of the call
            AsyncResultActions<ServiceSocket> asyncResults = new AsyncResultActions<ServiceSocket>(socket);
            asyncResults.Result1Action = SuccessAction;
            asyncResults.Result2Action = FailAction;
            asyncResults.TimeoutAction = TimeoutAction;

            Service.AsyncSocketRequests.Add(DateTime.UtcNow + Timeout, socket, asyncResults);

            socket.Send(rdata);
            Diags.LogSend(socket, rdata);
        }
Esempio n. 29
0
 /// <summary>
 /// Initializes a new instance of the BadRequestResponse class
 /// </summary>
 /// <param name="Data">The HTTPPartialData class to load this instance from</param>
 /// <param name="Service">State server instance</param>
 public BadRequestResponse(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
     //No Validation required
 }
Esempio n. 30
0
 /// <summary>
 /// Initializes a new instance of the UnknownResponse class
 /// </summary>
 /// <param name="Data">The HTTPPartialData class to load this instance from</param>
 /// <param name="Service">State server instance</param>
 public UnknownResponse(HTTPPartialData Data, StateServer Service)
     : base(Data, Service)
 {
 }
Esempio n. 31
0
        /// <summary>
        /// Sends a SetTransferRequest message to a specified ServiceSocket
        /// </summary>
        /// <param name="connectedMsg">AsyncMessageTracker holding connected socket</param>
        /// <param name="Service">The state server instance</param>
        /// <param name="Resource">The URI associated with the message</param>
        /// <param name="SessionInfo">The Session information used to populate fields in the message</param>
        /// <param name="Data">The message data</param>
        /// <param name="SuccessAction">The Action to call if the message was accepted</param>
        /// <param name="FailAction">The Action to call if the message transmission failed or was refused</param>
        /// <param name="AlreadyExistsAction">The Action to call if the recipient peer already has the URI</param>
        /// <param name="PeerShuttingDownAction">The Action to call if the recipient peer is shutting down</param>
        /// <param name="TimeoutAction">The Action to call if the transfer timed out. This Action's processing time should be very short because a long list of Timeout actions can be daisy-chained and called one after the other</param>
        /// <param name="Timeout">The timeout time span</param>
        public static void Send(AsyncMessageTracker connectedMsg, StateServer Service, string Resource, ISessionResponseInfo SessionInfo,
            byte[] Data, Action<AsyncMessageTracker> SuccessAction, Action<AsyncMessageTracker> FailAction, Action<AsyncMessageTracker> AlreadyExistsAction, Action<AsyncMessageTracker> PeerShuttingDownAction, System.Threading.WaitCallback TimeoutAction, TimeSpan Timeout)
        {
            StringBuilder headers = new StringBuilder();

            headers.AppendFormat("PUT {0} HTTP/1.1\r\nHost: {1}\r\nX-ID: {2}\r\n", Resource, Service.ServerIP ?? connectedMsg.Socket.LocalIP,  connectedMsg.ID.ToString("N"));

            if (SessionInfo.LockDateInTicks != DateTime.MinValue.Ticks)
            {
                headers.AppendFormat("LockDate: {0}\r\nLockAge: {1}\r\nLockCookie: {2}\r\n", SessionInfo.LockDateInTicks, SessionInfo.LockAgeInSeconds, SessionInfo.LockCookie);
            }

            headers.AppendFormat("X-If-None-Exists: true\r\nExclusive: transfer\r\nTimeout: {0}\r\nExtraFlags: {1}\r\nLast-Modified: {2}\r\n", SessionInfo.Timeout, SessionInfo.ActionFlags, SessionInfo.UpdateDateInTicks);

            ResponseData rdata = new ResponseData(
                MergeResponseData(headers, Data, true, Service.Settings.EncryptPeerData, Service.Authenticator, connectedMsg.Socket.SessionKey),
                typeof(SetTransferRequest)
            );

            //Create new AsyncResultActions object to hold delegates for actions based on the outcome of the call
            AsyncResultActions<AsyncMessageTracker> asyncResults = new AsyncResultActions<AsyncMessageTracker>(connectedMsg);
            asyncResults.Result1Action = SuccessAction;
            asyncResults.Result2Action = FailAction;
            asyncResults.Result3Action = AlreadyExistsAction;
            asyncResults.Result4Action = PeerShuttingDownAction;
            asyncResults.TimeoutAction = TimeoutAction;

            Service.AsyncMessageRequests.Add(DateTime.UtcNow + Timeout, connectedMsg.ID, asyncResults);

            connectedMsg.Socket.Send(rdata);

            Diags.LogSend(connectedMsg.Socket, rdata);
        }
Esempio n. 32
0
        /// <summary>
        /// Initializes a new instance of the OKResponse class
        /// </summary>
        /// <param name="Data">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public OKResponse(HTTPPartialData Data, StateServer Service)
            : base(Data,Service)
        {
            string auth_info = headers["AUTHENTICATION-INFO"];

            if (auth_info != null)
            {
                //Split comma-delimited directives
                string[] directives = auth_info.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                //Read rspauth, qop, cnonce and ncount
                foreach (string line in directives)
                {

                    string key, value;
                    GetKeyValue(line, '=', out key, out value);

                    switch (key.ToUpperInvariant().Trim())
                    {
                        case "RSPAUTH":
                            authInfo_rspauth = Unquote(value).Trim();
                            if (!IsValidBase64(authInfo_rspauth)) authInfo_rspauth = null;
                            break;

                        case "QOP":
                            authInfo_qop = Unquote(value).Trim();
                            break;

                        case "CNONCE":
                            authInfo_cnonce = Unquote(value).Trim();
                            if (!IsValidBase64(authInfo_cnonce)) authInfo_cnonce = null;
                            break;

                        case "NC":
                            Int32.TryParse(Unquote(value), System.Globalization.NumberStyles.HexNumber, null, out authInfo_ncount);
                            break;
                    }

                }

            }

            //Validate
            if (!isError)
            {
                //If there is an authentication-info header and the rspauth, qop, or cnonce directive is missing,
                //then there is an error.
                if (auth_info != null && (authInfo_rspauth == null || authInfo_cnonce == null || authInfo_qop == null))
                {
                    isError = true;
                }
            }
        }
Esempio n. 33
0
        /// <summary>
        /// Initializes a new instance of the UnauthorizedResponse class
        /// </summary>
        /// <param name="Data">The HTTPPartialData class to load this instance from</param>
        /// <param name="Service">State server instance</param>
        public UnauthorizedResponse(HTTPPartialData Data, StateServer Service)
            : base(Data, Service)
        {
            string www_auth = headers["WWW-AUTHENTICATE"];

            if (www_auth != null)
            {
                //Split comma-delimited directives
                string[] directives = www_auth.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                //first check for and remove 'Digest' from the first line
                if (directives.Length > 0 && directives[0].Trim().ToUpperInvariant().StartsWith("DIGEST"))
                {
                    directives[0] = directives[0].Trim().Substring(6); //remove digest word

                    //Read realm, qop and nonce
                    foreach (string line in directives)
                    {
                        string key, value;
                        GetKeyValue(line, '=', out key, out value);

                        switch(key.ToUpperInvariant().Trim())
                        {
                            case "REALM":
                                realm = Unquote( value).Trim();
                                break;

                            case "QOP":
                                qop = Unquote( value).Trim();
                                break;

                            case "NONCE":
                                nonce = Unquote( value).Trim();
                                if (!IsValidBase64(nonce)) nonce = null;
                                break;
                        }

                    }

                }

            }

            //Validate
            if (!isError)
            {
                //This message requires an empty content-length, qop, nonce and realm
                if (body.Length != 0 || qop == null || nonce == null || realm == null)
                {
                    isError = true;
                }
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Sends a GetTransferMessage to a list of ServiceSockets and queues an Action to be called if the 
        /// requested session is transferred to this peer, and another Action to be called if no session is
        /// transferred after a set time.
        /// </summary>
        /// <param name="OriginHost">The Host name of the peer that originally initiated this message</param>
        /// <param name="sockets">List of target ServiceSockets</param>
        /// <param name="Service">Instance of state server</param>
        /// <param name="SessionKey">The requested session URI</param>
        /// <param name="MessageID">The unique message identifier</param>
        /// <param name="MaxForwards">The maximum number of nodes to forward the message to. This field is decremented by one for each forward</param>
        /// <param name="BroadcastID">The broadcast identifier. Used by peers to identify different broadcasts of the same message</param>
        /// <param name="TimeoutStamp">The Time in UTC, at which point the message query is considered timed out</param>
        /// <param name="FoundAction">The Action to be called if the requested session is transferred to this peer</param>
        /// <param name="TimeoutAction">The Action to be called if the requested session is not transferred to this peer after the TimeoutStamp time</param>
        public static void Broadcast(string OriginHost, List<ServiceSocket> sockets, StateServer Service, string SessionKey, 
            Guid MessageID, int MaxForwards, Guid BroadcastID, DateTime TimeoutStamp,
            Action<string> FoundAction, System.Threading.WaitCallback TimeoutAction)
        {
            if (sockets.Count == 0 || MaxForwards < 0) return;

            if (FoundAction != null && TimeoutAction != null)
            {
                if (Service.NewExpectedTransfer(SessionKey, FoundAction, TimeoutAction, TimeoutStamp) > 1)
                {
                    //There's no point broadcasting another GetTransferMessage since an Action has done this earlier
                    return;
                }
            }

            string msgID = MessageID.ToString("N");

            string format;
            if (BroadcastID != Guid.Empty)
            {
                format = "GET {0} HTTP/1.1\r\nHost: {1}\r\nX-ID: {2}\r\nExclusive: transfer\r\nX-Broadcast-ID: {3}\r\nMax-Forwards: {4}\r\n\r\n";
            }
            else
            {
                format = "GET {0} HTTP/1.1\r\nHost: {1}\r\nX-ID: {2}\r\nExclusive: transfer\r\nMax-Forwards: {4}\r\n\r\n";
            }

            byte[] formatted = Encoding.UTF8.GetBytes(String.Format(format, SessionKey, OriginHost, msgID, BroadcastID.ToString("N"), MaxForwards));

            //send message to all sockets in sockets list
            foreach (ServiceSocket socket in sockets)
            {
                ResponseData rdata = new ResponseData(formatted, typeof(GetTransferMessage));
                socket.Send(rdata);
                Diags.LogSend(socket, rdata);
            }
        }