aboutsummaryrefslogtreecommitdiffstats
path: root/handshake/handshake.go
blob: e5e3c37dc5c5e8f784dbee98790ce722eac1cbfa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package handshake

import (
	"context"
	"golang.org/x/sync/errgroup"
	"time"

	"git.samanthony.xyz/hose/util"
)

const (
	port    = "60322"
	network = "tcp"

	timeout       = 1 * time.Minute
	retryInterval = 500 * time.Millisecond
)

// Handshake exchanges public keys with a remote host.
// The user is asked to verify the received keys before they are saved in the known hosts file.
func Handshake(rhost string) error {
	util.Logf("initiating handshake with %s...", rhost)

	errs := make(chan error, 2)
	defer close(errs)

	group, ctx := errgroup.WithContext(context.Background())
	group.Go(func() error {
		if err := send(rhost); err != nil {
			errs <- err
		}
		return nil
	})
	group.Go(func() error {
		if err := receive(rhost); err != nil {
			errs <- err
		}
		return nil
	})
	go func() { group.Wait() }() // cancel the context.

	select {
	case err := <-errs:
		return err
	case <-ctx.Done():
		return nil
	}
}