private void Renew()
        {
            HTTPMessage request = new HTTPMessage();
            String WebIP;
            int WebPort;
            String Tag;
            String NT;

            NT = "Second-" + CurrentTimeout.ToString();

            SSDP.ParseURL(this.__eventurl, out WebIP, out WebPort, out Tag);
            IPEndPoint dest = new IPEndPoint(IPAddress.Parse(WebIP), WebPort);

            request.Directive = "SUBSCRIBE";
            request.DirectiveObj = Tag;
            request.AddTag("Host", WebIP + ":" + WebPort.ToString());
            request.AddTag("SID", CurrentSID);
            request.AddTag("Timeout", NT);

            HTTPRequest R = new HTTPRequest();
            R.OnResponse += new HTTPRequest.RequestHandler(RenewSink);
            this.SendEventTable[R] = R;
            R.PipelineRequest(dest, request, null);
        }
        private void HandleSubscribeResponse(HTTPRequest sender, HTTPMessage response, object Tag)
        {
            UPnPEventSubscribeHandler CB = (UPnPEventSubscribeHandler)Tag;
            SubscribeRequestTable.Remove(sender);
            sender.Dispose();
            if (response != null)
            {
                if (response.StatusCode != 200)
                {
                    if (CB != null)
                    {
                        CB(this, false);
                    }
                    else
                    {
                        if (OnSubscribe != null) OnSubscribe(this, false);
                    }
                }
                else
                {
                    CurrentSID = response.GetTag("SID");
                    if (CB != null)
                    {
                        CB(this, true);
                    }
                    else
                    {
                        if (OnSubscribe != null) OnSubscribe(this, true);
                    }

                    if (CurrentTimeout != 0)
                    {
                        EventLogger.Log(this, System.Diagnostics.EventLogEntryType.SuccessAudit, "SUBSCRIBE [" + this.CurrentSID + "] Duration: " + CurrentTimeout.ToString() + " <" + DateTime.Now.ToLongTimeString() + ">");
                        SubscribeCycle.Add(this.GetHashCode(), CurrentTimeout / 2);
                    }
                }
            }
            else
            {
                if (CB != null)
                {
                    CB(this, false);
                }
                else
                {
                    if (OnSubscribe != null) OnSubscribe(this, false);
                }
            }
        }
 private void HandleUnsubscribeResponse(HTTPRequest sender, HTTPMessage response, object Tag)
 {
     SubscribeRequestTable.Remove(sender);
     sender.Dispose();
     SubscribeCycle.Remove(this.GetHashCode());
 }
Exemplo n.º 4
0
 private void NonPipelinedResponseSink(HTTPRequest sender, HTTPMessage Response, object Tag)
 {
     //			OpenSource.Utilities.EventLogger.Log(sender.s,System.Diagnostics.EventLogEntryType.Information,"TryingToDispose");
     _Source = sender.Source;
     this.NotPipelinedTable.Remove(sender);
     sender.Dispose();
     if (this.OnResponse != null)
         OnResponse(this, Response, Tag);
 }
Exemplo n.º 5
0
 protected void PreProcessPlayList(HTTPRequest sender, HTTPMessage M, object Tag)
 {
     //			if(M!=null)
     //			{
     //				if(M.StatusCode==200)
     //				{
     //					M3U = M.StringBuffer;
     //				}
     //			}
     //			sender.Dispose();
     //			FetchTable.Remove(sender);
 }
 private void SniffSink(HTTPRequest sender, byte[] raw, int offset, int length)
 {
     OnSniffEvent.Fire(raw, offset, length);
 }
Exemplo n.º 7
0
 private void NonPipelinedSniffSink(HTTPRequest sender, byte[] buffer, int offset, int count)
 {
     if (OnSniff != null)
         OnSniff(this, buffer, offset, count);
 }
Exemplo n.º 8
0
        private void HandleWebRequest(HTTPMessage msg, HTTPSession WebSession)
        {
            DText parser = new DText();
            HTTPMessage Response = new HTTPMessage();
            HTTPMessage Response2 = null;
            String Method = msg.Directive;
            String MethodData = msg.DirectiveObj;

            if (WebSession.InternalStateObject != null)
            {
                HTTPMessage _msg = (HTTPMessage)msg.Clone();
                object[] state = (object[])WebSession.InternalStateObject;
                _msg.DirectiveObj = (string)state[1];
                VirtualDirectoryHandler t = (VirtualDirectoryHandler)state[2];
                WebSession.InternalStateObject = null;
                t(this, _msg, WebSession, (string)state[0]);
                return;

            }

            if ((Method != "GET") && (Method != "HEAD") && (Method != "POST") &&
                (Method != "SUBSCRIBE") && (Method != "UNSUBSCRIBE") &&
                (Method != "NOTIFY"))
            {
                Response.StatusCode = 405;
                Response.StatusData = Method + " not supported";
                WebSession.Send(Response);
                return; // Other methods are unknown to us
            }

            // Process Headers
            if (Method == "GET" || Method == "HEAD")
            {
                try
                {
                    Response = Get(MethodData, WebSession.Source);
                }
                catch (UPnPCustomException ce)
                {
                    OpenSource.Utilities.EventLogger.Log(ce);
                    Response.StatusCode = ce.ErrorCode;
                    Response.StatusData = ce.ErrorDescription;
                    WebSession.Send(Response);
                    return;
                }
                catch (Exception e)
                {
                    OpenSource.Utilities.EventLogger.Log(e);
                    Response.StatusCode = 500;
                    Response.StatusData = "Internal";
                    Response.StringBuffer = e.ToString();
                }
                if (Method == "HEAD")
                {
                    Response.BodyBuffer = null;
                }
                WebSession.Send(Response);
            }

            if (Method == "POST")
            {
                //InvokerInfo[Thread.CurrentThread.GetHashCode()] = WebSession;
                try
                {
                    Response = Post(MethodData, msg.StringBuffer, msg.GetTag("SOAPACTION"), WebSession);
                }
                catch (DelayedResponseException ex)
                {
                    OpenSource.Utilities.EventLogger.Log(ex);
                    InvokerInfo.Remove(Thread.CurrentThread.GetHashCode());
                    WebSession.StopReading();
                    return;
                }
                catch (UPnPCustomException ce)
                {
                    OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "UPnP Error [" + ce.ErrorCode.ToString() + "] " + ce.ErrorDescription);
                    Response.StatusCode = 500;
                    Response.StatusData = "Internal";
                    Response.StringBuffer = BuildErrorBody(ce);
                    WebSession.Send(Response);
                    InvokerInfo.Remove(Thread.CurrentThread.GetHashCode());
                    return;
                }
                catch (UPnPInvokeException ie)
                {
                    Response.StatusCode = 500;
                    Response.StatusData = "Internal";
                    if (ie.UPNP != null)
                    {
                        OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "UPnP Error [" + ie.UPNP.ErrorCode.ToString() + "] " + ie.UPNP.ErrorDescription);
                        Response.StringBuffer = BuildErrorBody(ie.UPNP);
                    }
                    else
                    {
                        OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "UPnP Invocation Error [" + ie.MethodName + "] " + ie.Message);
                        Response.StringBuffer = BuildErrorBody(new UPnPCustomException(500, ie.Message));
                    }
                    WebSession.Send(Response);
                    InvokerInfo.Remove(Thread.CurrentThread.GetHashCode());
                    return;
                }
                catch (UPnPTypeMismatchException tme)
                {
                    OpenSource.Utilities.EventLogger.Log(tme);
                    Response.StatusCode = 500;
                    Response.StatusData = "Internal";
                    Response.StringBuffer = BuildErrorBody(new UPnPCustomException(402, tme.Message));
                    WebSession.Send(Response);
                    InvokerInfo.Remove(Thread.CurrentThread.GetHashCode());
                    return;
                }
                catch (UPnPStateVariable.OutOfRangeException oor)
                {
                    OpenSource.Utilities.EventLogger.Log(oor);
                    Response.StatusCode = 500;
                    Response.StatusData = "Internal";
                    Response.StringBuffer = BuildErrorBody(new UPnPCustomException(402, oor.Message));
                    WebSession.Send(Response);
                    InvokerInfo.Remove(Thread.CurrentThread.GetHashCode());
                    return;
                }
                catch (System.Reflection.TargetInvocationException tie)
                {
                    Exception inner = tie.InnerException;
                    OpenSource.Utilities.EventLogger.Log(tie);
                    while (inner.InnerException != null && (typeof(UPnPCustomException).IsInstanceOfType(inner) == false))
                    {
                        inner = inner.InnerException;
                    }
                    if (typeof(UPnPCustomException).IsInstanceOfType(inner))
                    {
                        UPnPCustomException ce = (UPnPCustomException)inner;
                        OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "UPnP Error [" + ce.ErrorCode.ToString() + "] " + ce.ErrorDescription);
                        Response.StatusCode = 500;
                        Response.StatusData = "Internal";
                        Response.StringBuffer = BuildErrorBody(ce);
                        WebSession.Send(Response);
                        InvokerInfo.Remove(Thread.CurrentThread.GetHashCode());
                        return;
                    }
                    else
                    {
                        Response.StatusCode = 500;
                        Response.StatusData = "Internal";
                        Response.StringBuffer = BuildErrorBody(new UPnPCustomException(500, inner.ToString()));
                        WebSession.Send(Response);
                        OpenSource.Utilities.EventLogger.Log(inner);
                        return;
                    }
                }
                catch (Exception e)
                {
                    Response.StatusCode = 500;
                    Response.StatusData = "Internal";
                    Response.StringBuffer = BuildErrorBody(new UPnPCustomException(500, e.ToString()));
                    WebSession.Send(Response);
                    OpenSource.Utilities.EventLogger.Log(e);
                    return;
                }

                WebSession.Send(Response);
                InvokerInfo.Remove(Thread.CurrentThread.GetHashCode());
                return;
            }

            if (Method == "SUBSCRIBE")
            {
                String SID = msg.GetTag("SID");
                String NT = msg.GetTag("NT");
                String Timeout = msg.GetTag("Timeout");
                String CallbackURL = msg.GetTag("Callback");
                if (Timeout == "")
                {
                    Timeout = "7200"; // Default  = 2 Hours
                }
                else
                {
                    Timeout = Timeout.Substring(Timeout.IndexOf("-") + 1).Trim().ToUpper();
                    if (Timeout == "INFINITE")
                    {
                        Timeout = "0";
                    }
                }
                if (SID != "")
                {
                    // Renew
                    RenewEvents(MethodData.Substring(1), SID, Timeout);
                }
                else
                {
                    // Subscribe
                    try
                    {
                        Response2 = SubscribeEvents(ref SID, MethodData.Substring(1), CallbackURL, Timeout);
                    }
                    catch (Exception s_exception)
                    {
                        OpenSource.Utilities.EventLogger.Log(s_exception);
                        HTTPMessage err = new HTTPMessage();
                        err.StatusCode = 500;
                        err.StatusData = s_exception.Message;
                        WebSession.Send(err);
                        return;
                    }
                }
                if (Timeout == "0")
                {
                    Timeout = "Second-infinite";
                }
                else
                {
                    Timeout = "Second-" + Timeout;
                }
                Response.StatusCode = 200;
                Response.StatusData = "OK";
                Response.AddTag("Server", "Windows NT/5.0, UPnP/1.0");
                Response.AddTag("SID", SID);
                Response.AddTag("Timeout", Timeout);
                WebSession.Send(Response);
                if (Response2 != null)
                {
                    Uri[] cbURL = ParseEventURL(CallbackURL);
                    for (int x = 0; x < cbURL.Length; ++x)
                    {
                        Response2.DirectiveObj = HTTPMessage.UnEscapeString(cbURL[x].PathAndQuery);
                        Response2.AddTag("Host", cbURL[x].Host + ":" + cbURL[x].Port.ToString());

                        IPEndPoint d = new IPEndPoint(IPAddress.Parse(cbURL[x].Host), cbURL[x].Port);
                        HTTPRequest R = new HTTPRequest();
                        R.OnResponse += new HTTPRequest.RequestHandler(HandleInitialEvent);
                        this.InitialEventTable[R] = R;
                        R.PipelineRequest(d, Response2, null);
                    }
                }
            }

            if (Method == "UNSUBSCRIBE")
            {
                CancelEvent(MethodData.Substring(1), msg.GetTag("SID"));
                Response.StatusCode = 200;
                Response.StatusData = "OK";
                WebSession.Send(Response);
            }
        }
        /// <summary>
        /// Subscribe to UPnPEvents
        /// </summary>
        /// <param name="Timeout">Subscription Cycle</param>
        public void Subscribe(int Timeout, UPnPEventSubscribeHandler CB)
        {
            bool processSubscribe = false;
            lock (SubscribeLock)
            {
                if (SubscribeCounter == 0) processSubscribe = true;
                ++SubscribeCounter;
                //OnUPnPEvent += UPnPEventCallback;
            }

            if (processSubscribe == false)
            {
                // Already subscribed... Just trigger Events
                foreach (UPnPStateVariable V in this.GetStateVariables()) V.InitialEvent();
                if (CB != null) CB(this, true);
                return;
            }

            foreach (UPnPStateVariable V in this.GetStateVariables())
            {
                if (V.SendEvent) V.CurrentValue = null;
            }

            CurrentTimeout = Timeout;

            HTTPMessage request = new HTTPMessage();
            String WebIP;
            int WebPort;
            String Tag;
            String NT;
            if (Timeout == 0)
            {
                NT = "Second-infinite";
            }
            else
            {
                NT = "Second-" + Timeout.ToString();
            }

            SSDP.ParseURL(this.__eventurl, out WebIP, out WebPort, out Tag);
            IPEndPoint dest = new IPEndPoint(IPAddress.Parse(WebIP), WebPort);
            IPAddress addr = IPAddress.Parse(WebIP);

            request.Directive = "SUBSCRIBE";
            request.DirectiveObj = Tag;
            if (addr.AddressFamily == AddressFamily.InterNetwork)
            {
                request.AddTag("Host", WebIP + ":" + WebPort.ToString());
            }
            else if (addr.AddressFamily == AddressFamily.InterNetworkV6)
            {
                request.AddTag("Host", "[" + RemoveIPv6Scope(addr.ToString()) + "]:" + WebPort.ToString());
            }
            request.AddTag("Callback", "<" + this.EventCallbackURL + ">");
            request.AddTag("NT", "upnp:event");
            request.AddTag("Timeout", NT);

            HTTPRequest SR = new HTTPRequest();
            SubscribeRequestTable[SR] = SR;
            SR.OnResponse += new HTTPRequest.RequestHandler(HandleSubscribeResponse);
            SR.PipelineRequest(dest, request, CB);
        }
        public override void Start(UPnPDevice device)
        {
            if(!Enabled) return;

            UPnPDevice dv = device;
            while(dv.ParentDevice!=null)
            {
                dv = dv.ParentDevice;
            }

            state = UPnPTestStates.Running;
            UPnPService[] _S = device.GetServices("urn:");

            foreach(UPnPService s in _S)
            {
                bool ok = false;
                foreach(UPnPStateVariable v in s.GetStateVariables())
                {
                    if(v.SendEvent)
                    {
                        ok = true;
                        break;
                    }
                }
                if(ok)
                {

                    UPnPDebugObject d = new UPnPDebugObject(s);
                    Uri EventUri = new Uri((string)d.GetField("__eventurl"));

                    IPEndPoint dest = new IPEndPoint(IPAddress.Parse(EventUri.Host),EventUri.Port);
                    HTTPMessage R = new HTTPMessage();
                    R.Directive = "SUBSCRIBE";
                    R.DirectiveObj = HTTPMessage.UnEscapeString(EventUri.PathAndQuery);
                    R.AddTag("Host",dest.ToString());
                    R.AddTag("Callback","<http://" + dv.InterfaceToHost.ToString()+ ":" + NetworkInfo.GetFreePort(10000,50000,dv.InterfaceToHost).ToString() + ">");
                    //R.AddTag("Callback","<http://127.0.0.1:55555>");
                    R.AddTag("NT","upnp:event");
                    R.AddTag("Timeout","Second-15");

                    System.Console.WriteLine(R.GetTag("Callback"));

                    MRE.Reset();
                    SID = "";
                    StartCountDown(30);
                    HTTPRequest rq = new HTTPRequest();
                    rq.OnResponse += new HTTPRequest.RequestHandler(SubscribeSink);

                    AddHTTPMessage(R);

                    rq.PipelineRequest(dest,R,s);
                    MRE.WaitOne(30000,false);
                    AbortCountDown();

                    if (SID=="")
                    {
                        AddEvent(LogImportance.Critical,"Subscribe","SUBSCRIBE: " + s.ServiceURN + " << FAILED >>");
                        AddEvent(LogImportance.Remark,"Subscribe","Aborting tests");

                        result = "Subscription test failed."; // TODO
                        state = UPnPTestStates.Failed;
                        return;
                    }
                    else
                    {
                        AddEvent(LogImportance.Remark,"Subscribe","SUBSCRIBE: " + s.ServiceURN + " << OK >>");

                        // Renew Test
                        R = new HTTPMessage();
                        R.Directive = "SUBSCRIBE";
                        R.DirectiveObj = HTTPMessage.UnEscapeString(EventUri.PathAndQuery);
                        R.AddTag("Host",dest.ToString());
                        R.AddTag("SID",SID);
                        R.AddTag("Timeout","Second-15");
                        StartCountDown(30);
                        SID = "";
                        MRE.Reset();

                        AddHTTPMessage(R);

                        rq = new HTTPRequest();
                        rq.OnResponse += new HTTPRequest.RequestHandler(SubscribeSink);
                        rq.PipelineRequest(dest,R,s);

                        MRE.WaitOne(30000,false);
                        AbortCountDown();

                        if (SID=="")
                        {
                            AddEvent(LogImportance.Critical,"Subscribe","SUBSCRIBE (Renew): " + s.ServiceURN + " << FAILED >>");
                            AddEvent(LogImportance.Remark,"Subscribe","Aborting tests");

                            result = "Subscription test failed."; // TODO
                            state = UPnPTestStates.Failed;
                            return;
                        }
                        else
                        {
                            AddEvent(LogImportance.Remark,"Subscribe","SUBSCRIBE (Renew): " + s.ServiceURN + " << OK >>");

                            // Cancel
                            R = new HTTPMessage();
                            R.Directive = "UNSUBSCRIBE";
                            R.DirectiveObj = HTTPMessage.UnEscapeString(EventUri.PathAndQuery);
                            R.AddTag("Host",dest.ToString());
                            R.AddTag("SID",SID);

                            StartCountDown(30);
                            SID = "";
                            MRE.Reset();
                            rq = new HTTPRequest();
                            rq.OnResponse += new HTTPRequest.RequestHandler(CancelSink);

                            AddHTTPMessage(R);

                            rq.PipelineRequest(dest,R,s);

                            MRE.WaitOne(30000,false);
                            AbortCountDown();

                            if (SID=="")
                            {
                                AddEvent(LogImportance.Critical,"Subscribe","UNSUBSCRIBE: " + s.ServiceURN + " << FAILED >>");
                                AddEvent(LogImportance.Remark,"Subscribe","Aborting tests");

                                result = "Subscription test failed.";
                                state = UPnPTestStates.Failed;
                                return;
                            }
                            else
                            {
                                AddEvent(LogImportance.Remark,"Subscribe","UNSUBSCRIBE: " + s.ServiceURN + " << OK >>");
                            }

                            /* Test for duplicate SID
                             * as well as initial events */

                            EventTable.Clear();
                            NumEvents = 0;
                            foreach(UPnPStateVariable V in s.GetStateVariables())
                            {
                                if(V.SendEvent)
                                {
                                    ++ NumEvents;
                                    EventTable[V.Name] = false;
                                    V.OnModified -= new UPnPStateVariable.ModifiedHandler(StateVarModifiedSink);
                                    V.OnModified += new UPnPStateVariable.ModifiedHandler(StateVarModifiedSink);
                                }
                            }
                            if(EventTable.Count>0)
                            {
                                MRE.Reset();
                                s.OnSubscribe -= new UPnPService.UPnPEventSubscribeHandler(OnSubscribeSink);
                                s.OnSubscribe += new UPnPService.UPnPEventSubscribeHandler(OnSubscribeSink);
                                s.UnSubscribe(null);
                                foreach(UPnPStateVariable V in s.GetStateVariables())
                                {
                                    V.Clear();
                                }
                                s.Subscribe(120,null);
                                MRE.WaitOne(30000,false);
                                if(SID=="")
                                {
                                    // Subscribe Failed
                                    AddEvent(LogImportance.Critical,"Subscribe","SUBSCRIBE(2): " + s.ServiceURN + " << FAILED >>");
                                    AddEvent(LogImportance.Remark,"Subscribe","Aborting tests");

                                    result = "Subscription test failed.";
                                    state = UPnPTestStates.Failed;
                                    return;
                                }
                                else
                                {
                                    if(SID==null)
                                    {
                                        // Duplicate SID
                                        // Subscribe Failed
                                        AddEvent(LogImportance.Critical,"Subscribe","SUBSCRIBE(2): " + s.ServiceURN + " << FAILED, duplicate SID >>");
                                        AddEvent(LogImportance.Remark,"Subscribe","Aborting tests");

                                        result = "Subscription test failed.";
                                        state = UPnPTestStates.Failed;
                                        return;
                                    }
                                    else
                                    {
                                        // Check Hashtable
                                        IDictionaryEnumerator de = EventTable.GetEnumerator();
                                        bool OK = true;
                                        while(de.MoveNext())
                                        {
                                            if((bool)de.Value==false)
                                            {
                                                // No Event Received
                                                OK = false;
                                                AddEvent(LogImportance.Critical,"Subscribe","   StateVariable: " + (string)de.Key + " >> Event NOT received");
                                            }
                                            else
                                            {
                                                // OK
                                                AddEvent(LogImportance.Remark,"Subscribe","   StateVariable: " + (string)de.Key + " >> Event OK");
                                            }
                                        }
                                        if(OK==false)
                                        {
                                            AddEvent(LogImportance.Critical,"Subscribe","SUBSCRIBE(2): " + s.ServiceURN + " << FAILED, Did not receive all events >>");
                                            AddEvent(LogImportance.Remark,"Subscribe","Aborting tests");

                                            result = "Subscription test failed.";
                                            state = UPnPTestStates.Failed;
                                            return;
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }

            result = "Subscribe Tests OK";
            state = UPnPTestStates.Pass;
        }
Exemplo n.º 11
0
 private void HandleInitialEvent(HTTPRequest R, HTTPMessage M, object Tag)
 {
     R.Dispose();
     this.InitialEventTable.Remove(R);
 }
        private void SubscribeSink(HTTPRequest sender, HTTPMessage MSG, object Tag)
        {
            if (MSG!=null)
            {
                AddPacket(MSG);

                if (MSG.StatusCode==200)
                {
                    SID = MSG.GetTag("SID");
                }
            }
            MRE.Set();
        }
        private void CancelSink(HTTPRequest sender, HTTPMessage MSG, object Tag)
        {
            if (MSG!=null)
            {
                AddPacket(MSG);

                if (MSG.StatusCode==200)
                {
                    SID = "CANCELED";
                }
            }
            MRE.Set();
        }
Exemplo n.º 14
0
        protected void Sink_AcquireAndSetPlaylist(HTTPRequest sender, HTTPMessage M, object Tag)
        {
            AVConnection avc = (AVConnection)Tag;

            lock (this.m_LockRequest)
            {
                if (this.m_LastRequest == sender)
                {
                    this.m_LastRequest = null;

                    if (M != null)
                    {
                        if (M.StatusCode == 200)
                        {
                            // The URI had a response.
                            // If the URI is for an M3U, then strip out the lines that
                            // begin with # and save to a local file so that mediaplayer
                            // uses the local file because it can't handle extended M3U.
                            string uri = ((string)(this.PlaylistRequests[sender]));

                            if (
                                (M.ContentType.IndexOf("audio/mpegurl") > 0) ||
                                (uri.EndsWith(".m3u"))
                                )
                            {
                                DText dt = new DText();
                                dt.ATTRMARK = "\n";
                                dt[0] = M.StringBuffer;

                                StringBuilder plainM3U = new StringBuilder(M.StringBuffer.Length);
                                StringBuilder metadata = new StringBuilder(M.StringBuffer.Length);

                                bool expectingTrackUri = false;

                                string comment = "";
                                string trackUri = "";
                                for (int i = 1; i <= dt.DCOUNT(); i++)
                                {
                                    string line = dt[i].Trim();
                                    //string lower = line.ToLower();

                                    if ((expectingTrackUri) && (line.StartsWith("#")))
                                    {
                                        // expecting URI and got another comment
                                        // TASK: overwrite comment
                                        comment = line;
                                    }
                                    else if ((expectingTrackUri == false) && (line.StartsWith("#")))
                                    {
                                        if (i == 1)
                                        {
                                            expectingTrackUri = false;
                                        }
                                        else
                                        {
                                            // expecting comment and got another comment
                                            // TASK: save comment
                                            comment = line;
                                            expectingTrackUri = true;
                                        }
                                    }
                                    else if ((expectingTrackUri) && (line.StartsWith("#") == false) && (line != ""))
                                    {
                                        // expecting URI and got a URI
                                        // TASK: write comment and URI to stringbuffers

                                        trackUri = line;
                                        metadata.AppendFormat("{0}\n", comment);
                                        plainM3U.AppendFormat("{0}\n", trackUri);

                                        comment = null;
                                        trackUri = null;
                                        expectingTrackUri = false;
                                    }
                                    else if ((expectingTrackUri == false) && (line.StartsWith("#") == false) && (line != ""))
                                    {
                                        // expecting comment and got a URI
                                        // TASK: write empty comment and URI to stringbuffers
                                        trackUri = line;
                                        int slashPos = line.LastIndexOf("/");
                                        int queryPos = line.LastIndexOf("?");

                                        if (slashPos < queryPos)
                                        {
                                            int len = queryPos - slashPos - 1;
                                            comment = line.Substring(slashPos + 1, len);
                                        }
                                        else
                                        {
                                            comment = line.Substring(slashPos + 1);
                                        }

                                        metadata.AppendFormat("#EXTINF:-1,{0}\n", comment);
                                        plainM3U.AppendFormat("{0}\n", trackUri);

                                        comment = null;
                                        trackUri = null;
                                        expectingTrackUri = false;
                                    }
                                }

                                string guid = Guid.NewGuid().ToString();

                                string tfn = guid + ".m3u";
                                this.m_TFC.AddFile(tfn, false);
                                StreamWriter sw = System.IO.File.CreateText(tfn);
                                sw.Write(plainM3U);
                                sw.Flush();
                                sw.Close();
                                this.m_M3U = plainM3U.ToString();
                                this.m_PlainM3U[uri] = tfn;

                                string mfn = guid + ".md";
                                this.m_TFC.AddFile(mfn, false);
                                sw = System.IO.File.CreateText(mfn);
                                sw.Write(metadata);
                                sw.Flush();
                                sw.Close();
                                this.m_METADATA = metadata.ToString();
                                this.m_Metadata[uri] = mfn;

                                //player.FileName = tfn;
                                player.openPlayer(tfn);
                                DetermineMediaDuration(this.m_METADATA);
                            }
                            else
                            {
                                //player.Open(avc.CurrentURI.AbsoluteUri);
                                player.openPlayer(avc.CurrentURI.AbsoluteUri);
                                this.m_M3U = avc.CurrentURI.AbsoluteUri;
                                this.m_METADATA = "";
                                DetermineMediaDuration(this.m_METADATA);
                            }
                        }
                    }
                }
            }

            this.PlaylistRequests.Remove(sender);
            sender.Dispose();
        }
Exemplo n.º 15
0
        private void RenewSink(HTTPRequest sender, HTTPMessage M, object Tag)
        {
            if (M != null)
            {
                if (M.StatusCode != 200)
                {
                    // Renew Failed
                    EventLogger.Log(this, System.Diagnostics.EventLogEntryType.SuccessAudit, "Renewal [" + this.CurrentSID + "] Error:" + M.StatusCode.ToString() + " <" + DateTime.Now.ToLongTimeString() + ">");

                    SubscribeCycle.Remove(this.GetHashCode());
                    this.SubscribeCounter = 0;
                    PeriodicRenewFailedEvent.Fire(this);
                }
                else
                {
                    EventLogger.Log(this, System.Diagnostics.EventLogEntryType.SuccessAudit, "Renewal [" + this.CurrentSID + "] OK <" + DateTime.Now.ToLongTimeString() + ">");
                    SubscribeCycle.Add(this.GetHashCode(), CurrentTimeout / 2);
                }
            }
            else
            {
                // Renew Failed
                EventLogger.Log(this, System.Diagnostics.EventLogEntryType.SuccessAudit, "Renewal [" + this.CurrentSID + "] DeviceError <" + DateTime.Now.ToLongTimeString() + ">");

                SubscribeCycle.Remove(this.GetHashCode());
                this.SubscribeCounter = 0;
                PeriodicRenewFailedEvent.Fire(this);
            }
            this.SendEventTable.Remove(sender);
            sender.Dispose();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Unsubscribe to UPnPEvent
        /// </summary>
        /// <param name="cb"></param>
        public void UnSubscribe(UPnPEventHandler cb)
        {
            bool processUnSubscribe = false;

            lock (SubscribeLock)
            {
                --SubscribeCounter;
                if (SubscribeCounter <= 0)
                {
                    SubscribeCounter = 0;
                    processUnSubscribe = true;
                }
                if (cb == null)
                {
                    processUnSubscribe = true;
                    OnUPnPEvent = null;
                }
                else
                {
                    OnUPnPEvent -= cb;
                }
            }

            if (processUnSubscribe == false) return;

            HTTPMessage request = new HTTPMessage();
            String WebIP;
            int WebPort;
            String Tag;

            SSDP.ParseURL(this.__eventurl, out WebIP, out WebPort, out Tag);
            IPEndPoint dest = new IPEndPoint(IPAddress.Parse(WebIP), WebPort);

            request.Directive = "UNSUBSCRIBE";
            request.DirectiveObj = Tag;
            request.AddTag("Host", WebIP + ":" + WebPort.ToString()); // WebIP is already formatted for IPv6
            request.AddTag("SID", CurrentSID);

            HTTPRequest UR = new HTTPRequest();
            SubscribeRequestTable[UR] = UR;
            UR.OnResponse += new HTTPRequest.RequestHandler(HandleUnsubscribeResponse);
            CurrentSID = "";
            UR.PipelineRequest(dest, request, null);
        }
Exemplo n.º 17
0
 private void SniffPacketSink(HTTPRequest sender, HTTPMessage MSG, object Tag)
 {
     OnSniffPacketEvent.Fire(this, MSG);
 }
Exemplo n.º 18
0
        internal void SendEvents(UPnPStateVariable V)
        {
            //IDictionaryEnumerator en = SubscriberTable.GetEnumerator();
            SubscriberInfo sinfo;
            HTTPMessage Packet;
            Uri[] EventURLS;
            ICollection en = SubscriberTable.Keys;
            String[] KEYS = new String[en.Count];
            HTTPRequest R;
            en.CopyTo(KEYS, 0);

            for (int keyid = 0; keyid < KEYS.Length; ++keyid)
            {
                object _tobj = SubscriberTable[KEYS[keyid]];
                if (_tobj != null)
                {
                    sinfo = (SubscriberInfo)_tobj;
                    if ((sinfo.Expires > DateTime.Now.Ticks) || (sinfo.Expires == -1))
                    {
                        EventURLS = ParseEventURL(sinfo.CallbackURL);
                        for (int x = 0; x < EventURLS.Length; ++x)
                        {
                            try
                            {
                                IPAddress dest = IPAddress.Parse(EventURLS[x].Host);

                                Packet = new HTTPMessage();
                                Packet.Directive = "NOTIFY";
                                Packet.AddTag("Content-Type", "text/xml");
                                Packet.AddTag("NT", "upnp:event");
                                Packet.AddTag("NTS", "upnp:propchange");
                                Packet.BodyBuffer = BuildEventXML(new UPnPStateVariable[1] { V });
                                Packet.DirectiveObj = HTTPMessage.UnEscapeString(EventURLS[x].PathAndQuery);
                                if (dest.AddressFamily == AddressFamily.InterNetwork) Packet.AddTag("Host", EventURLS[x].Host + ":" + EventURLS[x].Port.ToString());
                                if (dest.AddressFamily == AddressFamily.InterNetworkV6) Packet.AddTag("Host", "[" + RemoveIPv6Scope(EventURLS[x].Host) + "]:" + EventURLS[x].Port.ToString());
                                Packet.AddTag("SID", sinfo.SID);
                                Packet.AddTag("SEQ", sinfo.SEQ.ToString());
                                Packet.AddTag("CONNECTION", "close");
                                ++sinfo.SEQ;
                                SubscriberTable[KEYS[keyid]] = sinfo;

                                //OpenSource.Utilities.EventLogger.Log(this,System.Diagnostics.EventLogEntryType.SuccessAudit,Packet.StringBuffer);

                                R = new HTTPRequest();
                                SendEventTable[R] = R;
                                R.OnResponse += new HTTPRequest.RequestHandler(HandleSendEvent);
                                R.PipelineRequest(new IPEndPoint(IPAddress.Parse(EventURLS[x].Host), EventURLS[x].Port), Packet, null);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    else
                    {
                        SubscriberTable.Remove(sinfo.SID);
                    }
                }
            }
        }
Exemplo n.º 19
0
        private void ContinueRequest(IPEndPoint dest, string PQ, object Tag, HTTPMessage MSG)
        {
            HTTPMessage r = null;
            if (MSG == null)
            {
                r = new HTTPMessage();
                r.Directive = "GET";
                r.DirectiveObj = PQ;
                if (dest.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) r.AddTag("Host", dest.ToString());
                if (dest.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) r.AddTag("Host", "[" + RemoveIPv6Scope(dest.ToString()) + "]");
            }
            else
            {
                r = MSG;
            }

            lock (TagQueue)
            {
                this.IdleTimeout = false;
                KeepAliveTimer.Remove(this.GetHashCode());

                LastMessage = r;
                if ((PIPELINE == false && _PIPELINE == false) || (_PIPELINE == false))
                {
                    HTTPRequest TR = new HTTPRequest();
                    TR.ProxySetting = ProxySetting;
                    TR._PIPELINE = true;
                    if (this.OnSniff != null) TR.OnSniff += new HTTPRequest.SniffHandler(NonPipelinedSniffSink);
                    if (this.OnSniffPacket != null) TR.OnSniffPacket += new HTTPRequest.RequestHandler(NonPipelinedSniffPacketSink);
                    TR.OnResponse += new HTTPRequest.RequestHandler(NonPipelinedResponseSink);
                    this.NotPipelinedTable[TR] = TR;
                    TR.PipelineRequest(dest, r, Tag);
                    return;
                }

                bool NeedSend = (TagQueue.Count == 0);
                TagQueue.Enqueue(new StateData(r, dest, Tag, null));

                IPAddress localif = IPAddress.Any;
                if (dest.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) localif = IPAddress.IPv6Any;

                if (s == null)
                {
                    ReceivedFirstResponse = false;
                    if (ProxySetting != null)
                    {
                        s = new HTTPSession(new IPEndPoint(localif, 0),
                            ProxySetting,
                            new HTTPSession.SessionHandler(CreateSink),
                            new HTTPSession.SessionHandler(CreateFailedSink),
                            null);
                    }
                    else
                    {
                        s = new HTTPSession(new IPEndPoint(localif, 0),
                            dest,
                            new HTTPSession.SessionHandler(CreateSink),
                            new HTTPSession.SessionHandler(CreateFailedSink),
                            null);
                    }
                }
                else
                {
                    if (s.IsConnected && this.ReceivedFirstResponse)
                    {
                        try
                        {
                            if (ProxySetting == null)
                            {
                                s.Send(r);
                            }
                            else
                            {
                                HTTPMessage pr = (HTTPMessage)r.Clone();
                                pr.DirectiveObj = "http://" + dest.ToString() + pr.DirectiveObj;
                                pr.Version = "1.0";
                                s.Send(pr);
                            }
                        }
                        catch (Exception ex)
                        {
                            OpenSource.Utilities.EventLogger.Log(ex);
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
        private void HandleInvokeRequest(HTTPRequest sender, HTTPMessage response, object Tag)
        {
            AsyncInvokeInfo state = (AsyncInvokeInfo)Tag;

            if (response == null)
            {
                if (state.ErrorCB != null)
                {
                    state.ErrorCB(this, state.MethodName, state.Args, new UPnPInvokeException(state.MethodName, state.Args, "Could not connect to device"), state.Tag);
                }
                else
                {
                    if (OnInvokeError != null)
                    {
                        OnInvokeError(this, state.MethodName, state.Args, new UPnPInvokeException(state.MethodName, state.Args, "Could not connect to device"), state.Tag);
                    }
                }
                return;
            }

            if (response.StatusCode == 100)
            {
                // Ignore
                return;
            }

            UPnPAction action = (UPnPAction)RemoteMethods[state.MethodName];
            if (response.StatusCode != 200)
            {
                if ((OnInvokeError != null) || (state.ErrorCB != null))
                {
                    if ((response.StatusCode == 500) && (response.BodyBuffer.Length > 0))
                    {
                        // Try to parse SOAP Encoded Error
                        UPnPCustomException ce = null;
                        try
                        {
                            ce = ParseErrorBody(response.StringBuffer);
                            OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error,
                                "UPnP Action <" + state.MethodName + "> Error [" + ce.ErrorCode.ToString() + "] " + ce.ErrorDescription);
                        }
                        catch
                        {
                            ce = null;
                            OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error,
                                "HTTP Fault invoking " + state.MethodName + " : " + response.StatusData);

                        }
                        if (state.ErrorCB != null)
                        {
                            state.ErrorCB(this, action.Name, state.Args, new UPnPInvokeException(state.MethodName, state.Args, response.StatusData, ce), state.Tag);
                        }
                        else
                        {
                            if (OnInvokeError != null)
                            {
                                OnInvokeError(this, action.Name, state.Args, new UPnPInvokeException(state.MethodName, state.Args, response.StatusData, ce), state.Tag);
                            }
                        }
                    }
                    else
                    {
                        if (state.ErrorCB != null)
                        {
                            state.ErrorCB(this, action.Name, state.Args, new UPnPInvokeException(state.MethodName, state.Args, response.StatusData), state.Tag);
                        }
                        else
                        {
                            if (OnInvokeError != null)
                            {
                                OnInvokeError(this, action.Name, state.Args, new UPnPInvokeException(state.MethodName, state.Args, response.StatusData), state.Tag);
                            }
                        }
                    }
                }
                return;
            }

            //Lets Parse the data we got back
            //Now we can parse the XML Body

            StringReader MyString = new StringReader(response.StringBuffer.Trim());
            XmlTextReader XMLDoc = new XmlTextReader(MyString);

            String MethodTag = "";
            UPnPArgument VarArg;
            ArrayList VarList = new ArrayList();

            XMLDoc.Read();
            XMLDoc.MoveToContent();
            if (XMLDoc.LocalName == "Envelope")
            {
                XMLDoc.Read();
                XMLDoc.MoveToContent();

                if (XMLDoc.LocalName == "Body")
                {
                    XMLDoc.Read();
                    XMLDoc.MoveToContent();

                    MethodTag = XMLDoc.LocalName;

                    XMLDoc.Read();
                    XMLDoc.MoveToContent();
                    if (XMLDoc.LocalName != "Body")
                    {
                        while ((XMLDoc.LocalName != MethodTag) && (XMLDoc.EOF == false))
                        {
                            //							VarArg = new UPnPArgument(XMLDoc.Name,UPnPStringFormatter.UnEscapeString(XMLDoc.ReadInnerXml()));
                            VarArg = new UPnPArgument(XMLDoc.Name, XMLDoc.ReadString());

                            VarList.Add(VarArg);

                            if ((!XMLDoc.IsStartElement() && XMLDoc.LocalName != MethodTag) || XMLDoc.IsEmptyElement)
                            {
                                XMLDoc.Read();
                                XMLDoc.MoveToContent();
                            }
                        }
                    }
                }
            }

            //Finished processing the SOAP, lets build the return list
            Object RetVal = null;
            UPnPArgument[] InVarArr = state.Args;
            UPnPArgument ThisArg;
            Object[] temp = new Object[1];
            Type[] TypeParm = new Type[1];
            TypeParm[0] = Type.GetType("System.String");
            int StartIDX = 0;
            if (((UPnPAction)RemoteMethods[state.MethodName]).HasReturnValue == true)
            {
                UPnPArgument RetArg = action.GetArg(((UPnPArgument)VarList[0]).Name);
                Type RetType = RetArg.RelatedStateVar.GetNetType();
                RetVal = CreateObjectInstance(RetType,
                    (string)((UPnPArgument)VarList[0]).DataValue);
                StartIDX = 1;
            }

            for (int ID = StartIDX; ID < VarList.Count; ++ID)
            {
                for (int ix = 0; ix < InVarArr.Length; ++ix)
                {
                    if (InVarArr[ix].Name == ((UPnPArgument)VarList[ID]).Name)
                    {
                        ThisArg = action.GetArg(InVarArr[ix].Name);
                        if ((ThisArg.RelatedStateVar.GetNetType().FullName != "System.String") ||
                            (ThisArg.RelatedStateVar.GetNetType().FullName != "System.Object"))
                        {
                            InVarArr[ix].DataValue = CreateObjectInstance(ThisArg.RelatedStateVar.GetNetType(), (string)((UPnPArgument)VarList[ID]).DataValue);
                        }
                        else
                        {
                            InVarArr[ix].DataValue = ((UPnPArgument)VarList[ID]).DataValue;
                        }
                        InVarArr[ix].DataType = ThisArg.RelatedStateVar.GetNetType().FullName;
                        break;
                    }
                }
            }
            if (state.InvokeCB != null)
            {
                state.InvokeCB(this, state.MethodName, InVarArr, RetVal, state.Tag);
            }
            else
            {
                if (OnInvokeResponse != null)
                {
                    OnInvokeResponse(this, state.MethodName, InVarArr, RetVal, state.Tag);
                }
            }
        }
Exemplo n.º 21
0
 private void NonPipelinedSniffPacketSink(HTTPRequest sender, HTTPMessage Response, object Tag)
 {
     if (OnSniffPacket != null)
         OnSniffPacket(this, Response, Tag);
 }
Exemplo n.º 22
0
 private void HandleSendEvent(HTTPRequest R, HTTPMessage M, object Tag)
 {
     R.Dispose();
     SendEventTable.Remove(R);
 }
Exemplo n.º 23
0
        private void CloseSink(HTTPSession ss)
        {
            bool err = false;
            string erraddr = "";

            ss.CancelAllEvents();
            lock (TagQueue)
            {
                KeepAliveTimer.Remove(this.GetHashCode());

                if (TagQueue.Count > 0)
                {
                    OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Information, "Switching Pipeline Modes [" + ss.GetHashCode().ToString() + "]");
                    _PIPELINE = false;
                    if (!ReceivedFirstResponse)
                    {
                        erraddr = ((StateData)TagQueue.Peek()).Dest.ToString();
                    }
                }

                if (!ReceivedFirstResponse)
                {
                    OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Server[" + erraddr + "] closed socket without answering");
                    err = true;
                }

                while (TagQueue.Count > 0)
                {
                    StateData sd = (StateData)TagQueue.Dequeue();
                    if (!err)
                    {
                        HTTPRequest TR = new HTTPRequest();
                        TR.ProxySetting = ProxySetting;
                        TR._PIPELINE = true;
                        if (this.OnSniff != null) TR.OnSniff += new HTTPRequest.SniffHandler(NonPipelinedSniffSink);
                        if (this.OnSniffPacket != null) TR.OnSniffPacket += new HTTPRequest.RequestHandler(NonPipelinedSniffPacketSink);
                        TR.OnResponse += new HTTPRequest.RequestHandler(NonPipelinedResponseSink);
                        this.NotPipelinedTable[TR] = TR;
                        TR.PipelineRequest(sd.Dest, sd.Request, sd.Tag);
                    }
                    else
                    {
                        if (OnResponse != null) OnResponse(this, null, sd.Tag);

                    }
                }
                s = null;
            }
        }
Exemplo n.º 24
0
        protected void PlaySink(AVConnection sender, DvAVTransport.Enum_TransportPlaySpeed Speed)
        {
            if (InvokeRequired) { Invoke(new AVConnection.PlayHandler(PlaySink), sender, Speed); return; }

            if (sender.CurrentURI == null)
            {
                player.Ctlcontrols.stop();
                sender.CurrentTransportState = DvAVTransport.Enum_TransportState.STOPPED;
                return;
            }

            if (sender.CurrentTransportState == DvAVTransport.Enum_TransportState.PAUSED_PLAYBACK)
            {
                player.Ctlcontrols.play();
            }
            else
            {
                if (sender.CurrentTransportState != DvAVTransport.Enum_TransportState.PLAYING)
                {
                    if (sender.CurrentURI.LocalPath.EndsWith(".m3u", true, System.Threading.Thread.CurrentThread.CurrentUICulture))
                    {
                        lock (this.m_LockRequest)
                        {
                            sender.CurrentTransportState = DvAVTransport.Enum_TransportState.TRANSITIONING;
                            string mediaUri = sender.CurrentURI.AbsoluteUri.Trim();//.ToLower();
                            if (this.m_PlainM3U.ContainsKey(mediaUri))
                            {
                                player.openPlayer((string)this.m_PlainM3U[mediaUri]);

                                StreamReader sr = System.IO.File.OpenText((string)this.m_PlainM3U[mediaUri]);
                                this.m_M3U = sr.ReadToEnd();

                                sr = System.IO.File.OpenText((string)this.m_Metadata[mediaUri]);
                                this.m_METADATA = sr.ReadToEnd();
                                DetermineMediaDuration(this.m_METADATA);
                            }
                            else
                            {
                                HTTPRequest R = new HTTPRequest();
                                R.OnResponse += new HTTPRequest.RequestHandler(Sink_AcquireAndSetPlaylist);
                                this.PlaylistRequests[R] = sender.CurrentURI.AbsoluteUri.Trim();//.ToLower();
                                this.m_LastRequest = R;
                                try
                                {
                                    R.PipelineRequest(new Uri(mediaUri), sender);
                                }
                                catch
                                {
                                    this.m_LastRequest = null;
                                    this.PlaylistRequests.Remove(R);
                                }
                            }
                        }
                    }
                    else
                    {
                        lock (this.m_LockRequest)
                        {
                            sender.CurrentTransportState = DvAVTransport.Enum_TransportState.TRANSITIONING;
                            player.URL = sender.CurrentURI.ToString();
                            player.Ctlcontrols.play();
                        }
                    }

                }
            }
        }