-
Notifications
You must be signed in to change notification settings - Fork 42
/
serve.go
291 lines (259 loc) · 7.32 KB
/
serve.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package serve
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"sync"
"github.com/flimzy/kivik"
"github.com/flimzy/kivik/auth"
"github.com/flimzy/kivik/authdb"
"github.com/flimzy/kivik/errors"
"github.com/flimzy/kivik/serve/conf"
)
// Version is the version of this library.
const Version = "0.0.1"
// Vendor is the identifying vendor string for this library.
const Vendor = "Kivik"
// CompatVersion is the default compatibility version reported to clients.
const CompatVersion = "1.6.1"
// Service defines a CouchDB-like service to serve. You will define one of these
// per server endpoint.
type Service struct {
// Client is an instance of a driver.Client, which will be served.
Client *kivik.Client
// UserStore provides access to the user database. This is passed to auth
// handlers, and is used to authenticate sessions. If unset, a nil UserStore
// will be used which authenticates all uses. PERPETUAL ADMIN PARTY!
UserStore authdb.UserStore
// AuthHandler is a slice of authentication handlers. If no auth
// handlers are configured, the server will operate as a PERPETUAL
// ADMIN PARTY!
AuthHandlers []auth.Handler
// CompatVersion is the compatibility version to report to clients. Defaults
// to 1.6.1.
CompatVersion string
// VendorVersion is the vendor version string to report to clients. Defaults to the library
// version.
VendorVersion string
// VendorName is the vendor name string to report to clients. Defaults to the library
// vendor string.
VendorName string
// Favicon is the path to a file to serve as favicon.ico. If unset, a default
// image is used.
Favicon string
// ConfigFile is the path to a config file to read during startup.
ConfigFile string
// Config is a complete config object. If this is set, config loading is
// bypassed.
Config *conf.Conf
conf *conf.Conf
confMU sync.RWMutex
// authHandlers is a map version of AuthHandlers for easier internal
// use.
authHandlers map[string]auth.Handler
authHandlerNames []string
}
// Init initializes a configured server. This is automatically called when
// Start() is called, so this is meant to be used if you want to bind the server
// yourself.
func (s *Service) Init() (http.Handler, error) {
s.authHandlersSetup()
if err := s.loadConf(); err != nil {
return nil, err
}
if !s.Conf().IsSet("couch_httpd_auth.secret") {
fmt.Fprintf(os.Stderr, "couch_httpd_auth.secret is not set. This is insecure!\n")
}
return s.setupRoutes()
}
func (s *Service) loadConf() error {
s.confMU.Lock()
defer s.confMU.Unlock()
if s.Config != nil {
s.conf = s.Config
return nil
}
c, err := conf.Load(s.ConfigFile)
if err != nil {
return err
}
s.conf = c
return nil
}
// Conf returns the initialized server configuration.
func (s *Service) Conf() *conf.Conf {
s.confMU.RLock()
defer s.confMU.RUnlock()
if s.Config != nil {
s.confMU.RUnlock()
if err := s.loadConf(); err != nil {
panic(err)
}
s.confMU.RLock()
}
return s.conf
}
// Start begins serving connections.
func (s *Service) Start() error {
server, err := s.Init()
if err != nil {
return err
}
addr := fmt.Sprintf("%s:%d",
s.Conf().GetString("httpd.bind_address"),
s.Conf().GetInt("httpd.port"),
)
fmt.Fprintf(os.Stderr, "Listening on %s\n", addr)
return http.ListenAndServe(addr, server)
}
func (s *Service) authHandlersSetup() {
if s.AuthHandlers == nil || len(s.AuthHandlers) == 0 {
fmt.Fprintf(os.Stderr, "No AuthHandler specified! Welcome to the PERPETUAL ADMIN PARTY!\n")
}
s.authHandlers = make(map[string]auth.Handler)
s.authHandlerNames = make([]string, 0, len(s.AuthHandlers))
for _, handler := range s.AuthHandlers {
name := handler.MethodName()
if _, ok := s.authHandlers[name]; ok {
panic(fmt.Sprintf("Multiple auth handlers for for `%s` registered", name))
}
s.authHandlers[name] = handler
s.authHandlerNames = append(s.authHandlerNames, name)
}
if s.UserStore == nil {
s.UserStore = &perpetualAdminParty{}
}
}
type perpetualAdminParty struct{}
var _ authdb.UserStore = &perpetualAdminParty{}
func (p *perpetualAdminParty) Validate(ctx context.Context, username, _ string) (*authdb.UserContext, error) {
return p.UserCtx(ctx, username)
}
func (p *perpetualAdminParty) UserCtx(_ context.Context, username string) (*authdb.UserContext, error) {
return &authdb.UserContext{
Name: username,
Roles: []string{"_admin"},
}, nil
}
// Bind sets the HTTP daemon bind address and port.
func (s *Service) Bind(addr string) error {
port := addr[strings.LastIndex(addr, ":")+1:]
if _, err := strconv.Atoi(port); err != nil {
return errors.Wrapf(err, "invalid port '%s'", port)
}
host := strings.TrimSuffix(addr, ":"+port)
s.Conf().Set("httpd.bind_address", host)
s.Conf().Set("httpd.port", port)
return nil
}
const (
mGET = http.MethodGet
mPUT = http.MethodPut
mHEAD = http.MethodHead
mPOST = http.MethodPost
mDELETE = http.MethodDelete
mCOPY = "COPY"
)
type vendorInfo struct {
Name string `json:"name"`
Version string `json:"version"`
}
type serverInfo struct {
CouchDB string `json:"couchdb"`
Version string `json:"version"`
Vendor vendorInfo `json:"vendor"`
}
const (
typeJSON = "application/json"
typeText = "text/plain"
typeForm = "application/x-www-form-urlencoded"
typeMForm = "multipart/form-data"
)
type handler func(w http.ResponseWriter, r *http.Request) error
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h(w, r); err != nil {
reportError(w, err)
}
}
func reportError(w http.ResponseWriter, err error) {
w.Header().Add("Content-Type", typeJSON)
status := errors.StatusCode(err)
if status == 0 {
status = 500
}
w.WriteHeader(status)
short := err.Error()
reason := errors.Reason(err)
if reason == "" {
reason = short
} else {
short = strings.ToLower(http.StatusText(status))
}
json.NewEncoder(w).Encode(map[string]interface{}{
"error": short,
"reason": reason,
})
}
func root(w http.ResponseWriter, r *http.Request) error {
w.Header().Set("Content-Type", typeJSON)
svc := GetService(r)
vendVers := svc.VendorVersion
if vendVers == "" {
vendVers = Version
}
vendName := svc.VendorName
if vendName == "" {
vendName = Vendor
}
return json.NewEncoder(w).Encode(serverInfo{
CouchDB: "Välkommen",
Version: CompatVersion,
Vendor: vendorInfo{
Name: vendName,
Version: vendVers,
},
})
}
func allDBs(w http.ResponseWriter, r *http.Request) error {
w.Header().Set("Content-Type", typeJSON)
client := getClient(r)
dbs, err := client.AllDBs(r.Context())
if err != nil {
return err
}
return json.NewEncoder(w).Encode(dbs)
}
func createDB(w http.ResponseWriter, r *http.Request) error {
w.Header().Set("Content-Type", typeJSON)
params := getParams(r)
client := getClient(r)
if err := client.CreateDB(r.Context(), params["db"]); err != nil {
return err
}
return json.NewEncoder(w).Encode(map[string]interface{}{
"ok": true,
})
}
func dbExists(w http.ResponseWriter, r *http.Request) error {
params := getParams(r)
client := getClient(r)
exists, err := client.DBExists(r.Context(), params["db"])
if err != nil {
return err
}
if exists {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusNotFound)
}
return nil
}
// serveJSON serves i as JSON to w.
func serveJSON(w http.ResponseWriter, i interface{}) error {
w.Header().Set("Content-Type", typeJSON)
return json.NewEncoder(w).Encode(i)
}