@@ -568,6 +568,21 @@ const (
568
568
verbCancel = "cancel"
569
569
)
570
570
571
+ func executeSSH (ctx context.Context , sshConfig * ssh.SSHConfig , port int , command ... string ) error {
572
+ args := sshConfig .Args ()
573
+ args = append (args ,
574
+ "-p" , strconv .Itoa (port ),
575
+ "127.0.0.1" ,
576
+ "--" ,
577
+ )
578
+ args = append (args , command ... )
579
+ cmd := exec .CommandContext (ctx , sshConfig .Binary (), args ... )
580
+ if out , err := cmd .Output (); err != nil {
581
+ return fmt .Errorf ("failed to run %v: %q: %w" , cmd .Args , string (out ), err )
582
+ }
583
+ return nil
584
+ }
585
+
571
586
func forwardSSH (ctx context.Context , sshConfig * ssh.SSHConfig , port int , local , remote string , verb string , reverse bool ) error {
572
587
args := sshConfig .Args ()
573
588
args = append (args ,
@@ -595,6 +610,9 @@ func forwardSSH(ctx context.Context, sshConfig *ssh.SSHConfig, port int, local,
595
610
case verbForward :
596
611
if reverse {
597
612
logrus .Infof ("Forwarding %q (host) to %q (guest)" , local , remote )
613
+ if err := executeSSH (ctx , sshConfig , port , "rm" , "-f" , remote ); err != nil {
614
+ logrus .WithError (err ).Warnf ("Failed to clean up %q (guest) before setting up forwarding" , remote )
615
+ }
598
616
} else {
599
617
logrus .Infof ("Forwarding %q (guest) to %q (host)" , remote , local )
600
618
if err := os .RemoveAll (local ); err != nil {
@@ -607,6 +625,9 @@ func forwardSSH(ctx context.Context, sshConfig *ssh.SSHConfig, port int, local,
607
625
case verbCancel :
608
626
if reverse {
609
627
logrus .Infof ("Stopping forwarding %q (host) to %q (guest)" , local , remote )
628
+ if err := executeSSH (ctx , sshConfig , port , "rm" , "-f" , remote ); err != nil {
629
+ logrus .WithError (err ).Warnf ("Failed to clean up %q (guest) after stopping forwarding" , remote )
630
+ }
610
631
} else {
611
632
logrus .Infof ("Stopping forwarding %q (guest) to %q (host)" , remote , local )
612
633
defer func () {
@@ -622,7 +643,12 @@ func forwardSSH(ctx context.Context, sshConfig *ssh.SSHConfig, port int, local,
622
643
cmd := exec .CommandContext (ctx , sshConfig .Binary (), args ... )
623
644
if out , err := cmd .Output (); err != nil {
624
645
if verb == verbForward && strings .HasPrefix (local , "/" ) {
625
- if ! reverse {
646
+ if reverse {
647
+ logrus .WithError (err ).Warnf ("Failed to set up forward from %q (host) to %q (guest)" , local , remote )
648
+ if err := executeSSH (ctx , sshConfig , port , "rm" , "-f" , remote ); err != nil {
649
+ logrus .WithError (err ).Warnf ("Failed to clean up %q (guest) after forwarding failed" , remote )
650
+ }
651
+ } else {
626
652
logrus .WithError (err ).Warnf ("Failed to set up forward from %q (guest) to %q (host)" , remote , local )
627
653
if removeErr := os .RemoveAll (local ); err != nil {
628
654
logrus .WithError (removeErr ).Warnf ("Failed to clean up %q (host) after forwarding failed" , local )
0 commit comments