Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
190 lines (174 loc) · 5.31 KB
/
Copy pathmain.go
File metadata and controls
190 lines (174 loc) · 5.31 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
)
var version = "dev"
// options are everything the command line can say, parsed once and reused by the
// foreground path, the service path and `install` (which bakes them back into the
// service's command line).
type options struct {
localOnly bool
days int
data string
port int
logFile string // set only on the elevated re-launch; see elevate_windows.go
rawArgs []string // as given, for install to replay
}
func main() {
log.SetFlags(log.LstdFlags)
args := os.Args[1:]
// Subcommands come before flag parsing, so `pingping install --port 9000`
// reads the way a Windows admin expects rather than the way Go's flag package
// would otherwise insist on.
verb := ""
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
verb = args[0]
}
switch verb {
case "help":
printHelp(os.Stdout)
return
case "version":
fmt.Println("pingping", version)
return
case "selftest":
runSelftest(os.Stdout)
return
case "run", "install", "uninstall", "tray", "console", "firewall":
args = args[1:]
case "":
default:
fmt.Fprintf(os.Stderr, "pingping: unknown command %q\nRun 'pingping help' for examples.\n", verb)
os.Exit(2)
}
opt, err := parseOptions(args)
if err != nil {
if err == flag.ErrHelp {
printHelp(os.Stdout)
return
}
fmt.Fprintf(os.Stderr, "pingping: %v\nRun 'pingping help' for examples.\n", err)
os.Exit(2)
}
// install/uninstall need Administrator. On Windows this elevates itself rather
// than telling the operator to go and open a different window.
if verb == "install" || verb == "uninstall" {
os.Exit(runServiceVerb(verb, opt))
}
// The tray companion to an installed service: a separate process in the
// logged-in user's session, because a service cannot display UI at all.
if verb == "tray" {
os.Exit(runTrayCompanion(opt))
}
if verb == "firewall" {
os.Exit(runFirewallVerb(opt))
}
// `console`, and a bare launch of an installed copy, both mean "show me the
// console". Only `run` and a portable copy serve in the foreground.
//
// The distinction matters because the two used to be the same thing: the
// Start Menu shortcut passed no arguments, so double-clicking it started a
// second server on the port the service already held, which failed to bind
// and exited before the window could be read.
if verb == "console" || verb == "" {
if code, handled := openConsoleForInstalled(opt); handled {
os.Exit(code)
}
if verb == "console" {
fmt.Fprintln(os.Stderr, "pingping: no installed service found on this machine.\n"+
"Run 'pingping install' first, or 'pingping run' to serve from this folder.")
os.Exit(2)
}
}
// Started by the service control manager rather than a person: hand over to the
// platform's service loop, which calls back into startApp.
if isService() {
if err := runAsService(opt); err != nil {
log.Fatalf("service: %v", err)
}
return
}
if err := serveForeground(opt); err != nil {
log.Fatal(err)
}
}
func parseOptions(args []string) (options, error) {
var opt options
opt.rawArgs = append([]string(nil), args...)
fs := flag.NewFlagSet("pingping", flag.ContinueOnError)
fs.SetOutput(io.Discard)
localOnly := fs.Bool("localhost", false, "bind 127.0.0.1 only")
days := fs.Int("days", 0, "days of history to keep (default 300)")
data := fs.String("data", "", "data directory (default: portable ./data beside the exe, else the system location)")
port := fs.Int("port", 0, "console port (default 8518)")
logFile := fs.String("log-file", "", "") // internal: the elevated child writes here
showVer := fs.Bool("version", false, "print version")
if err := fs.Parse(args); err != nil {
return opt, err
}
if *showVer {
fmt.Println("pingping", version)
os.Exit(0)
}
if rest := fs.Args(); len(rest) > 0 {
return opt, fmt.Errorf("unexpected argument %q", rest[0])
}
opt.localOnly, opt.days, opt.data, opt.port = *localOnly, *days, *data, *port
opt.logFile = *logFile
return opt, nil
}
// configure turns options into the runtime Config. Credentials are deliberately
// absent: they live in the database, set on first run through the console.
func configure(opt options) (*Config, bool, error) {
cfg := defaultConfig()
if opt.days > 0 {
cfg.RetentionDays = opt.days
}
if opt.port < 0 || opt.port > 65535 {
return nil, false, fmt.Errorf("--port must be 1-65535")
}
if opt.port > 0 {
cfg.Listen = hostOf(cfg.Listen) + ":" + strconv.Itoa(opt.port)
}
if opt.localOnly {
cfg.Listen = "127.0.0.1" + portOf(cfg.Listen)
}
dir, portable := resolveDataDir(opt.data)
cfg.DataDir = dir
return cfg, portable, nil
}
func serveForeground(opt options) error {
cfg, portable, err := configure(opt)
if err != nil {
return err
}
a, err := startApp(cfg, opt.port, opt.localOnly)
if err != nil {
return err
}
a.banner(portable)
// Windows only: a tray icon so a double-clicked copy is not a console window
// with no other affordance. Closing it from the menu stops the program.
quit := make(chan struct{})
var once sync.Once
startForegroundTray("http://localhost"+portOf(cfg.Listen),
func() { once.Do(func() { close(quit) }) })
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
select {
case <-sig:
case <-quit:
}
a.shutdown()
log.Printf("pingping shut down")
return nil
}