示例#1
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;
            }
        }
示例#2
0
        private void SniffPacketSink(HTTPSession sender, HTTPMessage MSG)
        {
            if (this.OnSniffPacket != null)
            {
                if (sender.StateObject == null)
                {
                    OnSniffPacket(this, MSG, null);
                    return;
                }
                StateData sd = (StateData)sender.StateObject;
                object Tag = sd.Tag;

                OnSniffPacket(this, MSG, Tag);
            }
        }
示例#3
0
 private void RequestAnsweredSink(HTTPSession ss)
 {
     lock (TagQueue)
     {
         if (!ReceivedFirstResponse)
         {
             ReceivedFirstResponse = true;
             IEnumerator en = TagQueue.GetEnumerator();
             while (en.MoveNext())
             {
                 StateData sd = (StateData)en.Current;
                 try
                 {
                     if (ProxySetting == null)
                     {
                         ss.Send(sd.Request);
                     }
                     else
                     {
                         HTTPMessage pr = (HTTPMessage)sd.Request.Clone();
                         pr.DirectiveObj = "http://" + sd.Dest.ToString() + pr.DirectiveObj;
                         pr.Version = "1.0";
                         ss.Send(pr);
                     }
                 }
                 catch (Exception ex)
                 {
                     OpenSource.Utilities.EventLogger.Log(ex);
                 }
             }
         }
     }
 }
示例#4
0
 /// <summary>
 /// Terminates and disposes this object
 /// </summary>
 public void Dispose()
 {
     lock (this.TagQueue)
     {
         HTTPSession x = this.s;
         if (x != null)
             x.Close();
         s = null;
         TagQueue.Clear();
     }
 }
示例#5
0
 private void HeaderSink(HTTPSession sender, HTTPMessage header, Stream TheStream)
 {
     _Source = sender.Source;
     StateData sd = null;
     if (TheStream != null)
     {
         // This is the result of post-headers in a chunked document
         sd = (StateData)sender.StateObject;
         object Tag = sd.Tag;
         if (sd.HeaderCB != null) sd.HeaderCB(this, sender, header, TheStream, Tag);
         sender.StateObject = null;
         KeepAliveTimer.Add(this.GetHashCode(), 10);
     }
     else
     {
         lock (TagQueue)
         {
             sd = (StateData)TagQueue.Dequeue();
         }
         sender.StateObject = sd;
         object Tag = sd.Tag;
         if (sd.HeaderCB != null)
         {
             sd.HeaderCB(this, sender, header, TheStream, Tag);
             if (sender.UserStream != null && !sender.IsChunked)
             {
                 // If I don't set this to null, this holds a strong reference, resulting in
                 // possible memory leaks
                 sender.StateObject = null;
             }
         }
     }
 }
        private void Accept(IAsyncResult result)
        {
            HTTPSession WebSession = null;

            try
            {
                Socket AcceptedSocket = MainSocket.EndAccept(result);
                lock (SessionTable)
                {
                    WebSession = new HTTPSession(this.LocalIPEndPoint, AcceptedSocket);
                    WebSession.OnClosed += new HTTPSession.SessionHandler(CloseSink);
                    WebSession.OnHeader += new HTTPSession.ReceiveHeaderHandler(HandleHeader);
                    WebSession.OnReceive += new HTTPSession.ReceiveHandler(HandleRequest);
                    SessionTable[WebSession] = WebSession;
                }
                SessionTimer.Add(WebSession, 3);
                OnSessionEvent.Fire(this, WebSession);
                WebSession.StartReading();
            }
            catch (Exception err)
            {
                if (err.GetType() != typeof(System.ObjectDisposedException))
                {
                    // Error
                    OpenSource.Utilities.EventLogger.Log(err);
                }
            }

            try
            {
                MainSocket.BeginAccept(new AsyncCallback(Accept), null);
            }
            catch (Exception)
            {
                // Socket was closed
            }
        }
 private void HandleHeader(HTTPSession sender, HTTPMessage Header, Stream StreamObject)
 {
     SessionTimer.Remove(sender);
     OnHeaderEvent.Fire(Header, sender);
 }
示例#8
0
 private void HeaderHandler(OpenSource.UPnP.UPnPDevice sender, OpenSource.UPnP.HTTPMessage msg, OpenSource.UPnP.HTTPSession WebSession, string VirtualDir)
 {
     msg.AddTag("transferMode.dlna.org", "Streaming");
     msg.AddTag("contentFeatures.dlna.org", "DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000");
 }
示例#9
0
 private void PageHandler(OpenSource.UPnP.UPnPDevice sender, OpenSource.UPnP.HTTPMessage msg, OpenSource.UPnP.HTTPSession WebSession, string VirtualDir)
 {
     if (VirtualDir.Equals("/stream", StringComparison.InvariantCultureIgnoreCase) && msg.DirectiveObj.Equals("/swyh.mp3", StringComparison.InvariantCultureIgnoreCase))
     {
         WebSession.OnStreamDone += (s, e) =>
         {
             if (sessionMp3Streams.ContainsKey(s.SessionID))
             {
                 PipeStream value;
                 sessionMp3Streams.TryRemove(s.SessionID, out value);
                 App.CurrentInstance.wasapiProvider.UpdateClientsList();
             }
         };
         PipeStream stream = sessionMp3Streams.GetOrAdd(WebSession.SessionID, new PipeStream());
         App.CurrentInstance.wasapiProvider.UpdateClientsList();
         WebSession.SendStreamObject(stream, "audio/mpeg");
     }
     else if (VirtualDir.Equals("/stream", StringComparison.InvariantCultureIgnoreCase) && msg.DirectiveObj.Equals("/swyh.wav", StringComparison.InvariantCultureIgnoreCase))
     {
         WebSession.OnStreamDone += (s, e) =>
         {
             if (sessionPcmStreams.ContainsKey(s.SessionID))
             {
                 PipeStream value;
                 sessionPcmStreams.TryRemove(s.SessionID, out value);
                 App.CurrentInstance.wasapiProvider.UpdateClientsList();
             }
         };
         PipeStream stream = sessionPcmStreams.GetOrAdd(WebSession.SessionID, new PipeStream());
         App.CurrentInstance.wasapiProvider.UpdateClientsList();
         var audioFormat = AudioSettings.GetAudioFormat();
         WebSession.SendStreamObject(stream, "audio/L16;rate=" + audioFormat.SampleRate + ";channels=" + audioFormat.Channels);
     }
     else if (VirtualDir.Equals("/about", StringComparison.InvariantCultureIgnoreCase))
     {
         OpenSource.UPnP.HTTPMessage response = new OpenSource.UPnP.HTTPMessage();
         response.StatusCode = 200;
         response.StatusData = "OK";
         response.AddTag("Content-Type", "text/html");
         response.BodyBuffer = System.Text.Encoding.UTF8.GetBytes(Properties.Resources.About);
         WebSession.Send(response);
     }
     else
     {
         OpenSource.UPnP.HTTPMessage response = new OpenSource.UPnP.HTTPMessage();
         response.StatusCode = 404;
         response.StatusData = "Not Found";
         response.AddTag("Content-Type", "text/html");
         response.BodyBuffer = System.Text.Encoding.UTF8.GetBytes(Properties.Resources.Error404);
         WebSession.Send(response);
     }
 }
 private void Request(object msg, IPEndPoint dest)
 {
     if (dest == null) return;
     s = new HTTPSession(new IPEndPoint(IPAddress.Any, 0), dest,
         new HTTPSession.SessionHandler(CreateSink),
         new HTTPSession.SessionHandler(FailSink),
         msg);
 }
示例#11
0
		public void SendStreamObject(Stream SObject, HTTPSession.Range[] Ranges, string ContentType)
		{
			Info infoObj = new Info();

			infoObj.CurrentStreamObject = SObject;

			if (Ranges!=null && Ranges.Length>1)
			{
				infoObj.RangeSeparator = "**"+Guid.NewGuid().ToString()+"**";
				infoObj.RangeContentType = ContentType;
			}
			
			String Packet = "";
				
			if (Ranges == null && Headers.Version=="1.0")
			{
				// Oldskool Server
				Packet = "HTTP/1.0 200 OK\r\n";
			}
			else if (Ranges == null)
			{
				// 1.1 or better server
				Packet = "HTTP/1.1 200 OK\r\n";
				Packet += "Transfer-Encoding: Chunked\r\n";
			}
			if (Ranges!=null) 
			{
				Packet = "HTTP/1.1 206 Partial Content\r\n";
				infoObj.RangeList = Ranges;

				try
				{
					SObject.Seek(infoObj.RangeList[0].Position,SeekOrigin.Begin);
				}
				catch(Exception ex)
				{
                    OpenSource.Utilities.EventLogger.Log(ex);
					//ToDo: Fail This for invalid range
				}
				if (SObject.Length-SObject.Position<infoObj.RangeList[0].Length)
				{
					infoObj.RangeList[0].Length = SObject.Length-SObject.Position;
				}

				if (infoObj.RangeList.Length==1)
				{
					Packet += "Content-Range: bytes " + infoObj.RangeList[0].Position.ToString() + "-" + (infoObj.RangeList[0].Position+infoObj.RangeList[0].Length-1).ToString() + "/" + SObject.Length.ToString() + "\r\nContent-Length: " + infoObj.RangeList[0].Length.ToString()+"\r\n";
						
					Packet += "Content-Type: " + ContentType + "\r\n";
				}
				else
				{
					Packet += "Content-type: multipart/byteranges; boundary=" + infoObj.RangeSeparator + "\r\n";
				}
			}
			else
			{
				Packet += "Content-Type: " + ContentType + "\r\n";
			}
			Packet += "Server: MiniWebServer\r\n";
			Packet += "\r\n";


			infoObj.StringPacket = Packet;
			lock(StateQueue)
			{
				StateQueue.Enqueue(infoObj);
			}

			lock(SendQueue)
			{
				SendQueue.Enqueue(infoObj);
				if (SendQueue.Count==1)
				{
					// InitiateRead
					infoObj.StringPacket = null;
					MainSocket.Send(U.GetBytes(Packet),SObject);
				}
			}
		}
 private void ReceiveSink(HTTPSession sender, HTTPMessage msg)
 {
     GetText.Text = msg.StringPacket;
 }
 private void FailSink(HTTPSession FS)
 {
     SniffText.Text = "Could not connect to resouce.";
     GetText.Text = "Could not connect to resouce.";
 }
        private void CreateSink(HTTPSession CS)
        {
            CS.OnClosed += new HTTPSession.SessionHandler(CloseSink);

            SW = new HTTPSessionWatcher(CS);
            SW.OnSniff += new HTTPSessionWatcher.SniffHandler(SniffSink);
            CS.OnReceive += new HTTPSession.ReceiveHandler(ReceiveSink);
            if (CS.StateObject.GetType() == typeof(HTTPMessage))
            {
                CS.Send((HTTPMessage)CS.StateObject);
            }
            else
            {
                Queue Q = (Queue)CS.StateObject;
                HTTPMessage M;
                M = (HTTPMessage)Q.Dequeue();
                while (M != null && Q.Count > 0)
                {
                    CS.Send(M);
                    M = (HTTPMessage)Q.Dequeue();
                }
            }
        }
 private void CloseSink(HTTPSession CS)
 {
 }
示例#16
0
        private void EventProcesser(UPnPDevice sender, HTTPMessage msg, HTTPSession WebSession, string VirtualDir)
        {
            if (ControlPointOnly == true)
            {
                String Method = msg.Directive;
                HTTPMessage Response = new HTTPMessage();

                if (Method != "NOTIFY")
                {
                    Response.StatusCode = 405;
                    Response.StatusData = Method + " not supported";
                    WebSession.Send(Response);
                    return; // Other methods are unknown to us
                }
                else if (Method == "NOTIFY")
                {
                    for (int id = 0; id < Services.Length; ++id)
                    {
                        //						SSDP.ParseURL(Services[id].__eventurl,out WebIP, out WebPort, out WebData);
                        //						if (WebData==MethodData)
                        //						{
                        if (Services[id].IsYourEvent(msg.GetTag("SID")) == true)
                        {
                            Response.StatusCode = 200;
                            Response.StatusData = "OK";
                            WebSession.Send(Response);

                            Services[id]._TriggerEvent(msg.GetTag("SID"), long.Parse(msg.GetTag("SEQ")), msg.StringBuffer, 0);
                            break;
                        }
                        //						}
                    }
                }
            }
        }
示例#17
0
 private void SniffSessionSink3(HTTPSession sender, HTTPMessage msg)
 {
     if (OnSniffPacket != null)
         OnSniffPacket((HTTPMessage)msg.Clone());
 }
示例#18
0
 private void HandleEventReceive(HTTPSession TheSession, HTTPMessage msg)
 {
     TheSession.Close();
 }
 private void CloseSink(HTTPSession s)
 {
     lock (SessionTable)
     {
         SessionTable.Remove(s);
     }
 }
示例#20
0
        private void HandleHeaderRequest(HTTPMessage msg, HTTPSession WebSession)
        {
            DText parser = new DText();
            HTTPMessage Response = new HTTPMessage();
            String Method = msg.Directive;
            String MethodData = msg.DirectiveObj;

            VirtualDirectoryHandler H_cb = null;
            VirtualDirectoryHandler P_cb = null;

            String vd = "";
            String vdobj = "";

            // Check VirtualDirTable
            int vdi;
            try
            {
                vdi = MethodData.IndexOf("/", 1);
                if (vdi != -1)
                {
                    vdobj = MethodData.Substring(vdi);
                    vd = MethodData.Substring(0, vdi);
                    if (VirtualDir_Header_Table.ContainsKey(vd))
                    {
                        if (VirtualDir_Header_Table[vd] != null)
                            H_cb = (VirtualDirectoryHandler)VirtualDir_Header_Table[vd];
                    }
                    if (VirtualDir_Table.ContainsKey(vd))
                    {
                        if (VirtualDir_Table[vd] != null)
                            P_cb = (VirtualDirectoryHandler)VirtualDir_Table[vd];
                    }
                }
            }
            catch (Exception ex)
            {
                OpenSource.Utilities.EventLogger.Log(ex);
            }

            if ((H_cb != null) || (P_cb != null))
            {
                HTTPMessage _msg = (HTTPMessage)msg.Clone();
                _msg.DirectiveObj = vdobj;
                WebSession.InternalStateObject = new Object[3] { vd, vdobj, P_cb };
                if (H_cb != null)
                    H_cb(this, _msg, WebSession, vd);
                return;
            }
        }
 private void HandleRequest(HTTPSession WebSession, HTTPMessage request)
 {
     OnReceiveEvent.Fire(request, WebSession);
 }
示例#22
0
 private void HandleParent_Header(UPnPDevice sender, HTTPMessage msg, HTTPSession WebSession, string VD)
 {
     HandleHeaderRequest(msg, WebSession);
 }
示例#23
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);
                        }
                    }
                }
            }
        }
示例#24
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);
            }
        }
示例#25
0
        private void ReceiveSink(HTTPSession sender, HTTPMessage msg)
        {
            StateData sd = (StateData)sender.StateObject;
            object Tag = sd.Tag;

            if (msg.Version == "1.0" || msg.Version == "0.9")
            {
                sender.Close();
            }
            else
            {
                if (msg.GetTag("Connection").ToUpper() == "CLOSE")
                {
                    sender.Close();
                }
            }


            if (OnResponse != null) OnResponse(this, msg, Tag);
            // If I don't set this to null, this holds a strong reference, resulting in
            // possible memory leaks
            sender.StateObject = null;
            lock (TagQueue)
            {
                if (TagQueue.Count == 0)
                {
                    this.IdleTimeout = true;
                    KeepAliveTimer.Add(this.GetHashCode(), 10);
                }
            }
        }
示例#26
0
        private HTTPMessage Invoke(String Control, String XML, String SOAPACTION, HTTPSession WebSession)
        {
            String MethodTag = "";

            ArrayList VarList = new ArrayList();
            UPnPArgument VarArg;

            StringReader MyString = new StringReader(XML);
            XmlTextReader XMLDoc = new XmlTextReader(MyString);

            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();
                    while ((XMLDoc.LocalName != MethodTag) && (XMLDoc.LocalName != "Envelope")
                           && (XMLDoc.LocalName != "Body"))
                    {
                        //						VarArg = new UPnPArgument(XMLDoc.LocalName,UPnPStringFormatter.UnEscapeString(XMLDoc.ReadInnerXml()));
                        VarArg = new UPnPArgument(XMLDoc.LocalName, XMLDoc.ReadString());

                        VarList.Add(VarArg);
                        if (XMLDoc.LocalName == "" || XMLDoc.IsStartElement() == false || XMLDoc.IsEmptyElement)
                        {
                            XMLDoc.Read();
                            XMLDoc.MoveToContent();
                        }
                    }
                }
            }

            Object RetVal = "";
            bool found = false;
            int id = 0;

            for (id = 0; id < Services.Length; ++id)
            {
                if (Services[id].ControlURL == Control)
                {
                    if (MethodTag != "QueryStateVariable")
                    {
                        UPnPAction A = Services[id].GetAction(MethodTag);
                        if (A == null)
                        {
                            break;
                        }
                        ArrayList tlist = new ArrayList();
                        InvokerInfoStruct iis = new InvokerInfoStruct();
                        iis.WebSession = WebSession;
                        iis.MethodName = MethodTag;
                        iis.SOAPAction = SOAPACTION;
                        foreach (UPnPArgument arg in A.Arguments)
                        {
                            if (arg.IsReturnValue == true)
                                iis.RetArg = (UPnPArgument)arg.Clone();
                            if (arg.Direction == "out")
                                tlist.Add(arg.Clone());
                        }
                        iis.OutArgs = (UPnPArgument[])tlist.ToArray(typeof(UPnPArgument));
                        InvokerInfo[Thread.CurrentThread.GetHashCode()] = iis;
                    }

                    RetVal = Services[id].InvokeLocal(MethodTag, ref VarList);
                    found = true;
                    break;
                }
            }
            if (found == false)
            {
                throw (new UPnPCustomException(401, "Invalid Action: " + MethodTag));
            }

            HTTPMessage response = ParseInvokeResponse(MethodTag, SOAPACTION, Services[id].ServiceURN, RetVal, (UPnPArgument[])VarList.ToArray(typeof(UPnPArgument)));
            return (response);
        }
示例#27
0
 private void StreamDoneSink(HTTPSession sender, Stream StreamObject)
 {
     //ToDo: Place callback from StateData here, to notify Stream is Done
 }
示例#28
0
 private HTTPMessage Post(String MethodData, String XML, String SOAPACTION, HTTPSession WebSession)
 {
     return (Invoke(MethodData.Substring(1), XML, SOAPACTION, WebSession));
 }
示例#29
0
        private void CreateSink(HTTPSession ss)
        {
            lock (TagQueue)
            {
                ss.OnHeader += new HTTPSession.ReceiveHeaderHandler(HeaderSink);
                ss.OnReceive += new HTTPSession.ReceiveHandler(ReceiveSink);
                ss.OnClosed += new HTTPSession.SessionHandler(CloseSink);
                ss.OnStreamDone += new HTTPSession.StreamDoneHandler(StreamDoneSink);
                ss.OnRequestAnswered += new HTTPSession.SessionHandler(RequestAnsweredSink);

                if (this.OnSniff != null) ss.OnSniff += new HTTPSession.SniffHandler(SniffSink);
                if (this.OnSniffPacket != null) ss.OnSniffPacket += new HTTPSession.ReceiveHandler(SniffPacketSink);

                StateData sd = (StateData)TagQueue.Peek();

                try
                {
                    if (ProxySetting == null)
                    {
                        ss.Send(sd.Request);
                    }
                    else
                    {
                        HTTPMessage pr = (HTTPMessage)sd.Request.Clone();
                        pr.DirectiveObj = "http://" + sd.Dest.ToString() + pr.DirectiveObj;
                        pr.Version = "1.0";
                        ss.Send(pr);
                    }
                }
                catch (Exception exc)
                {
                    OpenSource.Utilities.EventLogger.Log(exc);
                }
            }
        }
示例#30
0
        private void SniffSessionSink(MiniWebServer Sender, HTTPSession s)
        {
            if (OnSniff != null)
            {
                s.OnSniff += new HTTPSession.SniffHandler(SniffSessionSink2);
            }
            else
            {
                if (OnSniffPacket == null)
                {
                    Sender.OnSession -= new MiniWebServer.NewSessionHandler(SniffSessionSink);
                }
            }

            if (OnSniffPacket != null)
            {
                s.OnSniffPacket += new HTTPSession.ReceiveHandler(SniffSessionSink3);
            }
        }
示例#31
0
        private void CreateFailedSink(HTTPSession ss)
        {
            lock (TagQueue)
            {
                while (TagQueue.Count > 0)
                {
                    StateData sd = (StateData)TagQueue.Dequeue();
                    OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Connection Attempt to [" + sd.Dest.ToString() + "] Refused/Failed");

                    object Tag = sd.Tag;
                    if (sd.HeaderCB != null)
                    {
                        sd.HeaderCB(this, ss, null, null, Tag);
                    }
                    else
                    {
                        if (this.OnResponse != null) OnResponse(this, null, Tag);
                    }
                }
                s = null;
            }
        }
 /// <summary>
 /// Returns true if the provided HTTP session object
 /// matches the transfer's session object.
 /// </summary>
 /// <param name="session"></param>
 /// <returns></returns>
 internal bool IsSessionMatch(HTTPSession session)
 {
     return (session == Session) ;
 }