package bridge

import (
	
	

	
	
)

// Clean clears long standing sessions from memory
func () {
	 := time.Now()
	for ,  := range Sessions.Connections {
		if .Sub(.LastConnection).Seconds() > 266 {
			closeSession(, )
			continue
		}

		if .SSH == nil {
			continue
		}

		if .IpAddr != "" && .Port != "" {
			,  := helpers.ResolveIP(.IpAddr)
			if  != nil {
				closeSession(, )
				continue
			}

			_,  = net.DialTimeout(
				"tcp",
				net.JoinHostPort(, .Port),
				10*time.Second,
			)
			if  != nil {
				closeSession(, )
				continue
			}
		}

		 := make(chan int, 1)
		go func() {
			select {
			case <-time.After(10 * time.Second):
			case <-:
				return
			default:
				, ,  := .SSH.SendRequest("keepalive@liman.dev", true, nil)
				if  != nil {
					closeSession(, )
					logger.Sugar().Warnw("error when sending request")
				}

				 <- 1
			}
		}()

		select {
		case <-:
			continue
		case <-time.After(10 * time.Second):
			closeSession(, )
			continue
		}
	}

	for ,  := range Tunnels.Connections {
		if .Sub(.LastConnection).Seconds() > 266 || .SshClient == nil {
			closeTunnel(, )
			continue
		}

		,  := net.DialTimeout(
			"tcp",
			.hostAddr,
			10*time.Second,
		)
		if  != nil {
			closeTunnel(, )
			continue
		}

		 := make(chan int, 1)
		go func() {
			select {
			case <-time.After(10 * time.Second):
			case <-:
				return
			default:
				, ,  := .SshClient.SendRequest("keepalive@openssh.com", true, nil)
				if  != nil {
					if .SshClient != nil {
						.SshClient.Close()
					}
					closeTunnel(, )
					logger.Sugar().Warnw("error when sending request")
				}

				 <- 1
			}
		}()

		select {
		case <-:
			continue
		case <-time.After(10 * time.Second):
			closeTunnel(, )
			continue
		}
	}

	time.Sleep(10 * time.Second)
	go ()
}

func closeSession( *Session,  string) {
	.Mutex.Lock()
	.CloseAllConnections()
	Sessions.Delete()
	.Mutex.Unlock()
}

func closeTunnel( *Tunnel,  string) {
	.Mutex.Lock()
	.Stop()
	Tunnels.Delete()
	.Mutex.Unlock()
}