Debian Codegraph @

buildkit/client/connhelper/ssh/ssh.go

raw
1 // Package ssh provides connhelper for ssh://<SSH URL>
2 package ssh
3
4 import (
5 "context"
6 "net"
7 "net/url"
8
9 "github.com/docker/cli/cli/connhelper/commandconn"
10 "github.com/moby/buildkit/client/connhelper"
11 "github.com/pkg/errors"
12 )
13
14 func init() {
15 connhelper.Register("ssh", Helper)
16 }
17
18 // Helper returns helper for connecting through an SSH URL.
19 func Helper(u *url.URL) (*connhelper.ConnectionHelper, error) {
20 sp, err := SpecFromURL(u)
21 if err != nil {
22 return nil, err
23 }
24 return &connhelper.ConnectionHelper{
25 ContextDialer: func(ctx context.Context, addr string) (net.Conn, error) {
26 args := []string{}
27 if sp.User != "" {
28 args = append(args, "-l", sp.User)
29 }
30 if sp.Port != "" {
31 args = append(args, "-p", sp.Port)
32 }
33 args = append(args, "--", sp.Host)
34 args = append(args, "buildctl")
35 if socket := sp.Socket; socket != "" {
36 args = append(args, "--addr", "unix://"+socket)
37 }
38 args = append(args, "dial-stdio")
39 // using background context because context remains active for the duration of the process, after dial has completed
40 return commandconn.New(context.Background(), "ssh", args...)
41 },
42 }, nil
43 }
44
45 // Spec
46 type Spec struct {
47 User string
48 Host string
49 Port string
50 Socket string
51 }
52
53 // SpecFromURL creates Spec from URL.
54 // URL is like ssh://<user>@host:<port>
55 // Only <host> part is mandatory.
56 func SpecFromURL(u *url.URL) (*Spec, error) {
57 sp := Spec{
58 Host: u.Hostname(),
59 Port: u.Port(),
60 Socket: u.Path,
61 }
62 if user := u.User; user != nil {
63 sp.User = user.Username()
64 if _, ok := user.Password(); ok {
65 return nil, errors.New("plain-text password is not supported")
66 }
67 }
68 if sp.Host == "" {
69 return nil, errors.Errorf("no host specified")
70 }
71 if u.RawQuery != "" {
72 return nil, errors.Errorf("extra query after the host: %q", u.RawQuery)
73 }
74 if u.Fragment != "" {
75 return nil, errors.Errorf("extra fragment after the host: %q", u.Fragment)
76 }
77 return &sp, nil
78 }