public void FindDeviceAsync(string SearchTarget) { HTTPMessage packet = new HTTPMessage(); packet.Directive = "M-SEARCH"; packet.DirectiveObj = "*"; packet.AddTag("ST", SearchTarget); packet.AddTag("MX", MX.ToString()); packet.AddTag("MAN", "\"ssdp:discover\""); packet.AddTag("HOST", "239.255.255.250:1900"); IPAddress[] localAddresses = this.NetInfo.GetLocalAddresses(); IPEndPoint dest = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 0x76c); for (int i = 0; i < localAddresses.Length; i++) { try { Socket theSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); theSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); theSocket.Bind(new IPEndPoint(localAddresses[i], 0)); SSDPSession session = new SSDPSession(theSocket, new SSDPSession.ReceiveHandler(this.HandleAsyncSearch)); this.SSDPSessions[session] = session; session.SendTo(packet, dest); session.SendTo(packet, dest); this.Lifetime.Add(session, 7); } catch (Exception exception) { EventLogger.Log(this, EventLogEntryType.Error, "CP Failure: " + localAddresses[i].ToString()); EventLogger.Log(exception); } } }
private void HandleAsyncSearch(SSDPSession sender, HTTPMessage msg) { DText text = new DText(); string tag = msg.GetTag("Location"); int maxAge = 0; string str2 = msg.GetTag("Cache-Control").Trim(); if (str2 != "") { text.ATTRMARK = ","; text.MULTMARK = "="; text[0] = str2; for (int i = 1; i <= text.DCOUNT(); i++) { if (text[i, 1].Trim().ToUpper() == "MAX-AGE") { maxAge = int.Parse(text[i, 2].Trim()); break; } } } str2 = msg.GetTag("USN"); string uSN = str2.Substring(str2.IndexOf(":") + 1); string searchTarget = msg.GetTag("ST"); if (uSN.IndexOf("::") != -1) { uSN = uSN.Substring(0, uSN.IndexOf("::")); } EventLogger.Log(this, EventLogEntryType.SuccessAudit, msg.RemoteEndPoint.ToString()); if (this.OnSearch != null) { this.OnSearch(msg.RemoteEndPoint, msg.LocalEndPoint, new Uri(tag), uSN, searchTarget, maxAge); } }
private void NonPipelinedSniffPacketSink(HTTPRequest sender, HTTPMessage Response, object Tag) { if (this.OnSniffPacket != null) { this.OnSniffPacket(this, Response, Tag); } }
public void BroadcastData(HTTPMessage Packet) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(new IPEndPoint(this.boundto.Address, 0)); try { socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, 1); } catch (Exception) { } string str = ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + ":" + ((IPEndPoint)socket.LocalEndPoint).Port.ToString(); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 0x76c); byte[] rawPacket = Packet.RawPacket; MulticastOption optionValue = new MulticastOption(remoteEP.Address); try { socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, optionValue); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)this.boundto.Address.Address); } catch (Exception) { return; } socket.SendTo(rawPacket, rawPacket.Length, SocketFlags.None, remoteEP); socket.SendTo(rawPacket, rawPacket.Length, SocketFlags.None, remoteEP); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, optionValue); socket.Close(); }
private void ReceiveSink(HTTPSession sender, HTTPMessage msg) { StateData stateObject = (StateData)sender.StateObject; object tag = stateObject.Tag; if ((msg.Version == "1.0") || (msg.Version == "0.9")) { sender.Close(); } else if (msg.GetTag("Connection").ToUpper() == "CLOSE") { sender.Close(); } if (this.OnResponse != null) { this.OnResponse(this, msg, tag); } sender.StateObject = null; lock (this.TagQueue) { if (this.TagQueue.Count == 0) { this.IdleTimeout = true; KeepAliveTimer.Add(this.GetHashCode(), 10); } } }
public StateData(HTTPMessage req, IPEndPoint d, object Tag, HTTPRequest.HeaderHandler HeaderCB) { this.Dest = d; this.Request = req; this.Tag = Tag; this.HeaderCB = HeaderCB; }
private void ValidateSearchPacket(HTTPMessage msg) { if (msg.GetTag("MAN") != "\"ssdp:discover\"") { throw new InvalidSearchPacketException("Invalid MAN"); } if (msg.DirectiveObj != "*") { throw new InvalidSearchPacketException("Expected * in RequestLine"); } if (double.Parse(msg.Version, new CultureInfo("en-US").NumberFormat) < 1.1) { throw new InvalidSearchPacketException("Version must be at least 1.1"); } int num = 0; string tag = msg.GetTag("MX"); if (tag == "") { throw new InvalidSearchPacketException("Missing MX"); } try { num = int.Parse(tag); } catch (Exception) { throw new InvalidSearchPacketException("MX must be an integer"); } if (num <= 0) { throw new InvalidSearchPacketException("MX must be a positive integer"); } }
private void RequestAnsweredSink(HTTPSession ss) { lock (this.TagQueue) { if (!this.ReceivedFirstResponse) { this.ReceivedFirstResponse = true; foreach (StateData data in this.TagQueue) { try { if (this.ProxySetting == null) { ss.Send(data.Request); } else { HTTPMessage packet = (HTTPMessage)data.Request.Clone(); packet.DirectiveObj = "http://" + data.Dest.ToString() + packet.DirectiveObj; packet.Version = "1.0"; ss.Send(packet); } continue; } catch (Exception) { continue; } } } } }
private void SniffPacketSink(HTTPMessage Packet) { if (this.OnSniffPacket != null) { this.OnSniffPacket(Packet); } }
private void HeaderSink(HTTPSession sender, HTTPMessage header, Stream TheStream) { this._Source = sender.Source; StateData stateObject = null; if (TheStream != null) { stateObject = (StateData)sender.StateObject; object tag = stateObject.Tag; if (stateObject.HeaderCB != null) { stateObject.HeaderCB(this, sender, header, TheStream, tag); } sender.StateObject = null; KeepAliveTimer.Add(this.GetHashCode(), 10); } else { lock (this.TagQueue) { stateObject = (StateData)this.TagQueue.Dequeue(); } sender.StateObject = stateObject; object obj3 = stateObject.Tag; if (stateObject.HeaderCB != null) { stateObject.HeaderCB(this, sender, header, TheStream, obj3); if ((sender.UserStream != null) && !sender.IsChunked) { sender.StateObject = null; } } } }
protected void SniffPacketSink(UPnPService sender, HTTPMessage MSG) { if (this.OnSniffPacket != null) { this.OnSniffPacket(this, MSG); } }
public void UnicastData(HTTPMessage msg, IPEndPoint dest) { if (this.OnSniffPacket != null) { this.OnSniffPacket(null, dest, msg); } byte[] rawPacket = msg.RawPacket; this.UnicastSendSocket.SendTo(rawPacket, rawPacket.Length, SocketFlags.None, dest); }
private void NonPipelinedResponseSink(HTTPRequest sender, HTTPMessage Response, object Tag) { this._Source = sender.Source; this.NotPipelinedTable.Remove(sender); sender.Dispose(); if (this.OnResponse != null) { this.OnResponse(this, Response, Tag); } }
private void HandleService(HTTPRequest sender, HTTPMessage msg, object Tag) { bool flag = false; if (msg == null) { EventLogger.Log(this, EventLogEntryType.Error, "Could not connect to device to fetch SCPD: " + ((UPnPService)Tag).SCPDURL); sender.Dispose(); this.TempDevice = null; this.OnFailed(this, new Uri(this.DUrl), new Exception("HTTP Connection Refused/Failed")); } else { bool flag2 = false; lock (this.CBLock) { if (msg.StatusCode == 200) { try { ((UPnPService)Tag).ParseSCPD(msg.StringBuffer); } catch (Exception exception) { EventLogger.Log(this, EventLogEntryType.Error, "Invalid SCPD XML on device:\r\n Friendly: " + this.TempDevice.FriendlyName + "\r\n Service: " + ((UPnPService)Tag).ServiceURN + "\r\n @" + this.TempDevice.LocationURL); EventLogger.Log(exception); return; } this.ServiceNum--; if ((this.ServiceNum == 0) && (this.OnDevice != null)) { flag2 = true; } } else { EventLogger.Log(this, EventLogEntryType.Error, "Device returned Error Code: " + msg.StatusCode.ToString() + " while fetching SCPD: " + ((UPnPService)Tag).SCPDURL); sender.Dispose(); flag = true; } } if (flag2) { this.TempDevice.descXmlLocation = new Uri(this.DUrl); this.OnDevice(this, this.TempDevice, new Uri(this.DUrl)); this.TempDevice = null; } if (flag && (this.OnFailed != null)) { this.TempDevice = null; this.OnFailed(this, new Uri(this.DUrl), new Exception("HTTP[" + msg.StatusCode.ToString() + "] Error")); } } }
private void HandleRequest(HTTPRequest sender, HTTPMessage msg, object Tag) { if (Tag != null) { this.HandleService(sender, msg, Tag); } else if (msg != null) { if (msg.StatusCode == 200) { try { this.TempDevice = UPnPDevice.Parse(msg.StringBuffer, new Uri(this.DUrl), sender.Source.Address); } catch (Exception) { EventLogger.Log(this, EventLogEntryType.Error, "Invalid Device Description XML @" + this.DUrl); return; } if (this.TempDevice == null) { EventLogger.Log(this, EventLogEntryType.Error, "Invalid Device Description XML @" + this.DUrl); } else { this.TempDevice.LocationURL = this.DUrl; this.TempDevice.ExpirationTimeout = this.MaxAge; if (this.TempDevice != null) { this.ServiceNum = this.FetchServiceCount(this.TempDevice); if ((this.ServiceNum == 0) && (this.OnDevice != null)) { this.Lifetime.Remove(this); this.OnDevice(this, this.TempDevice, new Uri(this.DUrl)); this.TempDevice = null; } else { this.FetchServiceDocuments(this.TempDevice); } } } } else if (this.OnFailed != null) { this.OnFailed(this, new Uri(this.DUrl), new Exception("Device returned HTTP fault: " + msg.StatusData)); } } else if (this.OnFailed != null) { this.OnFailed(this, new Uri(this.DUrl), new Exception("Could not connect to target")); } }
public static void ParseURL(string ServiceURL, out string WebIP, out int Port, out string ServiceName) { Uri uri = new Uri(ServiceURL); WebIP = uri.Host; if (uri.HostNameType == UriHostNameType.Dns) { WebIP = Dns.GetHostByName(WebIP).AddressList[0].ToString(); } Port = uri.Port; ServiceName = HTTPMessage.UnEscapeString(uri.PathAndQuery); }
private void HandleReceive(AsyncSocket sender, byte[] buffer, int HeadPointer, int BufferSize, int BytesRead, IPEndPoint source, IPEndPoint remote) { HTTPMessage msg = HTTPMessage.ParseByteArray(buffer, 0, BufferSize); msg.LocalEndPoint = source; msg.RemoteEndPoint = remote; sender.BufferBeginPointer = BufferSize; if (this.OnReceive != null) { this.OnReceive(this, msg); } }
private void SniffPacketSink(HTTPSession sender, HTTPMessage MSG) { if (this.OnSniffPacket != null) { if (sender.StateObject == null) { this.OnSniffPacket(this, MSG, null); } else { StateData stateObject = (StateData)sender.StateObject; object tag = stateObject.Tag; this.OnSniffPacket(this, MSG, tag); } } }
private void GetHostByNameSink(IAsyncResult result) { IPHostEntry entry = null; try { entry = Dns.EndGetHostByName(result); } catch (Exception) { return; } object[] asyncState = (object[])result.AsyncState; Uri uri = (Uri)asyncState[0]; object tag = asyncState[1]; this.ContinueRequest(new IPEndPoint(entry.AddressList[0], uri.Port), HTTPMessage.UnEscapeString(uri.PathAndQuery), tag, null); }
private void FetchServiceDocuments(UPnPDevice device) { for (int i = 0; i < device.Services.Length; i++) { HTTPMessage message = new HTTPMessage(); Uri resource = new Uri(device.Services[i].SCPDURL); message.Directive = "GET"; message.DirectiveObj = HTTPMessage.UnEscapeString(resource.PathAndQuery); message.AddTag("Host", resource.Host + ":" + resource.Port.ToString()); this.r.PipelineRequest(resource, device.Services[i]); } if (device.EmbeddedDevices.Length > 0) { for (int j = 0; j < device.EmbeddedDevices.Length; j++) { this.FetchServiceDocuments(device.EmbeddedDevices[j]); } } }
private void HandleReceive(IAsyncResult result) { try { int count = this.ReceiveSocket.EndReceiveFrom(result, ref this.R_Ep); HTTPMessage msg = HTTPMessage.ParseByteArray(this.MainBuffer, 0, count); msg.LocalEndPoint = this.LocalIPEndPoint; msg.RemoteEndPoint = new IPEndPoint(((IPEndPoint)this.R_Ep).Address, ((IPEndPoint)this.R_Ep).Port); this.ProcessPacket(msg, msg.RemoteEndPoint); } catch (Exception) { } try { this.ReceiveSocket.BeginReceiveFrom(this.MainBuffer, 0, 0x1000, SocketFlags.None, ref this.R_Ep, new AsyncCallback(this.HandleReceive), null); } catch (Exception) { } }
private void CreateSink(HTTPSession ss) { lock (this.TagQueue) { ss.OnHeader += new HTTPSession.ReceiveHeaderHandler(this.HeaderSink); ss.OnReceive += new HTTPSession.ReceiveHandler(this.ReceiveSink); ss.OnClosed += new HTTPSession.SessionHandler(this.CloseSink); ss.OnStreamDone += new HTTPSession.StreamDoneHandler(this.StreamDoneSink); ss.OnRequestAnswered += new HTTPSession.SessionHandler(this.RequestAnsweredSink); if (this.OnSniff != null) { ss.OnSniff += new HTTPSession.SniffHandler(this.SniffSink); } if (this.OnSniffPacket != null) { ss.OnSniffPacket += new HTTPSession.ReceiveHandler(this.SniffPacketSink); } StateData data = (StateData)this.TagQueue.Peek(); try { if (this.ProxySetting == null) { ss.Send(data.Request); } else { HTTPMessage packet = (HTTPMessage)data.Request.Clone(); packet.DirectiveObj = "http://" + data.Dest.ToString() + packet.DirectiveObj; packet.Version = "1.0"; ss.Send(packet); } } catch (Exception exception) { EventLogger.Log(exception); } } }
private void HandleRequest(HTTPSession WebSession, HTTPMessage request) { this.OnReceiveEvent.Fire(request, WebSession); }
private void ContinueRequest(IPEndPoint dest, string PQ, object Tag, HTTPMessage MSG) { HTTPMessage mSG = null; if (MSG == null) { mSG = new HTTPMessage(); mSG.Directive = "GET"; mSG.DirectiveObj = PQ; mSG.AddTag("Host", dest.ToString()); } else { mSG = MSG; } lock (this.TagQueue) { this.IdleTimeout = false; KeepAliveTimer.Remove(this.GetHashCode()); this.LastMessage = mSG; if ((!PIPELINE && !this._PIPELINE) || !this._PIPELINE) { HTTPRequest request = new HTTPRequest(); request.ProxySetting = this.ProxySetting; request._PIPELINE = true; if (this.OnSniff != null) { request.OnSniff = (SniffHandler)Delegate.Combine(request.OnSniff, new SniffHandler(this.NonPipelinedSniffSink)); } if (this.OnSniffPacket != null) { request.OnSniffPacket = (RequestHandler)Delegate.Combine(request.OnSniffPacket, new RequestHandler(this.NonPipelinedSniffPacketSink)); } request.OnResponse = (RequestHandler)Delegate.Combine(request.OnResponse, new RequestHandler(this.NonPipelinedResponseSink)); this.NotPipelinedTable[request] = request; request.PipelineRequest(dest, mSG, Tag); } else { bool flag = this.TagQueue.Count == 0; this.TagQueue.Enqueue(new StateData(mSG, dest, Tag, null)); if (this.s == null) { this.ReceivedFirstResponse = false; if (this.ProxySetting != null) { this.s = new HTTPSession(new IPEndPoint(IPAddress.Any, 0), this.ProxySetting, new HTTPSession.SessionHandler(this.CreateSink), new HTTPSession.SessionHandler(this.CreateFailedSink), null); } else { this.s = new HTTPSession(new IPEndPoint(IPAddress.Any, 0), dest, new HTTPSession.SessionHandler(this.CreateSink), new HTTPSession.SessionHandler(this.CreateFailedSink), null); } } else if (this.s.IsConnected && this.ReceivedFirstResponse) { try { if (this.ProxySetting == null) { this.s.Send(mSG); } else { HTTPMessage packet = (HTTPMessage)mSG.Clone(); packet.DirectiveObj = "http://" + dest.ToString() + packet.DirectiveObj; packet.Version = "1.0"; this.s.Send(packet); } } catch (Exception) { } } } } }
private void ProcessPacket(HTTPMessage msg, IPEndPoint src) { if (this.OnSniffPacket != null) { this.OnSniffPacket(src, null, msg); } DText text = new DText(); text.ATTRMARK = "::"; bool isAlive = false; string tag = msg.GetTag("USN"); text[0] = tag; string uSN = text[1]; uSN = uSN.Substring(uSN.IndexOf(":") + 1); string sT = text[2]; int maxAge = 0; if (msg.GetTag("NTS").ToUpper() == "SSDP:ALIVE") { isAlive = true; string str5 = msg.GetTag("Cache-Control").Trim(); if (str5 != "") { text.ATTRMARK = ","; text.MULTMARK = "="; text[0] = str5; for (int i = 1; i <= text.DCOUNT(); i++) { if (text[i, 1].Trim().ToUpper() == "MAX-AGE") { maxAge = int.Parse(text[i, 2].Trim()); break; } } } } else { isAlive = false; } if ((msg.Directive == "NOTIFY") && (this.OnNotify != null)) { Uri uri; try { uri = new Uri(msg.GetTag("Location")); } catch (Exception) { uri = null; } this.OnNotify(src, msg.LocalEndPoint, uri, isAlive, uSN, sT, maxAge, msg); } if (msg.Directive == "M-SEARCH") { try { this.ValidateSearchPacket(msg); } catch (InvalidSearchPacketException) { return; } if (this.OnSearch != null) { int maxValue = int.Parse(msg.GetTag("MX")); SearchStruct struct2 = new SearchStruct(); struct2.ST = msg.GetTag("ST"); struct2.Source = src; struct2.Local = this.LocalIPEndPoint; this.SearchTimer.Add(struct2, this.RandomGenerator.Next(0, maxValue)); } } }
public static HTTPMessage ParseByteArray(byte[] buffer, int indx, int count) { byte[] buffer2; HTTPMessage message = new HTTPMessage(); string str = new UTF8Encoding().GetString(buffer, indx, count); DText text = new DText(); int index = str.IndexOf("\r\n\r\n"); str = str.Substring(0, index); text.ATTRMARK = "\r\n"; text.MULTMARK = ":"; text[0] = str; string str3 = text[1]; DText text2 = new DText(); text2.ATTRMARK = " "; text2.MULTMARK = "/"; text2[0] = str3; if (str3.ToUpper().StartsWith("HTTP/")) { message.ResponseCode = int.Parse(text2[2]); int startIndex = str3.IndexOf(" "); startIndex = str3.IndexOf(" ", (int)(startIndex + 1)); message.ResponseData = UnEscapeString(str3.Substring(startIndex)); try { message.Version = text2[1, 2]; } catch (Exception) { message.Version = "0.9"; } } else { message.Directive = text2[1]; string theString = str3.Substring(str3.LastIndexOf(" ") + 1); if (!theString.ToUpper().StartsWith("HTTP/")) { message.Version = "0.9"; message.DirectiveObj = UnEscapeString(theString); } else { message.Version = theString.Substring(theString.IndexOf("/") + 1); int num3 = str3.IndexOf(" ") + 1; message.DirectiveObj = UnEscapeString(str3.Substring(num3, ((str3.Length - num3) - theString.Length) - 1)); } } string tagName = ""; string tagData = ""; for (int i = 2; i <= text.DCOUNT(); i++) { if ((tagName != "") && text[i, 1].StartsWith(" ")) { tagData = text[i, 1].Substring(1); } else { tagName = text[i, 1]; tagData = ""; for (int j = 2; j <= text.DCOUNT(i); j++) { if (tagData == "") { tagData = text[i, j]; } else { tagData = tagData + text.MULTMARK + text[i, j]; } } } message.AppendTag(tagName, tagData); } int length = 0; if (message.HasTag("Content-Length")) { try { length = int.Parse(message.GetTag("Content-Length")); } catch (Exception) { length = -1; } } else { length = -1; } if (length > 0) { buffer2 = new byte[length]; if (((index + 4) + length) <= count) { Array.Copy(buffer, index + 4, buffer2, 0, length); message.DataBuffer = buffer2; } } switch (length) { case -1: buffer2 = new byte[count - (index + 4)]; Array.Copy(buffer, index + 4, buffer2, 0, buffer2.Length); message.DataBuffer = buffer2; break; case 0: message.DataBuffer = new byte[0]; break; } return(message); }
public void PipelineRequest(IPEndPoint dest, HTTPMessage MSG, object Tag) { this.ContinueRequest(dest, "", Tag, MSG); }
public void PipelineRequest(Uri Resource, object Tag) { object[] stateObject = new object[] { Resource, Tag }; string host = Resource.Host; if (Resource.HostNameType == UriHostNameType.Dns) { Dns.BeginGetHostByName(host, new AsyncCallback(this.GetHostByNameSink), stateObject); } else { this.ContinueRequest(new IPEndPoint(IPAddress.Parse(Resource.Host), Resource.Port), HTTPMessage.UnEscapeString(Resource.PathAndQuery), Tag, null); } }
private void HandleNotify(IPEndPoint source, IPEndPoint local, Uri LocationURL, bool IsAlive, string USN, string ST, int MaxAge, HTTPMessage Packet) { if (IsAlive && (LocationURL != null)) { EventLogger.Log(this, EventLogEntryType.SuccessAudit, LocationURL.ToString()); } if (this.OnNotify != null) { this.OnNotify(source, local, LocationURL, IsAlive, USN, ST, MaxAge, Packet); } }
private void HandleHeader(HTTPSession sender, HTTPMessage Header, Stream StreamObject) { this.SessionTimer.Remove(sender); this.OnHeaderEvent.Fire(Header, sender); }