| 1 |
// Copyright (c) 2014-2019 Ludovic Fauvet |
| 2 |
// Licensed under the MIT license |
| 3 |
|
| 4 |
package cli |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"fmt" |
| 9 |
"os" |
| 10 |
"strconv" |
| 11 |
|
| 12 |
"github.com/etix/mirrorbits/core" |
| 13 |
"github.com/etix/mirrorbits/rpc" |
| 14 |
"github.com/golang/protobuf/ptypes/empty" |
| 15 |
"google.golang.org/grpc" |
| 16 |
"google.golang.org/grpc/codes" |
| 17 |
"google.golang.org/grpc/status" |
| 18 |
) |
| 19 |
|
| 20 |
func (c *cli) GetRPC() rpc.CLIClient { |
| 21 |
c.Lock() |
| 22 |
defer c.Unlock() |
| 23 |
|
| 24 |
if c.rpcconn == nil { |
| 25 |
conn, err := grpc.Dial(core.RPCHost+":"+strconv.FormatUint(uint64(core.RPCPort), 10), |
| 26 |
grpc.WithInsecure(), |
| 27 |
grpc.WithBlock(), |
| 28 |
grpc.FailOnNonTempDialError(true), |
| 29 |
grpc.WithPerRPCCredentials(c.creds)) |
| 30 |
if err != nil { |
| 31 |
fmt.Fprintf(os.Stderr, "rpc: %s\n", err) |
| 32 |
os.Exit(1) |
| 33 |
} |
| 34 |
c.rpcconn = conn |
| 35 |
client := rpc.NewCLIClient(c.rpcconn) |
| 36 |
_, err = client.Ping(context.Background(), &empty.Empty{}) |
| 37 |
s := status.Convert(err) |
| 38 |
if s.Code() == codes.Unauthenticated { |
| 39 |
if len(c.creds.Password) == 0 { |
| 40 |
fmt.Fprintf(os.Stderr, "Please set the server password with the -P option.\n") |
| 41 |
} else { |
| 42 |
fmt.Fprintf(os.Stderr, "Password refused\n") |
| 43 |
} |
| 44 |
os.Exit(1) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
return rpc.NewCLIClient(c.rpcconn) |
| 49 |
} |
| 50 |
|
| 51 |
type loginCreds struct { |
| 52 |
Password string |
| 53 |
} |
| 54 |
|
| 55 |
func (c *loginCreds) GetRequestMetadata(context.Context, ...string) (map[string]string, error) { |
| 56 |
return map[string]string{ |
| 57 |
"password": c.Password, |
| 58 |
}, nil |
| 59 |
} |
| 60 |
|
| 61 |
func (c *loginCreds) RequireTransportSecurity() bool { |
| 62 |
return false |
| 63 |
} |