From d86c093480d30852569a315139be07b10b0b0718 Mon Sep 17 00:00:00 2001 From: Fabian Wickborn Date: Sun, 21 Feb 2016 19:20:12 +0100 Subject: [PATCH 1/6] Merged the restic-server by @bchapuis Commit ID in fd0/restic-server at time of merge is 07fae00e7ddd8751b150e2ebf0bff8b2871c77ce --- src/restic/cmd/restic-server/.gitignore | 24 +++ src/restic/cmd/restic-server/LICENSE | 24 +++ src/restic/cmd/restic-server/README.md | 29 ++++ src/restic/cmd/restic-server/handlers.go | 157 ++++++++++++++++++++ src/restic/cmd/restic-server/htpasswd.go | 84 +++++++++++ src/restic/cmd/restic-server/router.go | 115 ++++++++++++++ src/restic/cmd/restic-server/router_test.go | 58 ++++++++ src/restic/cmd/restic-server/server.go | 70 +++++++++ 8 files changed, 561 insertions(+) create mode 100644 src/restic/cmd/restic-server/.gitignore create mode 100644 src/restic/cmd/restic-server/LICENSE create mode 100644 src/restic/cmd/restic-server/README.md create mode 100644 src/restic/cmd/restic-server/handlers.go create mode 100644 src/restic/cmd/restic-server/htpasswd.go create mode 100644 src/restic/cmd/restic-server/router.go create mode 100644 src/restic/cmd/restic-server/router_test.go create mode 100644 src/restic/cmd/restic-server/server.go diff --git a/src/restic/cmd/restic-server/.gitignore b/src/restic/cmd/restic-server/.gitignore new file mode 100644 index 000000000..daf913b1b --- /dev/null +++ b/src/restic/cmd/restic-server/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/src/restic/cmd/restic-server/LICENSE b/src/restic/cmd/restic-server/LICENSE new file mode 100644 index 000000000..c50bca0b1 --- /dev/null +++ b/src/restic/cmd/restic-server/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2015, Bertil Chapuis +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/src/restic/cmd/restic-server/README.md b/src/restic/cmd/restic-server/README.md new file mode 100644 index 000000000..aa5d33e0e --- /dev/null +++ b/src/restic/cmd/restic-server/README.md @@ -0,0 +1,29 @@ +# Restic Server + +Restic Server is a sample server that implement restic's rest backend api. +It has been developed for demonstration purpose and is not intented to be used in production. + +## Getting started + +By default the server persists backup data in `/tmp/restic`. +Build and start the server with a custom persistence directory: + +``` +go build +./restic-server -path /user/home/backup +``` + +The server use an `.htpasswd` file to specify users. You can create such a file at the root of the persistence directory by executing the following command. In order to append new user to the file, just omit the `-c` argument. + +``` +htpasswd -s -c .htpasswd username +``` + +By default the server uses http. This is not very secure since with Basic Authentication, username and passwords will be present in every request. In order to enable TLS support just add the `-tls` argument and add a private and public key at the root of your persistence directory. + +Signed certificate are required by the restic backend but if you just want to test the feature you can generate unsigned keys with the following commands: + +``` +openssl genrsa -out private_key 2048 +openssl req -new -x509 -key private_key -out public_key -days 365 +``` diff --git a/src/restic/cmd/restic-server/handlers.go b/src/restic/cmd/restic-server/handlers.go new file mode 100644 index 000000000..8294d454f --- /dev/null +++ b/src/restic/cmd/restic-server/handlers.go @@ -0,0 +1,157 @@ +package main + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +type Context struct { + path string +} + +func AuthHandler(f *HtpasswdFile, h http.Handler) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + username, password, ok := r.BasicAuth() + if !ok { + http.Error(w, "401 unauthorized", 401) + return + } + if !f.Validate(username, password) { + http.Error(w, "401 unauthorized", 401) + return + } + h.ServeHTTP(w, r) + } +} + +func CheckConfig(c *Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + config := filepath.Join(c.path, "config") + if _, err := os.Stat(config); err != nil { + http.Error(w, "404 not found", 404) + return + } + } +} + +func GetConfig(c *Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + config := filepath.Join(c.path, "config") + bytes, err := ioutil.ReadFile(config) + if err != nil { + http.Error(w, "404 not found", 404) + return + } + w.Write(bytes) + } +} + +func SaveConfig(c *Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + config := filepath.Join(c.path, "config") + bytes, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "400 bad request", 400) + return + } + errw := ioutil.WriteFile(config, bytes, 0600) + if errw != nil { + http.Error(w, "500 internal server error", 500) + return + } + w.Write([]byte("200 ok")) + } +} + +func ListBlobs(c *Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := strings.Split(r.RequestURI, "/") + dir := vars[1] + path := filepath.Join(c.path, dir) + files, err := ioutil.ReadDir(path) + if err != nil { + http.Error(w, "404 not found", 404) + return + } + names := make([]string, len(files)) + for i, f := range files { + names[i] = f.Name() + } + data, err := json.Marshal(names) + if err != nil { + http.Error(w, "500 internal server error", 500) + return + } + w.Write(data) + } +} + +func CheckBlob(c *Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := strings.Split(r.RequestURI, "/") + dir := vars[1] + name := vars[2] + path := filepath.Join(c.path, dir, name) + _, err := os.Stat(path) + if err != nil { + http.Error(w, "404 not found", 404) + return + } + } +} + +func GetBlob(c *Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := strings.Split(r.RequestURI, "/") + dir := vars[1] + name := vars[2] + path := filepath.Join(c.path, dir, name) + file, err := os.Open(path) + if err != nil { + http.Error(w, "404 not found", 404) + return + } + defer file.Close() + http.ServeContent(w, r, "", time.Unix(0, 0), file) + } +} + +func SaveBlob(c *Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := strings.Split(r.RequestURI, "/") + dir := vars[1] + name := vars[2] + path := filepath.Join(c.path, dir, name) + bytes, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "400 bad request", 400) + return + } + errw := ioutil.WriteFile(path, bytes, 0600) + if errw != nil { + http.Error(w, "500 internal server error", 500) + return + } + w.Write([]byte("200 ok")) + } +} + +func DeleteBlob(c *Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := strings.Split(r.RequestURI, "/") + dir := vars[1] + name := vars[2] + path := filepath.Join(c.path, dir, name) + err := os.Remove(path) + if err != nil { + http.Error(w, "500 internal server error", 500) + return + } + w.Write([]byte("200 ok")) + } +} diff --git a/src/restic/cmd/restic-server/htpasswd.go b/src/restic/cmd/restic-server/htpasswd.go new file mode 100644 index 000000000..d72a83c9a --- /dev/null +++ b/src/restic/cmd/restic-server/htpasswd.go @@ -0,0 +1,84 @@ +package main + +/* +Copied from: github.com/bitly/oauth2_proxy + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +import ( + "crypto/sha1" + "encoding/base64" + "encoding/csv" + "io" + "log" + "os" +) + +// lookup passwords in a htpasswd file +// The entries must have been created with -s for SHA encryption + +type HtpasswdFile struct { + Users map[string]string +} + +func NewHtpasswdFromFile(path string) (*HtpasswdFile, error) { + r, err := os.Open(path) + if err != nil { + return nil, err + } + defer r.Close() + return NewHtpasswd(r) +} + +func NewHtpasswd(file io.Reader) (*HtpasswdFile, error) { + csv_reader := csv.NewReader(file) + csv_reader.Comma = ':' + csv_reader.Comment = '#' + csv_reader.TrimLeadingSpace = true + + records, err := csv_reader.ReadAll() + if err != nil { + return nil, err + } + h := &HtpasswdFile{Users: make(map[string]string)} + for _, record := range records { + h.Users[record[0]] = record[1] + } + return h, nil +} + +func (h *HtpasswdFile) Validate(user string, password string) bool { + realPassword, exists := h.Users[user] + if !exists { + return false + } + if realPassword[:5] == "{SHA}" { + d := sha1.New() + d.Write([]byte(password)) + if realPassword[5:] == base64.StdEncoding.EncodeToString(d.Sum(nil)) { + return true + } + } else { + log.Printf("Invalid htpasswd entry for %s. Must be a SHA entry.", user) + } + return false +} diff --git a/src/restic/cmd/restic-server/router.go b/src/restic/cmd/restic-server/router.go new file mode 100644 index 000000000..c0a302832 --- /dev/null +++ b/src/restic/cmd/restic-server/router.go @@ -0,0 +1,115 @@ +package main + +import ( + "log" + "net/http" + "strings" +) + +type Route struct { + path []string + handler http.Handler +} + +type Router struct { + routes map[string][]Route +} + +func NewRouter() *Router { + return &Router{make(map[string][]Route)} +} + +func (router *Router) Options(path string, handler http.Handler) { + router.Handle("OPTIONS", path, handler) +} + +func (router *Router) OptionsFunc(path string, handler http.HandlerFunc) { + router.Handle("OPTIONS", path, handler) +} + +func (router *Router) Get(path string, handler http.Handler) { + router.Handle("GET", path, handler) +} + +func (router *Router) GetFunc(path string, handler http.HandlerFunc) { + router.Handle("GET", path, handler) +} + +func (router *Router) Head(path string, handler http.Handler) { + router.Handle("HEAD", path, handler) +} + +func (router *Router) HeadFunc(path string, handler http.HandlerFunc) { + router.Handle("HEAD", path, handler) +} + +func (router *Router) Post(path string, handler http.Handler) { + router.Handle("POST", path, handler) +} + +func (router *Router) PostFunc(path string, handler http.HandlerFunc) { + router.Handle("POST", path, handler) +} + +func (router *Router) Put(path string, handler http.Handler) { + router.Handle("PUT", path, handler) +} + +func (router *Router) PutFunc(path string, handler http.HandlerFunc) { + router.Handle("PUT", path, handler) +} + +func (router *Router) Delete(path string, handler http.Handler) { + router.Handle("DELETE", path, handler) +} + +func (router *Router) DeleteFunc(path string, handler http.HandlerFunc) { + router.Handle("DELETE", path, handler) +} + +func (router *Router) Trace(path string, handler http.Handler) { + router.Handle("TRACE", path, handler) +} + +func (router *Router) TraceFunc(path string, handler http.HandlerFunc) { + router.Handle("TRACE", path, handler) +} + +func (router *Router) Connect(path string, handler http.Handler) { + router.Handle("Connect", path, handler) +} + +func (router *Router) ConnectFunc(path string, handler http.HandlerFunc) { + router.Handle("Connect", path, handler) +} + +func (router *Router) Handle(method string, uri string, handler http.Handler) { + routes := router.routes[method] + path := strings.Split(uri, "/") + routes = append(routes, Route{path, handler}) + router.routes[method] = routes +} + +func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { + method := r.Method + uri := r.RequestURI + path := strings.Split(uri, "/") + + log.Printf("%s %s", method, uri) + +ROUTE: + for _, route := range router.routes[method] { + if len(route.path) != len(path) { + continue + } + for i := 0; i < len(route.path); i++ { + if !strings.HasPrefix(route.path[i], ":") && route.path[i] != path[i] { + continue ROUTE + } + } + route.handler.ServeHTTP(w, r) + return + } + + http.Error(w, "404 not found", 404) +} diff --git a/src/restic/cmd/restic-server/router_test.go b/src/restic/cmd/restic-server/router_test.go new file mode 100644 index 000000000..f7b1f4304 --- /dev/null +++ b/src/restic/cmd/restic-server/router_test.go @@ -0,0 +1,58 @@ +package main + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRouter(t *testing.T) { + router := NewRouter() + + getConfig := []byte("GET /config") + router.GetFunc("/config", func(w http.ResponseWriter, r *http.Request) { + w.Write(getConfig) + }) + + postConfig := []byte("POST /config") + router.PostFunc("/config", func(w http.ResponseWriter, r *http.Request) { + w.Write(postConfig) + }) + + getBlobs := []byte("GET /blobs/") + router.GetFunc("/blobs/", func(w http.ResponseWriter, r *http.Request) { + w.Write(getBlobs) + }) + + getBlob := []byte("GET /blobs/:sha") + router.GetFunc("/blobs/:sha", func(w http.ResponseWriter, r *http.Request) { + w.Write(getBlob) + }) + + server := httptest.NewServer(router) + defer server.Close() + + getConfigResp, _ := http.Get(server.URL + "/config") + getConfigBody, _ := ioutil.ReadAll(getConfigResp.Body) + require.Equal(t, 200, getConfigResp.StatusCode) + require.Equal(t, string(getConfig), string(getConfigBody)) + + postConfigResp, _ := http.Post(server.URL+"/config", "binary/octet-stream", strings.NewReader("post test")) + postConfigBody, _ := ioutil.ReadAll(postConfigResp.Body) + require.Equal(t, 200, postConfigResp.StatusCode) + require.Equal(t, string(postConfig), string(postConfigBody)) + + getBlobsResp, _ := http.Get(server.URL + "/blobs/") + getBlobsBody, _ := ioutil.ReadAll(getBlobsResp.Body) + require.Equal(t, 200, getBlobsResp.StatusCode) + require.Equal(t, string(getBlobs), string(getBlobsBody)) + + getBlobResp, _ := http.Get(server.URL + "/blobs/test") + getBlobBody, _ := ioutil.ReadAll(getBlobResp.Body) + require.Equal(t, 200, getBlobResp.StatusCode) + require.Equal(t, string(getBlob), string(getBlobBody)) +} diff --git a/src/restic/cmd/restic-server/server.go b/src/restic/cmd/restic-server/server.go new file mode 100644 index 000000000..86bcf75c0 --- /dev/null +++ b/src/restic/cmd/restic-server/server.go @@ -0,0 +1,70 @@ +package main + +import ( + "flag" + "log" + "net/http" + "os" + "path/filepath" +) + +const ( + HTTP = ":8000" + HTTPS = ":8443" +) + +func main() { + // Parse command-line args + var path = flag.String("path", "/tmp/restic", "specifies the path of the data directory") + var tls = flag.Bool("tls", false, "turns on tls support") + flag.Parse() + + // Create the missing directories + dirs := []string{ + "data", + "snapshots", + "index", + "locks", + "keys", + } + for _, d := range dirs { + os.MkdirAll(filepath.Join(*path, d), 0600) + } + + // Define the routes + context := &Context{*path} + router := NewRouter() + router.HeadFunc("/config", CheckConfig(context)) + router.GetFunc("/config", GetConfig(context)) + router.PostFunc("/config", SaveConfig(context)) + router.GetFunc("/:dir/", ListBlobs(context)) + router.HeadFunc("/:dir/:name", CheckBlob(context)) + router.GetFunc("/:type/:name", GetBlob(context)) + router.PostFunc("/:type/:name", SaveBlob(context)) + router.DeleteFunc("/:type/:name", DeleteBlob(context)) + + // Check for a password file + var handler http.Handler + htpasswdFile, err := NewHtpasswdFromFile(filepath.Join(*path, ".htpasswd")) + if err != nil { + log.Println("Authentication disabled") + handler = router + } else { + log.Println("Authentication enabled") + handler = AuthHandler(htpasswdFile, router) + } + + // start the server + if !*tls { + log.Printf("start server on port %s\n", HTTP) + http.ListenAndServe(HTTP, handler) + } else { + privateKey := filepath.Join(*path, "private_key") + publicKey := filepath.Join(*path, "public_key") + log.Println("TLS enabled") + log.Printf("private key: %s", privateKey) + log.Printf("public key: %s", publicKey) + log.Printf("start server on port %s\n", HTTPS) + http.ListenAndServeTLS(HTTPS, publicKey, privateKey, handler) + } +} From 51d86370a531fe8002c7e3d528fe1b71f99354d3 Mon Sep 17 00:00:00 2001 From: Fabian Wickborn Date: Sun, 21 Feb 2016 17:33:45 +0100 Subject: [PATCH 2/6] Fixes for the PR - Removed external dependencies for test - Prevent building restic-server w/ Go 1.3 Go versions 1.0, 1.1., and 1.2 are going to fail as well, but they are "excluded" by README.md already. --- src/restic/cmd/restic-server/handlers.go | 21 ++++++++++++ src/restic/cmd/restic-server/htpasswd.go | 22 ++++++++++--- src/restic/cmd/restic-server/router.go | 22 +++++++++++++ src/restic/cmd/restic-server/router_test.go | 36 +++++++++++++++------ src/restic/cmd/restic-server/server.go | 14 ++++---- 5 files changed, 94 insertions(+), 21 deletions(-) diff --git a/src/restic/cmd/restic-server/handlers.go b/src/restic/cmd/restic-server/handlers.go index 8294d454f..cd2fd518b 100644 --- a/src/restic/cmd/restic-server/handlers.go +++ b/src/restic/cmd/restic-server/handlers.go @@ -1,3 +1,5 @@ +// +build go1.4 + package main import ( @@ -10,10 +12,14 @@ import ( "time" ) +// Context contains repository meta-data. type Context struct { path string } +// AuthHandler wraps h with a http.HandlerFunc that performs basic +// authentication against the user/passwords pairs stored in f and returns the +// http.HandlerFunc. func AuthHandler(f *HtpasswdFile, h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { username, password, ok := r.BasicAuth() @@ -29,6 +35,8 @@ func AuthHandler(f *HtpasswdFile, h http.Handler) http.HandlerFunc { } } +// CheckConfig returns a http.HandlerFunc that checks whether +// a configuration exists. func CheckConfig(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { config := filepath.Join(c.path, "config") @@ -39,6 +47,8 @@ func CheckConfig(c *Context) http.HandlerFunc { } } +// GetConfig returns a http.HandlerFunc that allows for a +// config to be retrieved. func GetConfig(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { config := filepath.Join(c.path, "config") @@ -51,6 +61,8 @@ func GetConfig(c *Context) http.HandlerFunc { } } +// SaveConfig returns a http.HandlerFunc that allows for a +// config to be saved. func SaveConfig(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { config := filepath.Join(c.path, "config") @@ -68,6 +80,8 @@ func SaveConfig(c *Context) http.HandlerFunc { } } +// ListBlobs returns a http.HandlerFunc that lists +// all blobs of a given type in an arbitrary order. func ListBlobs(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := strings.Split(r.RequestURI, "/") @@ -91,6 +105,8 @@ func ListBlobs(c *Context) http.HandlerFunc { } } +// CheckBlob reutrns a http.HandlerFunc that tests whether a blob exists +// and returns 200, if it does, or 404 otherwise. func CheckBlob(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := strings.Split(r.RequestURI, "/") @@ -105,6 +121,8 @@ func CheckBlob(c *Context) http.HandlerFunc { } } +// GetBlob returns a http.HandlerFunc that retrieves a blob +// from the repository. func GetBlob(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := strings.Split(r.RequestURI, "/") @@ -121,6 +139,7 @@ func GetBlob(c *Context) http.HandlerFunc { } } +// SaveBlob returns a http.HandlerFunc that saves a blob to the repository. func SaveBlob(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := strings.Split(r.RequestURI, "/") @@ -141,6 +160,8 @@ func SaveBlob(c *Context) http.HandlerFunc { } } +// DeleteBlob returns a http.HandlerFunc that deletes a blob from the +// repository. func DeleteBlob(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := strings.Split(r.RequestURI, "/") diff --git a/src/restic/cmd/restic-server/htpasswd.go b/src/restic/cmd/restic-server/htpasswd.go index d72a83c9a..2b7108f7f 100644 --- a/src/restic/cmd/restic-server/htpasswd.go +++ b/src/restic/cmd/restic-server/htpasswd.go @@ -1,3 +1,5 @@ +// +build go1.4 + package main /* @@ -36,10 +38,14 @@ import ( // lookup passwords in a htpasswd file // The entries must have been created with -s for SHA encryption +// HtpasswdFile is a map for usernames to passwords. type HtpasswdFile struct { Users map[string]string } +// NewHtpasswdFromFile reads the users and passwords from a htpasswd +// file and returns them. If an error is encountered, it is returned, together +// with a nil-Pointer for the HtpasswdFile. func NewHtpasswdFromFile(path string) (*HtpasswdFile, error) { r, err := os.Open(path) if err != nil { @@ -49,13 +55,16 @@ func NewHtpasswdFromFile(path string) (*HtpasswdFile, error) { return NewHtpasswd(r) } +// NewHtpasswd reads the users and passwords from a htpasswd +// datastream in file and returns them. If an error is encountered, +// it is returned, together with a nil-Pointer for the HtpasswdFile. func NewHtpasswd(file io.Reader) (*HtpasswdFile, error) { - csv_reader := csv.NewReader(file) - csv_reader.Comma = ':' - csv_reader.Comment = '#' - csv_reader.TrimLeadingSpace = true + cr := csv.NewReader(file) + cr.Comma = ':' + cr.Comment = '#' + cr.TrimLeadingSpace = true - records, err := csv_reader.ReadAll() + records, err := cr.ReadAll() if err != nil { return nil, err } @@ -66,6 +75,9 @@ func NewHtpasswd(file io.Reader) (*HtpasswdFile, error) { return h, nil } +// Validate returns true if password matches the stored password +// for user. If no password for user is stored, or the password +// is wrong, false is returned. func (h *HtpasswdFile) Validate(user string, password string) bool { realPassword, exists := h.Users[user] if !exists { diff --git a/src/restic/cmd/restic-server/router.go b/src/restic/cmd/restic-server/router.go index c0a302832..c48203955 100644 --- a/src/restic/cmd/restic-server/router.go +++ b/src/restic/cmd/restic-server/router.go @@ -1,3 +1,5 @@ +// +build go1.4 + package main import ( @@ -6,83 +8,103 @@ import ( "strings" ) +// Route is a handler for a path that was already split. type Route struct { path []string handler http.Handler } +// Router maps HTTP methods to a slice of Route handlers. type Router struct { routes map[string][]Route } +// NewRouter creates a new Router and returns a pointer to it. func NewRouter() *Router { return &Router{make(map[string][]Route)} } +// Options registers handler for path with method "OPTIONS". func (router *Router) Options(path string, handler http.Handler) { router.Handle("OPTIONS", path, handler) } +// OptionsFunc registers handler for path with method "OPTIONS". func (router *Router) OptionsFunc(path string, handler http.HandlerFunc) { router.Handle("OPTIONS", path, handler) } +// Get registers handler for path with method "GET". func (router *Router) Get(path string, handler http.Handler) { router.Handle("GET", path, handler) } +// GetFunc registers handler for path with method "GET". func (router *Router) GetFunc(path string, handler http.HandlerFunc) { router.Handle("GET", path, handler) } +// Head registers handler for path with method "HEAD". func (router *Router) Head(path string, handler http.Handler) { router.Handle("HEAD", path, handler) } +// HeadFunc registers handler for path with method "HEAD". func (router *Router) HeadFunc(path string, handler http.HandlerFunc) { router.Handle("HEAD", path, handler) } +// Post registers handler for path with method "POST". func (router *Router) Post(path string, handler http.Handler) { router.Handle("POST", path, handler) } +// PostFunc registers handler for path with method "POST". func (router *Router) PostFunc(path string, handler http.HandlerFunc) { router.Handle("POST", path, handler) } +// Put registers handler for path with method "PUT". func (router *Router) Put(path string, handler http.Handler) { router.Handle("PUT", path, handler) } +// PutFunc registers handler for path with method "PUT". func (router *Router) PutFunc(path string, handler http.HandlerFunc) { router.Handle("PUT", path, handler) } +// Delete registers handler for path with method "DELETE". func (router *Router) Delete(path string, handler http.Handler) { router.Handle("DELETE", path, handler) } +// DeleteFunc registers handler for path with method "DELETE". func (router *Router) DeleteFunc(path string, handler http.HandlerFunc) { router.Handle("DELETE", path, handler) } +// Trace registers handler for path with method "TRACE". func (router *Router) Trace(path string, handler http.Handler) { router.Handle("TRACE", path, handler) } +// TraceFunc registers handler for path with method "TRACE". func (router *Router) TraceFunc(path string, handler http.HandlerFunc) { router.Handle("TRACE", path, handler) } +// Connect registers handler for path with method "Connect". func (router *Router) Connect(path string, handler http.Handler) { router.Handle("Connect", path, handler) } +// ConnectFunc registers handler for path with method "Connect". func (router *Router) ConnectFunc(path string, handler http.HandlerFunc) { router.Handle("Connect", path, handler) } +// Handle registers a http.Handler for method and uri func (router *Router) Handle(method string, uri string, handler http.Handler) { routes := router.routes[method] path := strings.Split(uri, "/") diff --git a/src/restic/cmd/restic-server/router_test.go b/src/restic/cmd/restic-server/router_test.go index f7b1f4304..d4da1843d 100644 --- a/src/restic/cmd/restic-server/router_test.go +++ b/src/restic/cmd/restic-server/router_test.go @@ -1,3 +1,5 @@ +// +build go1.4 + package main import ( @@ -6,8 +8,6 @@ import ( "net/http/httptest" "strings" "testing" - - "github.com/stretchr/testify/require" ) func TestRouter(t *testing.T) { @@ -38,21 +38,37 @@ func TestRouter(t *testing.T) { getConfigResp, _ := http.Get(server.URL + "/config") getConfigBody, _ := ioutil.ReadAll(getConfigResp.Body) - require.Equal(t, 200, getConfigResp.StatusCode) - require.Equal(t, string(getConfig), string(getConfigBody)) + if getConfigResp.StatusCode != 200 { + t.Fatalf("Wanted HTTP Status 200, got %d", getConfigResp.StatusCode) + } + if string(getConfig) != string(getConfigBody) { + t.Fatalf("Config wrong:\nWanted '%s'\nGot: '%s'", string(getConfig), string(getConfigBody)) + } postConfigResp, _ := http.Post(server.URL+"/config", "binary/octet-stream", strings.NewReader("post test")) postConfigBody, _ := ioutil.ReadAll(postConfigResp.Body) - require.Equal(t, 200, postConfigResp.StatusCode) - require.Equal(t, string(postConfig), string(postConfigBody)) + if postConfigResp.StatusCode != 200 { + t.Fatalf("Wanted HTTP Status 200, got %d", postConfigResp.StatusCode) + } + if string(postConfig) != string(postConfigBody) { + t.Fatalf("Config wrong:\nWanted '%s'\nGot: '%s'", string(postConfig), string(postConfigBody)) + } getBlobsResp, _ := http.Get(server.URL + "/blobs/") getBlobsBody, _ := ioutil.ReadAll(getBlobsResp.Body) - require.Equal(t, 200, getBlobsResp.StatusCode) - require.Equal(t, string(getBlobs), string(getBlobsBody)) + if getBlobsResp.StatusCode != 200 { + t.Fatalf("Wanted HTTP Status 200, got %d", getBlobsResp.StatusCode) + } + if string(getBlobs) != string(getBlobsBody) { + t.Fatalf("Config wrong:\nWanted '%s'\nGot: '%s'", string(getBlobs), string(getBlobsBody)) + } getBlobResp, _ := http.Get(server.URL + "/blobs/test") getBlobBody, _ := ioutil.ReadAll(getBlobResp.Body) - require.Equal(t, 200, getBlobResp.StatusCode) - require.Equal(t, string(getBlob), string(getBlobBody)) + if getBlobResp.StatusCode != 200 { + t.Fatalf("Wanted HTTP Status 200, got %d", getBlobResp.StatusCode) + } + if string(getBlob) != string(getBlobBody) { + t.Fatalf("Config wrong:\nWanted '%s'\nGot: '%s'", string(getBlob), string(getBlobBody)) + } } diff --git a/src/restic/cmd/restic-server/server.go b/src/restic/cmd/restic-server/server.go index 86bcf75c0..bdad003f4 100644 --- a/src/restic/cmd/restic-server/server.go +++ b/src/restic/cmd/restic-server/server.go @@ -1,3 +1,5 @@ +// +build go1.4 + package main import ( @@ -9,8 +11,8 @@ import ( ) const ( - HTTP = ":8000" - HTTPS = ":8443" + defaultHTTPPort = ":8000" + defaultHTTPSPort = ":8443" ) func main() { @@ -56,15 +58,15 @@ func main() { // start the server if !*tls { - log.Printf("start server on port %s\n", HTTP) - http.ListenAndServe(HTTP, handler) + log.Printf("start server on port %s\n", defaultHTTPPort) + http.ListenAndServe(defaultHTTPPort, handler) } else { privateKey := filepath.Join(*path, "private_key") publicKey := filepath.Join(*path, "public_key") log.Println("TLS enabled") log.Printf("private key: %s", privateKey) log.Printf("public key: %s", publicKey) - log.Printf("start server on port %s\n", HTTPS) - http.ListenAndServeTLS(HTTPS, publicKey, privateKey, handler) + log.Printf("start server on port %s\n", defaultHTTPSPort) + http.ListenAndServeTLS(defaultHTTPSPort, publicKey, privateKey, handler) } } From 4749e610af7b5c8c9b0dfc8803579a8ee46d273c Mon Sep 17 00:00:00 2001 From: Fabian Wickborn Date: Sun, 21 Feb 2016 21:40:06 +0100 Subject: [PATCH 3/6] restic-server: Fix content length for HEAD requests --- src/restic/cmd/restic-server/handlers.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/restic/cmd/restic-server/handlers.go b/src/restic/cmd/restic-server/handlers.go index cd2fd518b..6c87ef121 100644 --- a/src/restic/cmd/restic-server/handlers.go +++ b/src/restic/cmd/restic-server/handlers.go @@ -4,6 +4,7 @@ package main import ( "encoding/json" + "fmt" "io/ioutil" "net/http" "os" @@ -40,10 +41,12 @@ func AuthHandler(f *HtpasswdFile, h http.Handler) http.HandlerFunc { func CheckConfig(c *Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { config := filepath.Join(c.path, "config") - if _, err := os.Stat(config); err != nil { + st, err := os.Stat(config) + if err != nil { http.Error(w, "404 not found", 404) return } + w.Header().Add("Content-Length", fmt.Sprint(st.Size())) } } @@ -113,11 +116,12 @@ func CheckBlob(c *Context) http.HandlerFunc { dir := vars[1] name := vars[2] path := filepath.Join(c.path, dir, name) - _, err := os.Stat(path) + st, err := os.Stat(path) if err != nil { http.Error(w, "404 not found", 404) return } + w.Header().Add("Content-Length", fmt.Sprint(st.Size())) } } From e4168fdde5962f2097d106360cb2f2c52078e9cd Mon Sep 17 00:00:00 2001 From: Fabian Wickborn Date: Mon, 22 Feb 2016 11:50:32 +0100 Subject: [PATCH 4/6] restic-server: Reduce memory footprint for saving blobs Before, the restic-server read the whole blob (up to 8MB) into memory prior to writing it to disk. Concurrent writes consumed a lot of memory. This change writes the blob to a tmp file directly and renames it afterwards in case there where no errors. --- src/restic/cmd/restic-server/handlers.go | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/restic/cmd/restic-server/handlers.go b/src/restic/cmd/restic-server/handlers.go index 6c87ef121..f7c4d8c5d 100644 --- a/src/restic/cmd/restic-server/handlers.go +++ b/src/restic/cmd/restic-server/handlers.go @@ -5,6 +5,7 @@ package main import ( "encoding/json" "fmt" + "io" "io/ioutil" "net/http" "os" @@ -150,13 +151,22 @@ func SaveBlob(c *Context) http.HandlerFunc { dir := vars[1] name := vars[2] path := filepath.Join(c.path, dir, name) - bytes, err := ioutil.ReadAll(r.Body) + tmp := path + "_tmp" + tf, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { - http.Error(w, "400 bad request", 400) + http.Error(w, "500 internal server error", 500) return } - errw := ioutil.WriteFile(path, bytes, 0600) - if errw != nil { + if _, err := io.Copy(tf, r.Body); err != nil { + http.Error(w, "400 bad request", 400) + tf.Close() + os.Remove(tmp) + return + } + if err := tf.Close(); err != nil { + http.Error(w, "500 internal server error", 500) + } + if err := os.Rename(tmp, path); err != nil { http.Error(w, "500 internal server error", 500) return } From 1cdbc8e1aa91a6789ba4c9b5ee49432fcec448ef Mon Sep 17 00:00:00 2001 From: Fabian Wickborn Date: Mon, 22 Feb 2016 17:30:49 +0100 Subject: [PATCH 5/6] restic-server: Fix folder permissions --- src/restic/cmd/restic-server/server.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/restic/cmd/restic-server/server.go b/src/restic/cmd/restic-server/server.go index bdad003f4..51ce0698d 100644 --- a/src/restic/cmd/restic-server/server.go +++ b/src/restic/cmd/restic-server/server.go @@ -30,7 +30,7 @@ func main() { "keys", } for _, d := range dirs { - os.MkdirAll(filepath.Join(*path, d), 0600) + os.MkdirAll(filepath.Join(*path, d), 0700) } // Define the routes From dd5680dab646bc166cec7c513c93d044e2abcd8e Mon Sep 17 00:00:00 2001 From: Fabian Wickborn Date: Mon, 22 Feb 2016 17:31:09 +0100 Subject: [PATCH 6/6] restic-server: Create tmp folder --- src/restic/cmd/restic-server/server.go | 1 + 1 file changed, 1 insertion(+) diff --git a/src/restic/cmd/restic-server/server.go b/src/restic/cmd/restic-server/server.go index 51ce0698d..bce991462 100644 --- a/src/restic/cmd/restic-server/server.go +++ b/src/restic/cmd/restic-server/server.go @@ -28,6 +28,7 @@ func main() { "index", "locks", "keys", + "tmp", } for _, d := range dirs { os.MkdirAll(filepath.Join(*path, d), 0700)