From 9678daeafa083d2cba477ae8c7140e5a085b2223 Mon Sep 17 00:00:00 2001
From: Asim Aslam <asim@aslam.me>
Date: Sat, 30 Nov 2019 01:14:40 +0000
Subject: [PATCH] fix bug in the tunnel which causes multicast connections to
 be closed

---
 tunnel/default.go  | 9 ++++++---
 tunnel/listener.go | 3 ++-
 tunnel/session.go  | 5 +++++
 3 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/tunnel/default.go b/tunnel/default.go
index 72963f0c..fc24ee9d 100644
--- a/tunnel/default.go
+++ b/tunnel/default.go
@@ -93,6 +93,9 @@ func (t *tun) getSession(channel, session string) (*session, bool) {
 // delSession deletes a session if it exists
 func (t *tun) delSession(channel, session string) {
 	t.Lock()
+	if s, ok := t.sessions[channel+session]; ok {
+		s.Close()
+	}
 	delete(t.sessions, channel+session)
 	t.Unlock()
 }
@@ -512,10 +515,10 @@ func (t *tun) listen(link *link) {
 			}
 
 			// try get the dialing socket
-			s, exists := t.getSession(channel, sessionId)
+			_, exists := t.getSession(channel, sessionId)
 			if exists {
-				// close and continue
-				s.Close()
+				// delete and continue
+				t.delSession(channel, sessionId)
 				continue
 			}
 			// otherwise its a session mapping of sorts
diff --git a/tunnel/listener.go b/tunnel/listener.go
index cc207d70..62883777 100644
--- a/tunnel/listener.go
+++ b/tunnel/listener.go
@@ -66,6 +66,7 @@ func (t *tunListener) process() {
 			sess, ok := conns[m.session]
 			log.Debugf("Tunnel listener received channel %s session %s exists: %t", m.channel, m.session, ok)
 			if !ok {
+				// we only process open and session types
 				switch m.typ {
 				case "open", "session":
 				default:
@@ -87,7 +88,7 @@ func (t *tunListener) process() {
 					// the link the message was received on
 					link: m.link,
 					// set the connection mode
-					mode: m.mode,
+					mode: t.session.mode,
 					// close chan
 					closed: make(chan bool),
 					// recv called by the acceptor
diff --git a/tunnel/session.go b/tunnel/session.go
index 4b8721aa..a0dbef93 100644
--- a/tunnel/session.go
+++ b/tunnel/session.go
@@ -413,6 +413,11 @@ func (s *session) Close() error {
 	default:
 		close(s.closed)
 
+		// don't broadcast the close for multicast
+		if s.mode != Unicast {
+			return nil
+		}
+
 		// append to backlog
 		msg := s.newMessage("close")
 		// no error response on close