|
| 1 | +//go:build darwin |
| 2 | + |
| 3 | +package cli |
| 4 | + |
| 5 | +import ( |
| 6 | + "cdr.dev/slog" |
| 7 | + "github.com/coder/coder/v2/vpn" |
| 8 | + "github.com/coder/serpent" |
| 9 | + "golang.org/x/sys/unix" |
| 10 | + "golang.org/x/xerrors" |
| 11 | +) |
| 12 | + |
| 13 | +func (r *RootCmd) vpnDaemonRun() *serpent.Command { |
| 14 | + var ( |
| 15 | + rpcReadHandleInt int64 |
| 16 | + rpcWriteHandleInt int64 |
| 17 | + ) |
| 18 | + |
| 19 | + cmd := &serpent.Command{ |
| 20 | + Use: "run", |
| 21 | + Short: "Run the VPN daemon on macOS.", |
| 22 | + Middleware: serpent.Chain( |
| 23 | + serpent.RequireNArgs(0), |
| 24 | + ), |
| 25 | + Options: serpent.OptionSet{ |
| 26 | + { |
| 27 | + Flag: "rpc-read-handle", |
| 28 | + Env: "CODER_VPN_DAEMON_RPC_READ_HANDLE", |
| 29 | + Description: "The handle for the pipe to read from the RPC connection.", |
| 30 | + Value: serpent.Int64Of(&rpcReadHandleInt), |
| 31 | + Required: true, |
| 32 | + }, |
| 33 | + { |
| 34 | + Flag: "rpc-write-handle", |
| 35 | + Env: "CODER_VPN_DAEMON_RPC_WRITE_HANDLE", |
| 36 | + Description: "The handle for the pipe to write to the RPC connection.", |
| 37 | + Value: serpent.Int64Of(&rpcWriteHandleInt), |
| 38 | + Required: true, |
| 39 | + }, |
| 40 | + }, |
| 41 | + Handler: func(inv *serpent.Invocation) error { |
| 42 | + ctx := inv.Context() |
| 43 | + |
| 44 | + if rpcReadHandleInt < 0 || rpcWriteHandleInt < 0 { |
| 45 | + return xerrors.Errorf("rpc-read-handle (%v) and rpc-write-handle (%v) must be positive", rpcReadHandleInt, rpcWriteHandleInt) |
| 46 | + } |
| 47 | + if rpcReadHandleInt == rpcWriteHandleInt { |
| 48 | + return xerrors.Errorf("rpc-read-handle (%v) and rpc-write-handle (%v) must be different", rpcReadHandleInt, rpcWriteHandleInt) |
| 49 | + } |
| 50 | + |
| 51 | + pipe, err := vpn.NewBidirectionalPipe(uintptr(rpcReadHandleInt), uintptr(rpcWriteHandleInt)) |
| 52 | + if err != nil { |
| 53 | + return xerrors.Errorf("create bidirectional RPC pipe: %w", err) |
| 54 | + } |
| 55 | + defer pipe.Close() |
| 56 | + |
| 57 | + tunnel, err := vpn.NewTunnel(ctx, slog.Make().Leveled(slog.LevelDebug), pipe, |
| 58 | + vpn.NewClient(), |
| 59 | + vpn.UseOSNetworkingStack(), |
| 60 | + vpn.UseAsLogger(), |
| 61 | + ) |
| 62 | + if err != nil { |
| 63 | + unix.Close(int(rpcReadHandleInt)) |
| 64 | + unix.Close(int(rpcWriteHandleInt)) |
| 65 | + return xerrors.Errorf("create new tunnel for client: %w", err) |
| 66 | + } |
| 67 | + defer tunnel.Close() |
| 68 | + |
| 69 | + <-ctx.Done() |
| 70 | + return nil |
| 71 | + }, |
| 72 | + } |
| 73 | + |
| 74 | + return cmd |
| 75 | +} |
0 commit comments