forked from perkeep/perkeep
/
config.go
271 lines (237 loc) · 6.9 KB
/
config.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package client
import (
"flag"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"camlistore.org/pkg/auth"
"camlistore.org/pkg/blobref"
"camlistore.org/pkg/jsonconfig"
"camlistore.org/pkg/jsonsign"
"camlistore.org/pkg/osutil"
)
// These, if set, override the JSON config file ~/.camlistore/config
// "server" and "password" keys.
//
// A main binary must call AddFlags to expose these.
var (
flagServer string
flagSecretRing string
)
func AddFlags() {
defaultPath := ConfigFilePath()
flag.StringVar(&flagServer, "server", "", "Camlistore server prefix. If blank, the default from the \"server\" field of "+defaultPath+" is used. Acceptable forms: https://you.example.com, example.com:1345 (https assumed), or http://you.example.com/alt-root")
flag.StringVar(&flagSecretRing, "secret-keyring", "", "GnuPG secret keyring file to use.")
}
// ExplicitServer returns the blobserver given in the flags, if any.
func ExplicitServer() string {
return flagServer
}
func ConfigFilePath() string {
return filepath.Join(osutil.CamliConfigDir(), "config")
}
var configOnce sync.Once
var config = make(map[string]interface{})
var parseConfigErr error
func parseConfig() {
configPath := ConfigFilePath()
if _, err := os.Stat(configPath); os.IsNotExist(err) {
parseConfigErr = os.ErrNotExist
return
}
var err error
if config, err = jsonconfig.ReadFile(configPath); err != nil {
log.Fatal(err.Error())
return
}
}
func cleanServer(server string) string {
// Remove trailing slash if provided.
if strings.HasSuffix(server, "/") {
server = server[0 : len(server)-1]
}
// Default to "https://" when not specified
if !strings.HasPrefix(server, "http") && !strings.HasPrefix(server, "https") {
server = "https://" + server
}
return server
}
func serverOrDie() string {
if flagServer != "" {
return cleanServer(flagServer)
}
configOnce.Do(parseConfig)
value, ok := config["server"]
var server string
if ok {
server = value.(string)
}
server = cleanServer(server)
if !ok || server == "" {
log.Fatalf("Missing or invalid \"server\" in %q", ConfigFilePath())
}
return server
}
func (c *Client) useTLS() bool {
return strings.HasPrefix(c.server, "https://")
}
func (c *Client) SetupAuth() error {
if flagServer != "" {
// If using an explicit blobserver, don't use auth
// configured from the config file, so we don't send
// our password to a friend's blobserver.
var err error
c.authMode, err = auth.FromEnv()
if err == auth.ErrNoAuth {
log.Printf("Using explicit --server parameter; not using config file auth, and no auth mode set in environment")
}
return err
}
configOnce.Do(parseConfig)
return c.SetupAuthFromConfig(config)
}
func (c *Client) SetupAuthFromConfig(conf jsonconfig.Obj) error {
var err error
value, ok := conf["auth"]
authString := ""
if ok {
authString, ok = value.(string)
c.authMode, err = auth.FromConfig(authString)
} else {
c.authMode, err = auth.FromEnv()
}
return err
}
// Returns blobref of signer's public key, or nil if unconfigured.
func (c *Client) SignerPublicKeyBlobref() *blobref.BlobRef {
return SignerPublicKeyBlobref()
}
func (c *Client) SecretRingFile() string {
if flagSecretRing != "" {
return flagSecretRing
}
configOnce.Do(parseConfig)
keyRing, ok := config["secretRing"].(string)
if ok && keyRing != "" {
return keyRing
}
if keyRing = osutil.IdentitySecretRing(); fileExists(keyRing) {
return keyRing
}
return jsonsign.DefaultSecRingPath()
}
func fileExists(name string) bool {
_, err := os.Stat(name)
return err == nil
}
var (
signerPublicKeyRefOnce sync.Once
signerPublicKeyRef *blobref.BlobRef
)
// TODO: move to config package?
func SignerPublicKeyBlobref() *blobref.BlobRef {
signerPublicKeyRefOnce.Do(initSignerPublicKeyBlobref)
return signerPublicKeyRef
}
func initSignerPublicKeyBlobref() {
signerPublicKeyRef = getSignerPublicKeyBlobref()
}
func getSignerPublicKeyBlobref() *blobref.BlobRef {
configOnce.Do(parseConfig)
key := "keyId"
keyId, ok := config[key].(string)
if !ok {
log.Printf("No key %q in JSON configuration file %q; have you run \"camput init\"?", key, ConfigFilePath())
return nil
}
keyRing, hasKeyRing := config["secretRing"].(string)
if !hasKeyRing {
if fn := osutil.IdentitySecretRing(); fileExists(fn) {
keyRing = fn
} else if fn := jsonsign.DefaultSecRingPath(); fileExists(fn) {
keyRing = fn
} else {
log.Printf("Couldn't find keyId %q; no 'secretRing' specified in config file, and no standard secret ring files exist.")
return nil
}
}
entity, err := jsonsign.EntityFromSecring(keyId, keyRing)
if err != nil {
log.Printf("Couldn't find keyId %q in secret ring: %v", keyId, err)
return nil
}
armored, err := jsonsign.ArmoredPublicKey(entity)
if err != nil {
log.Printf("Error serializing public key: %v", err)
return nil
}
selfPubKeyDir, ok := config["selfPubKeyDir"].(string)
if !ok {
log.Printf("No 'selfPubKeyDir' defined in %q", ConfigFilePath())
return nil
}
fi, err := os.Stat(selfPubKeyDir)
if err != nil || !fi.IsDir() {
log.Printf("selfPubKeyDir of %q doesn't exist or not a directory", selfPubKeyDir)
return nil
}
br := blobref.SHA1FromString(armored)
pubFile := filepath.Join(selfPubKeyDir, br.String()+".camli")
fi, err = os.Stat(pubFile)
if err != nil {
err = ioutil.WriteFile(pubFile, []byte(armored), 0644)
if err != nil {
log.Printf("Error writing public key to %q: %v", pubFile, err)
return nil
}
}
return br
}
func (c *Client) GetBlobFetcher() blobref.SeekFetcher {
// Use blobref.NewSeriesFetcher(...all configured fetch paths...)
return blobref.NewConfigDirFetcher()
}
// config[trustedCerts] is the list of trusted certificates fingerprints.
// Case insensitive.
// See Client.trustedCerts in client.go
const trustedCerts = "trustedCerts"
var initTrustedCertsOnce sync.Once
func (c *Client) initTrustedCerts() {
if e := os.Getenv("CAMLI_TRUSTED_CERT"); e != "" {
c.trustedCerts = []string{e}
return
}
c.trustedCerts = []string{}
configOnce.Do(parseConfig)
val, ok := config[trustedCerts].([]interface{})
if !ok {
return
}
for _, v := range val {
trustedCert, ok := v.(string)
if !ok {
log.Printf("trustedCert: was expecting a string, got %T", v)
return
}
c.trustedCerts = append(c.trustedCerts, strings.ToLower(trustedCert))
}
}
func (c *Client) GetTrustedCerts() []string {
initTrustedCertsOnce.Do(func() { c.initTrustedCerts() })
return c.trustedCerts
}