This repository has been archived by the owner on Nov 2, 2018. It is now read-only.
/
daemon.go
243 lines (217 loc) · 7.17 KB
/
daemon.go
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main
import (
"errors"
"fmt"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/NebulousLabs/Sia/build"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/modules"
"github.com/NebulousLabs/Sia/profile"
mnemonics "github.com/NebulousLabs/entropy-mnemonics"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
)
// passwordPrompt securely reads a password from stdin.
func passwordPrompt(prompt string) (string, error) {
fmt.Print(prompt)
pw, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Println()
return string(pw), err
}
// verifyAPISecurity checks that the security values are consistent with a
// sane, secure system.
func verifyAPISecurity(config Config) error {
// Make sure that only the loopback address is allowed unless the
// --disable-api-security flag has been used.
if !config.Siad.AllowAPIBind {
addr := modules.NetAddress(config.Siad.APIaddr)
if !addr.IsLoopback() {
if addr.Host() == "" {
return fmt.Errorf("a blank host will listen on all interfaces, did you mean localhost:%v?\nyou must pass --disable-api-security to bind Siad to a non-localhost address", addr.Port())
}
return errors.New("you must pass --disable-api-security to bind Siad to a non-localhost address")
}
return nil
}
// If the --disable-api-security flag is used, enforce that
// --authenticate-api must also be used.
if config.Siad.AllowAPIBind && !config.Siad.AuthenticateAPI {
return errors.New("cannot use --disable-api-security without setting an api password")
}
return nil
}
// processNetAddr adds a ':' to a bare integer, so that it is a proper port
// number.
func processNetAddr(addr string) string {
_, err := strconv.Atoi(addr)
if err == nil {
return ":" + addr
}
return addr
}
// processModules makes the modules string lowercase to make checking if a
// module in the string easier, and returns an error if the string contains an
// invalid module character.
func processModules(modules string) (string, error) {
modules = strings.ToLower(modules)
validModules := "cghmrtwe"
invalidModules := modules
for _, m := range validModules {
invalidModules = strings.Replace(invalidModules, string(m), "", 1)
}
if len(invalidModules) > 0 {
return "", errors.New("Unable to parse --modules flag, unrecognized or duplicate modules: " + invalidModules)
}
return modules, nil
}
// processProfileFlags checks that the flags given for profiling are valid.
func processProfileFlags(profile string) (string, error) {
profile = strings.ToLower(profile)
validProfiles := "cmt"
invalidProfiles := profile
for _, p := range validProfiles {
invalidProfiles = strings.Replace(invalidProfiles, string(p), "", 1)
}
if len(invalidProfiles) > 0 {
return "", errors.New("Unable to parse --profile flags, unrecognized or duplicate flags: " + invalidProfiles)
}
return profile, nil
}
// processConfig checks the configuration values and performs cleanup on
// incorrect-but-allowed values.
func processConfig(config Config) (Config, error) {
var err1, err2 error
config.Siad.APIaddr = processNetAddr(config.Siad.APIaddr)
config.Siad.RPCaddr = processNetAddr(config.Siad.RPCaddr)
config.Siad.HostAddr = processNetAddr(config.Siad.HostAddr)
config.Siad.Modules, err1 = processModules(config.Siad.Modules)
config.Siad.Profile, err2 = processProfileFlags(config.Siad.Profile)
err3 := verifyAPISecurity(config)
err := build.JoinErrors([]error{err1, err2, err3}, ", and ")
if err != nil {
return Config{}, err
}
return config, nil
}
// unlockWallet is called on siad startup and attempts to automatically
// unlock the wallet with the given password string.
func unlockWallet(w modules.Wallet, password string) error {
var validKeys []crypto.TwofishKey
dicts := []mnemonics.DictionaryID{"english", "german", "japanese"}
for _, dict := range dicts {
seed, err := modules.StringToSeed(password, dict)
if err != nil {
continue
}
validKeys = append(validKeys, crypto.TwofishKey(crypto.HashObject(seed)))
}
validKeys = append(validKeys, crypto.TwofishKey(crypto.HashObject(password)))
for _, key := range validKeys {
if err := w.Unlock(key); err == nil {
return nil
}
}
return modules.ErrBadEncryptionKey
}
// startDaemon uses the config parameters to initialize Sia modules and start
// siad.
func startDaemon(config Config) (err error) {
if config.Siad.AuthenticateAPI {
password := os.Getenv("SIA_API_PASSWORD")
if password != "" {
fmt.Println("Using SIA_API_PASSWORD environment variable")
config.APIPassword = password
} else {
// Prompt user for API password.
config.APIPassword, err = passwordPrompt("Enter API password: ")
if err != nil {
return err
}
if config.APIPassword == "" {
return errors.New("password cannot be blank")
}
}
}
// Print the siad Version and GitRevision
fmt.Println("Sia Daemon v" + build.Version)
if build.GitRevision == "" {
fmt.Println("WARN: compiled without build commit or version. To compile correctly, please use the makefile")
} else {
fmt.Println("Git Revision " + build.GitRevision)
}
// Install a signal handler that will catch exceptions thrown by mmap'd
// files.
// NOTE: ideally we would catch SIGSEGV here too, since that signal can
// also be thrown by an mmap I/O error. However, SIGSEGV can occur under
// other circumstances as well, and in those cases, we will want a full
// stack trace.
mmapChan := make(chan os.Signal, 1)
signal.Notify(mmapChan, syscall.SIGBUS)
go func() {
<-mmapChan
fmt.Println("A fatal I/O exception (SIGBUS) has occurred.")
fmt.Println("Please check your disk for errors.")
os.Exit(1)
}()
// Print a startup message.
fmt.Println("Loading...")
loadStart := time.Now()
srv, err := NewServer(config)
if err != nil {
return err
}
errChan := make(chan error)
go func() {
errChan <- srv.Serve()
}()
err = srv.loadModules()
if err != nil {
return err
}
// listen for kill signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, os.Kill, syscall.SIGTERM)
// Print a 'startup complete' message.
startupTime := time.Since(loadStart)
fmt.Println("Finished loading in", startupTime.Seconds(), "seconds")
// wait for Serve to return or for kill signal to be caught
err = func() error {
select {
case err := <-errChan:
return err
case <-sigChan:
fmt.Println("\rCaught stop signal, quitting...")
return srv.Close()
}
}()
if err != nil {
build.Critical(err)
}
return nil
}
// startDaemonCmd is a passthrough function for startDaemon.
func startDaemonCmd(cmd *cobra.Command, _ []string) {
var profileCPU, profileMem, profileTrace bool
profileCPU = strings.Contains(globalConfig.Siad.Profile, "c")
profileMem = strings.Contains(globalConfig.Siad.Profile, "m")
profileTrace = strings.Contains(globalConfig.Siad.Profile, "t")
if build.DEBUG {
profileCPU = true
profileMem = true
}
if profileCPU || profileMem || profileTrace {
go profile.StartContinuousProfile(globalConfig.Siad.ProfileDir, profileCPU, profileMem, profileTrace)
}
// Start siad. startDaemon will only return when it is shutting down.
err := startDaemon(globalConfig)
if err != nil {
die(err)
}
// Daemon seems to have closed cleanly. Print a 'closed' mesasge.
fmt.Println("Shutdown complete.")
}