#!/bin/sh

# -------------------------------------------------------------------------- #
# Copyright 2002-2025, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

##############################################################################
# WARNING: The arguments of the 'find' command below must be aligned with
# 'ControlPath' and 'ControlPersist' options in oneadmin's SSH configuration
# (/var/lib/one/.ssh/config) otherwise it will not have the desired effect!
##############################################################################

# This script enforce the cleanup of all oneadmin's SSH master sockets for the
# persistent connections when they reach their age of one minute. It as a
# workaround to a race condition inside the OpenSSH which occurs during the
# closing of the master sockets.
# Possibly related to: https://bugzilla.mindrot.org/show_bug.cgi?id=3067

find /var/run/one/ssh-socks \
    -maxdepth 1 \
    -type s \
    -name 'ctl-M-*.sock' \
    -mmin +1 \
    -print | while read -r sockname ; do
        # atomic operation - no other ssh client should be disrupted
        mv -f "$sockname" "$sockname"~todelete

        # stop the multiplexing ('this' is just unnecessary gibberish)
        ssh -S "$sockname"~todelete -O stop this </dev/null >/dev/null

        # delete the old socket
        rm -f "$sockname"~todelete
    done
