From f848c385baab77d8158e2c60e2484bcddb6f179e Mon Sep 17 00:00:00 2001 From: Gene Date: Wed, 30 Aug 2023 09:42:48 +0200 Subject: [PATCH] Deprecated device expiration/update timers (no status polling). --- UPnP/LifeTimeMonitor.cs | 61 +-------------- UPnP/SSDP.cs | 159 +++++++++------------------------------- UPnP/UPnPDevice.cs | 52 ++++++------- UPnP/Utils.cs | 11 --- 4 files changed, 62 insertions(+), 221 deletions(-) diff --git a/UPnP/LifeTimeMonitor.cs b/UPnP/LifeTimeMonitor.cs index a4405f0..b9b5c8e 100644 --- a/UPnP/LifeTimeMonitor.cs +++ b/UPnP/LifeTimeMonitor.cs @@ -62,9 +62,6 @@ public event LifeTimeHandler OnExpired /// public LifeTimeMonitor() { - SafeNotifyTimer.SetTimer(5000, OnTimedEvent); - //SafeNotifyTimer.OnElapsed += new SafeTimer.TimeElapsedHandler(OnTimedEvent); - //SafeNotifyTimer.AutoReset = false; //OpenSource.Utilities.InstanceTracker.Add(this); } @@ -81,40 +78,13 @@ private void OnTimedEvent(SafeTimer_SINGLE sender) } foreach (object obj in eventList) OnExpiredEvent.Fire(this, obj); - lock (MonitorLock) - { - if (MonitorList.Count > 0) - { - TimeSpan nextEventTime = ((DateTime)MonitorList.GetKey(0)).Subtract(DateTime.Now); - if (nextEventTime.TotalMilliseconds <= 0) - { - sender.SetTimer(1, OnTimedEvent); - } - else - { - sender.SetTimer((int)nextEventTime.TotalMilliseconds, OnTimedEvent); - } - /* - TimeSpan nextEventTime = ((DateTime)MonitorList.GetKey(0)).Subtract(DateTime.Now); - if (nextEventTime.TotalMilliseconds<=0) - { - SafeNotifyTimer.Interval = 1; - } - else - { - SafeNotifyTimer.Interval = (int)nextEventTime.TotalMilliseconds; - } - SafeNotifyTimer.Start(); - */ - } - } + } public void Clear() { lock (MonitorLock) { - //this.SafeNotifyTimer.Stop(); MonitorList.Clear(); } } @@ -133,39 +103,10 @@ public bool Remove(object obj) { if (MonitorList.ContainsValue(obj) == true) { - //SafeNotifyTimer.Stop(); - //NotifyTimer.Stop(); RetVal = true; MonitorList.RemoveAt(MonitorList.IndexOfValue(obj)); - - if (MonitorList.Count > 0) - { - TimeSpan nextEventTime = ((DateTime)MonitorList.GetKey(0)).Subtract(DateTime.Now); - if (nextEventTime.TotalMilliseconds <= 0) - { - SafeNotifyTimer.SetTimer(1, OnTimedEvent); - } - else - { - SafeNotifyTimer.SetTimer((int)nextEventTime.TotalMilliseconds, OnTimedEvent); - } - /* - TimeSpan nextEventTime = ((DateTime)MonitorList.GetKey(0)).Subtract(DateTime.Now); - if (nextEventTime.TotalMilliseconds<=0) - { - SafeNotifyTimer.Interval = 1; - } - else - { - SafeNotifyTimer.Interval = (int)nextEventTime.TotalMilliseconds; - } - SafeNotifyTimer.Start(); - */ - } } } - //OnTimedEvent(this,null); -// OnTimedEvent(); return RetVal; } diff --git a/UPnP/SSDP.cs b/UPnP/SSDP.cs index 8c65196..ec49316 100644 --- a/UPnP/SSDP.cs +++ b/UPnP/SSDP.cs @@ -83,8 +83,6 @@ private class SearchStruct private Hashtable sessions = new Hashtable(); private Hashtable usessions = new Hashtable(); - private SafeTimer_SINGLE NotifyTimer = new SafeTimer_SINGLE(); - /// /// Constructs a new SSDP Server /// @@ -93,22 +91,13 @@ private class SearchStruct public SSDP(int Expiration) { //OpenSource.Utilities.InstanceTracker.Add(this); - LifeTimeHandler = new LifeTimeMonitor.LifeTimeHandler(SearchTimerSink); + LifeTimeHandler = SearchTimerSink; SearchTimer.OnExpired += LifeTimeHandler; SSDP_EXPIRATION = Expiration; if (SSDP_EXPIRATION < 5) SSDP_EXPIRATION = 5; - __NotifyCheck(NotifyTimer); - - /* - int MinVal = (int)((double)SSDP_EXPIRATION * 0.25 * 1000); - int MaxVal = (int)((double)SSDP_EXPIRATION * 0.45 * 1000); - NotifyTimer.Interval = RND.Next(MinVal, MaxVal); - NotifyTimer.AutoReset = true; - NotifyTimer.Start(); - */ NetInfo = new NetworkInfo(); SetupSessions(); } @@ -154,10 +143,6 @@ public void Dispose() private void SetupSessions() { - const int SIO_UDP_CONNRESET = -1744830452; - byte[] inValue = new byte[] { 0, 0, 0, 0 }; // == false - byte[] outValue = new byte[] { 0, 0, 0, 0 }; // initialize to 0 - IPAddress[] ips = NetInfo.GetLocalAddresses(); foreach (IPAddress addr in ips) { @@ -167,19 +152,14 @@ private void SetupSessions() { try { + + // IPV4 if (addr.AddressFamily == AddressFamily.InterNetwork) { UdpClient session = new UdpClient(AddressFamily.InterNetwork); try { session.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - } - catch (SocketException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); - } - try - { session.ExclusiveAddressUse = false; } catch (SocketException ex) @@ -187,60 +167,33 @@ private void SetupSessions() session.Client.Close(); OpenSource.Utilities.EventLogger.Log(ex); } - if (!Utils.IsMono()) - session.Client.Bind(new IPEndPoint(addr, 1900)); - else + +// TODO: commented because not working with dotnet >= 6 +// only binding all addresses will make UDP work properly (event-driven) +// if (!Utils.IsMono()) +// session.Client.Bind(new IPEndPoint(addr, 1900)); +// else session.Client.Bind(new IPEndPoint(IPAddress.Any, 1900)); + session.EnableBroadcast = true; session.JoinMulticastGroup(Utils.UpnpMulticastV4Addr, addr); - try - { -// session.Client.IOControl(SIO_UDP_CONNRESET, inValue, outValue); -session.Client.Disconnect(false); - } - catch (SocketException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); -// session.Client.Close(); - } -#if NET6_0_OR_GREATER - catch (NotSupportedException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); -// session.Client.Close(); - } -#endif - session.BeginReceive(new AsyncCallback(OnReceiveSink), new object[2] { session, new IPEndPoint(addr, ((IPEndPoint)session.Client.LocalEndPoint).Port) }); + session.BeginReceive(OnReceiveSink, new object[2] { session, new IPEndPoint(addr, ((IPEndPoint)session.Client.LocalEndPoint).Port) }); sessions[addr] = session; UdpClient usession = new UdpClient(AddressFamily.InterNetwork); usession.Client.Bind(new IPEndPoint(addr, 0)); - try - { -// session.Client.IOControl(SIO_UDP_CONNRESET, inValue, outValue); -session.Client.Disconnect(false); - } - catch (SocketException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); -// usession.Client.Close(); - } -#if NET6_0_OR_GREATER - catch (NotSupportedException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); -// session.Client.Close(); - } -#endif - usession.BeginReceive(new AsyncCallback(OnReceiveSink), new object[2] { usession, new IPEndPoint(addr, ((IPEndPoint)session.Client.LocalEndPoint).Port) }); + + usession.BeginReceive(OnReceiveSink, new object[2] { usession, new IPEndPoint(addr, ((IPEndPoint)session.Client.LocalEndPoint).Port) }); usessions[addr] = usession; } + + // IPV6 if (addr.AddressFamily == AddressFamily.InterNetworkV6) { - UdpClient session = new UdpClient(AddressFamily.InterNetworkV6); + UdpClient sessionIPv6 = new UdpClient(AddressFamily.InterNetworkV6); try { - session.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + sessionIPv6.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } catch (SocketException ex) { @@ -248,63 +201,32 @@ private void SetupSessions() } try { - session.ExclusiveAddressUse = false; + sessionIPv6.ExclusiveAddressUse = false; } catch (SocketException ex) { OpenSource.Utilities.EventLogger.Log(ex); } - if (!Utils.IsMono()) - session.Client.Bind(new IPEndPoint(addr, 1900)); - else - session.Client.Bind(new IPEndPoint(IPAddress.IPv6Any, 1900)); - session.EnableBroadcast = true; +// if (!Utils.IsMono()) +// session.Client.Bind(new IPEndPoint(addr, 1900)); +// else + sessionIPv6.Client.Bind(new IPEndPoint(IPAddress.IPv6Any, 1900)); + sessionIPv6.EnableBroadcast = true; if (addr.IsIPv6LinkLocal) - session.JoinMulticastGroup((int)addr.ScopeId, Utils.UpnpMulticastV6Addr2); + sessionIPv6.JoinMulticastGroup((int)addr.ScopeId, Utils.UpnpMulticastV6Addr2); else - session.JoinMulticastGroup((int)addr.ScopeId, Utils.UpnpMulticastV6Addr1); - try - { -// session.Client.IOControl(SIO_UDP_CONNRESET, inValue, outValue); -session.Client.Disconnect(false); - } - catch (SocketException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); -// session.Close(); - } -#if NET6_0_OR_GREATER - catch (NotSupportedException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); -// session.Client.Close(); - } -#endif - session.BeginReceive(new AsyncCallback(OnReceiveSink), new object[2] { session, new IPEndPoint(addr, ((IPEndPoint)session.Client.LocalEndPoint).Port) }); - sessions[addr] = session; + sessionIPv6.JoinMulticastGroup((int)addr.ScopeId, Utils.UpnpMulticastV6Addr1); - UdpClient usession = new UdpClient(AddressFamily.InterNetworkV6); - usession.Client.Bind(new IPEndPoint(addr, 0)); - try - { -// session.Client.IOControl(SIO_UDP_CONNRESET, inValue, outValue); -session.Client.Disconnect(false); - } - catch (SocketException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); -// usession.Close(); - } -#if NET6_0_OR_GREATER - catch (NotSupportedException ex) - { - OpenSource.Utilities.EventLogger.Log(ex); -// session.Client.Close(); - } -#endif - usession.BeginReceive(new AsyncCallback(OnReceiveSink), new object[2] { usession, new IPEndPoint(addr, ((IPEndPoint)session.Client.LocalEndPoint).Port) }); - usessions[addr] = usession; + sessionIPv6.BeginReceive(OnReceiveSink, new object[2] { sessionIPv6, new IPEndPoint(addr, ((IPEndPoint)sessionIPv6.Client.LocalEndPoint).Port) }); + sessions[addr] = sessionIPv6; + + UdpClient usessionIPv6 = new UdpClient(AddressFamily.InterNetworkV6); + usessionIPv6.Client.Bind(new IPEndPoint(addr, 0)); + + usessionIPv6.BeginReceive(OnReceiveSink, new object[2] { usessionIPv6, new IPEndPoint(addr, ((IPEndPoint)sessionIPv6.Client.LocalEndPoint).Port) }); + usessions[addr] = usessionIPv6; } + } catch (SocketException ex) { @@ -340,7 +262,7 @@ private void OnReceiveSink(IAsyncResult result) { OpenSource.Utilities.EventLogger.Log(ex); } - session.BeginReceive(new AsyncCallback(OnReceiveSink), args); + session.BeginReceive(OnReceiveSink, args); } catch (Exception ex) { @@ -351,17 +273,6 @@ private void OnReceiveSink(IAsyncResult result) } } - private void __NotifyCheck(SafeTimer_SINGLE sender) - { - if (OnRefresh != null) - OnRefresh(); - int MinVal = (int)((double)SSDP_EXPIRATION * 0.25 * 1000); - int MaxVal = (int)((double)SSDP_EXPIRATION * 0.45 * 1000); - sender.SetTimer(RND.Next(MinVal, MaxVal), __NotifyCheck); - //sender.SetTimer(RND.Next(MinVal, MaxVal), __NotifyCheck); - //NotifyTimer.Interval = RND.Next(MinVal, MaxVal); - } - /// /// Parses a URL /// diff --git a/UPnP/UPnPDevice.cs b/UPnP/UPnPDevice.cs index aaf0458..11a4158 100644 --- a/UPnP/UPnPDevice.cs +++ b/UPnP/UPnPDevice.cs @@ -23,8 +23,8 @@ limitations under the License. using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; -using OpenSource.Utilities; - +using OpenSource.Utilities; + namespace OpenSource.UPnP { /// @@ -398,7 +398,7 @@ internal UPnPDevice() if (DeviceCount == 0) { CPWebServerTable = new Hashtable(); - CPNetworkInfo = new NetworkInfo(new NetworkInfo.InterfaceHandler(NewCPInterface)); + CPNetworkInfo = new NetworkInfo(NewCPInterface); } else { @@ -406,10 +406,10 @@ internal UPnPDevice() for (int i = 0; i < alist.Length; ++i) { CP_RegisteredInterfaces[alist[i].ToString()] = true; - ((MiniWebServer)CPWebServerTable[alist[i].ToString()]).OnReceive += new MiniWebServer.HTTPReceiveHandler(HandleWebRequest); - ((MiniWebServer)CPWebServerTable[alist[i].ToString()]).OnHeader += new MiniWebServer.HTTPReceiveHandler(HandleHeaderRequest); + ((MiniWebServer)CPWebServerTable[alist[i].ToString()]).OnReceive += HandleWebRequest; + ((MiniWebServer)CPWebServerTable[alist[i].ToString()]).OnHeader += HandleHeaderRequest; } - CPNetworkInfo.OnNewInterface += new NetworkInfo.InterfaceHandler(NewCPInterface); + CPNetworkInfo.OnNewInterface += NewCPInterface; } ++DeviceCount; } @@ -661,11 +661,11 @@ public void AddDevice(UPnPDevice device) if (ControlPointOnly == false) { device.AddSubVirtualDirectory(device.UniqueDeviceName); - this.AddVirtualDirectory(device.UniqueDeviceName, new UPnPDevice.VirtualDirectoryHandler(device.HandleParent_Header), new UPnPDevice.VirtualDirectoryHandler(device.HandleParent)); + this.AddVirtualDirectory(device.UniqueDeviceName, device.HandleParent_Header, device.HandleParent); } else { - this.AddVirtualDirectory(device.UniqueDeviceName, null, new UPnPDevice.VirtualDirectoryHandler(device.EventProcesser)); + this.AddVirtualDirectory(device.UniqueDeviceName, null, device.EventProcesser); ProcessDevice_EVENTCALLBACK(this); } } @@ -711,8 +711,8 @@ private void NewCPInterface(NetworkInfo sender, IPAddress ip) if (CPWebServerTable.ContainsKey(ip.ToString()) == false) { MiniWebServer ws = new MiniWebServer(new IPEndPoint(ip, 0)); - ws.OnReceive += new MiniWebServer.HTTPReceiveHandler(HandleWebRequest); - ws.OnHeader += new MiniWebServer.HTTPReceiveHandler(HandleHeaderRequest); + ws.OnReceive += HandleWebRequest; + ws.OnHeader += HandleHeaderRequest; CPWebServerTable[ip.ToString()] = ws; } else @@ -720,8 +720,8 @@ private void NewCPInterface(NetworkInfo sender, IPAddress ip) if (CP_RegisteredInterfaces.ContainsKey(ip.ToString()) == false) { CP_RegisteredInterfaces[ip.ToString()] = true; - ((MiniWebServer)CPWebServerTable[ip.ToString()]).OnReceive += new MiniWebServer.HTTPReceiveHandler(HandleWebRequest); - ((MiniWebServer)CPWebServerTable[ip.ToString()]).OnHeader += new MiniWebServer.HTTPReceiveHandler(HandleHeaderRequest); + ((MiniWebServer)CPWebServerTable[ip.ToString()]).OnReceive += HandleWebRequest; + ((MiniWebServer)CPWebServerTable[ip.ToString()]).OnHeader += HandleHeaderRequest; } } @@ -769,7 +769,7 @@ public void UpdateDevice(Uri LocationUri, IPAddress HostInterface) { lock (UpdateTable) { - UPnPDeviceFactory df = new UPnPDeviceFactory(LocationUri, 250, new UPnPDeviceFactory.UPnPDeviceHandler(UpdateDeviceSink), null, null, null); + UPnPDeviceFactory df = new UPnPDeviceFactory(LocationUri, 250, UpdateDeviceSink, null, null, null); UpdateTable[df] = df; } } @@ -796,11 +796,11 @@ private void ManualNewDeviceInterface(IPAddress ip, int Port) { //String tmp = ip.ToString(); MiniWebServer WebServer = new MiniWebServer(new IPEndPoint(ip, Port)); - if ((this.OnSniff != null) || (this.OnSniffPacket != null)) - WebServer.OnSession += new MiniWebServer.NewSessionHandler(SniffSessionSink); + if ((OnSniff != null) || (OnSniffPacket != null)) + WebServer.OnSession += SniffSessionSink; - WebServer.OnReceive += new MiniWebServer.HTTPReceiveHandler(HandleWebRequest); - WebServer.OnHeader += new MiniWebServer.HTTPReceiveHandler(HandleHeaderRequest); + WebServer.OnReceive += HandleWebRequest; + WebServer.OnHeader += HandleHeaderRequest; WebServerTable[ip.ToString()] = WebServer; SendNotify(ip); } @@ -814,10 +814,10 @@ private void NewDeviceInterface(NetworkInfo sender, IPAddress ip) MiniWebServer WebServer; WebServer = new MiniWebServer(new IPEndPoint(ip, UseThisPort)); if ((this.OnSniff != null) || (this.OnSniffPacket != null)) - WebServer.OnSession += new MiniWebServer.NewSessionHandler(SniffSessionSink); + WebServer.OnSession += SniffSessionSink; - WebServer.OnReceive += new MiniWebServer.HTTPReceiveHandler(HandleWebRequest); - WebServer.OnHeader += new MiniWebServer.HTTPReceiveHandler(HandleHeaderRequest); + WebServer.OnReceive += HandleWebRequest; + WebServer.OnHeader += HandleHeaderRequest; WebServerTable[ip.ToString()] = WebServer; SendNotify(ip); } @@ -900,8 +900,8 @@ public void StartDevice() { if (IsRoot == true) { - NetInfo = new NetworkInfo(new NetworkInfo.InterfaceHandler(NewDeviceInterface)); - NetInfo.OnInterfaceDisabled += new NetworkInfo.InterfaceHandler(DisabledInterface); + NetInfo = new NetworkInfo(NewDeviceInterface); + NetInfo.OnInterfaceDisabled += DisabledInterface; Advertise(); } else @@ -958,19 +958,19 @@ private void SniffSessionSink(MiniWebServer Sender, HTTPSession s) { if (OnSniff != null) { - s.OnSniff += new HTTPSession.SniffHandler(SniffSessionSink2); + s.OnSniff += SniffSessionSink2; } else { if (OnSniffPacket == null) { - Sender.OnSession -= new MiniWebServer.NewSessionHandler(SniffSessionSink); + Sender.OnSession -= SniffSessionSink; } } if (OnSniffPacket != null) { - s.OnSniffPacket += new HTTPSession.ReceiveHandler(SniffSessionSink3); + s.OnSniffPacket += SniffSessionSink3; } } @@ -1342,7 +1342,7 @@ private void HandleWebRequest(HTTPMessage msg, HTTPSession WebSession) IPEndPoint d = new IPEndPoint(IPAddress.Parse(cbURL[x].Host), cbURL[x].Port); HTTPRequest R = new HTTPRequest(); - R.OnResponse += new HTTPRequest.RequestHandler(HandleInitialEvent); + R.OnResponse += HandleInitialEvent; this.InitialEventTable[R] = R; R.PipelineRequest(d, Response2, null); } diff --git a/UPnP/Utils.cs b/UPnP/Utils.cs index 423d141..9daf9c1 100644 --- a/UPnP/Utils.cs +++ b/UPnP/Utils.cs @@ -58,16 +58,5 @@ public static string GetMulticastAddrBraketPort(IPAddress addr) return ""; } - private static bool MonoDetected = false; - private static bool MonoActive = false; - - public static bool IsMono() - { - if (MonoDetected) - return MonoActive; - MonoActive = (Type.GetType("Mono.Runtime") != null); - MonoDetected = true; - return MonoActive; - } } }