aboutsummaryrefslogtreecommitdiff
path: root/internal/options/options.go
blob: da63fc2a2973c1e12323598a9d391aa81c69a131 (plain)
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
49
50
51
52
53
54
55
56
// Package options provides parsing of user-provided onion-csr options
package options

import (
	"encoding/hex"
	"flag"
	"fmt"
	"os"
)

const usage = `Usage:

  onion-csr -h
  onion-csr -d HS_DIR -n NONCE

Options:

  -h, --help:      Output usage message and exit
  -d, --hs-dir:    Path to hidden service directory
  -n, --ca-nonce:  Nonce provided by a certificate authority in hex
`

// Options is a collection of onion-csr options
type Options struct {
	HSDir   string
	CANonce []byte

	caNonce string
}

// New parses user-supplied onion-csr options
func New(cmd string, args []string) (opts Options, err error) {
	fs := flag.NewFlagSet(cmd, flag.ContinueOnError)
	fs.Usage = func() { fmt.Fprintf(os.Stderr, "%s", usage) }
	stringOpt(fs, &opts.HSDir, "hs-dir", "d", "")
	stringOpt(fs, &opts.caNonce, "ca-nonce", "n", "")
	if err = fs.Parse(args); err != nil {
		return opts, err
	}

	if opts.HSDir == "" {
		return opts, fmt.Errorf("-d, --hs-dir: must not be an empty string")
	}
	if opts.CANonce, err = hex.DecodeString(opts.caNonce); err != nil {
		return opts, fmt.Errorf("-n, --ca-nonce: %v", err)
	}
	if len(opts.CANonce) == 0 {
		return opts, fmt.Errorf("-n, --ca-nonce: must not be empty string")
	}
	return opts, err
}

func stringOpt(fs *flag.FlagSet, opt *string, short, long, value string) {
	fs.StringVar(opt, short, value, "")
	fs.StringVar(opt, long, value, "")
}