http

package
v1.61.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2022 License: MIT Imports: 22 Imported by: 9

Documentation

Overview

Package http provides a registration interface for http services

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidMinTLSVersion - hard coded errors, allowing for easier testing
	ErrInvalidMinTLSVersion = errors.New("invalid value for --min-tls-version")
	// ErrTLSBodyMismatch - hard coded errors, allowing for easier testing
	ErrTLSBodyMismatch = errors.New("need both TLSCertBody and TLSKeyBody to use TLS")
	// ErrTLSFileMismatch - hard coded errors, allowing for easier testing
	ErrTLSFileMismatch = errors.New("need both --cert and --key to use TLS")
	// ErrTLSParseCA - hard coded errors, allowing for easier testing
	ErrTLSParseCA = errors.New("unable to parse client certificate authority")
)
View Source
var Assets embed.FS

Assets holds the embedded filesystem for the default template

View Source
var AuthHelp = `
#### Authentication

By default this will serve files without needing a login.

You can either use an htpasswd file which can take lots of users, or
set a single username and password with the ` + "`--user` and `--pass`" + ` flags.

Use ` + "`--htpasswd /path/to/htpasswd`" + ` to provide an htpasswd file.  This is
in standard apache format and supports MD5, SHA1 and BCrypt for basic
authentication.  Bcrypt is recommended.

To create an htpasswd file:

    touch htpasswd
    htpasswd -B htpasswd user
    htpasswd -B htpasswd anotherUser

The password file can be updated while rclone is running.

Use ` + "`--realm`" + ` to set the authentication realm.

Use ` + "`--salt`" + ` to change the password hashing salt from the default.
`

AuthHelp contains text describing the http authentication to add to the command help.

View Source
var Help = `
### Server options

Use ` + "`--addr`" + ` to specify which IP address and port the server should
listen on, eg ` + "`--addr 1.2.3.4:8000` or `--addr :8080`" + ` to listen to all
IPs.  By default it only listens on localhost.  You can use port
:0 to let the OS choose an available port.

If you set ` + "`--addr`" + ` to listen on a public or LAN accessible IP address
then using Authentication is advised - see the next section for info.

You can use a unix socket by setting the url to ` + "`unix:///path/to/socket`" + `
or just by using an absolute path name. Note that unix sockets bypass the
authentication - this is expected to be done with file system permissions.

` + "`--addr`" + ` may be repeated to listen on multiple IPs/ports/sockets.

` + "`--server-read-timeout` and `--server-write-timeout`" + ` can be used to
control the timeouts on the server.  Note that this is the total time
for a transfer.

` + "`--max-header-bytes`" + ` controls the maximum number of bytes the server will
accept in the HTTP header.

` + "`--baseurl`" + ` controls the URL prefix that rclone serves from.  By default
rclone will serve from the root.  If you used ` + "`--baseurl \"/rclone\"`" + ` then
rclone would serve from a URL starting with "/rclone/".  This is
useful if you wish to proxy rclone serve.  Rclone automatically
inserts leading and trailing "/" on ` + "`--baseurl`" + `, so ` + "`--baseurl \"rclone\"`" + `,
` + "`--baseurl \"/rclone\"` and `--baseurl \"/rclone/\"`" + ` are all treated
identically.

#### TLS (SSL)

By default this will serve over http.  If you want you can serve over
https.  You will need to supply the ` + "`--cert` and `--key`" + ` flags.
If you wish to do client side certificate validation then you will need to
supply ` + "`--client-ca`" + ` also.

` + "`--cert`" + ` should be a either a PEM encoded certificate or a concatenation
of that with the CA certificate.  ` + "`--key`" + ` should be the PEM encoded
private key and ` + "`--client-ca`" + ` should be the PEM encoded client
certificate authority certificate.

--min-tls-version is minimum TLS version that is acceptable. Valid
  values are "tls1.0", "tls1.1", "tls1.2" and "tls1.3" (default
  "tls1.0").
`

Help contains text describing the http server to add to the command help.

View Source
var TemplateHelp = `
#### Template

` + "`--template`" + ` allows a user to specify a custom markup template for HTTP
and WebDAV serve functions.  The server exports the following markup
to be used within the template to server pages:

| Parameter   | Description |
| :---------- | :---------- |
| .Name       | The full path of a file/directory. |
| .Title      | Directory listing of .Name |
| .Sort       | The current sort used.  This is changeable via ?sort= parameter |
|             | Sort Options: namedirfirst,name,size,time (default namedirfirst) |
| .Order      | The current ordering used.  This is changeable via ?order= parameter |
|             | Order Options: asc,desc (default asc) |
| .Query      | Currently unused. |
| .Breadcrumb | Allows for creating a relative navigation |
|-- .Link     | The relative to the root link of the Text. |
|-- .Text     | The Name of the directory. |
| .Entries    | Information about a specific file/directory. |
|-- .URL      | The 'url' of an entry.  |
|-- .Leaf     | Currently same as 'URL' but intended to be 'just' the name. |
|-- .IsDir    | Boolean for if an entry is a directory or not. |
|-- .Size     | Size in Bytes of the entry. |
|-- .ModTime  | The UTC timestamp of an entry. |
`

TemplateHelp describes how to use a custom template

Functions

func AddAuthFlagsPrefix added in v1.61.0

func AddAuthFlagsPrefix(flagSet *pflag.FlagSet, prefix string, cfg *AuthConfig)

AddAuthFlagsPrefix adds flags to the flag set for AuthConfig

func AddHTTPFlagsPrefix added in v1.61.0

func AddHTTPFlagsPrefix(flagSet *pflag.FlagSet, prefix string, cfg *Config)

AddHTTPFlagsPrefix adds flags for the httplib

func AddTemplateFlagsPrefix added in v1.61.0

func AddTemplateFlagsPrefix(flagSet *pflag.FlagSet, prefix string, cfg *TemplateConfig)

AddTemplateFlagsPrefix for the templating functionality

func AfterEpoch added in v1.61.0

func AfterEpoch(t time.Time) bool

AfterEpoch returns the time since the epoch for the given time

func CtxGetAuth added in v1.61.0

func CtxGetAuth(ctx context.Context) interface{}

CtxGetAuth is a wrapper over the private Auth context key

func CtxGetUser added in v1.61.0

func CtxGetUser(ctx context.Context) (string, bool)

CtxGetUser is a wrapper over the private User context key

func CtxSetUser added in v1.61.0

func CtxSetUser(ctx context.Context, value string) context.Context

CtxSetUser is a test helper that injects a User value into context

func GetTemplate added in v1.61.0

func GetTemplate(tmpl string) (*template.Template, error)

GetTemplate returns the HTML template for serving directories via HTTP/WebDAV

func IsAuthenticated added in v1.61.0

func IsAuthenticated(r *http.Request) bool

IsAuthenticated checks if this request was authenticated via a middleware

func IsUnixSocket added in v1.61.0

func IsUnixSocket(r *http.Request) bool

IsUnixSocket checks if the request was received on a unix socket, used to skip auth & CORS

func NewBaseContext added in v1.61.0

func NewBaseContext(ctx context.Context, url string) func(l net.Listener) context.Context

NewBaseContext initializes the context for all requests, adding info for use in middleware and handlers

func PublicURL added in v1.61.0

func PublicURL(r *http.Request) string

PublicURL returns the URL defined in NewBaseContext, used for logging & CORS

Types

type AuthConfig added in v1.61.0

type AuthConfig struct {
	HtPasswd     string       // htpasswd file - if not provided no authentication is done
	Realm        string       // realm for authentication
	BasicUser    string       // single username for basic auth if not using Htpasswd
	BasicPass    string       // password for BasicUser
	Salt         string       // password hashing salt
	CustomAuthFn CustomAuthFn `json:"-"` // custom Auth (not set by command line flags)
}

AuthConfig contains options for the http authentication

func DefaultAuthCfg added in v1.61.0

func DefaultAuthCfg() AuthConfig

DefaultAuthCfg returns a new config which can be customized by command line flags

func (*AuthConfig) AddFlagsPrefix added in v1.61.0

func (cfg *AuthConfig) AddFlagsPrefix(flagSet *pflag.FlagSet, prefix string)

AddFlagsPrefix adds flags to the flag set for AuthConfig

type Config added in v1.61.0

type Config struct {
	ListenAddr         []string      // Port to listen on
	BaseURL            string        // prefix to strip from URLs
	ServerReadTimeout  time.Duration // Timeout for server reading data
	ServerWriteTimeout time.Duration // Timeout for server writing data
	MaxHeaderBytes     int           // Maximum size of request header
	TLSCert            string        // Path to TLS PEM key (concatenation of certificate and CA certificate)
	TLSKey             string        // Path to TLS PEM Private key
	TLSCertBody        []byte        // TLS PEM key (concatenation of certificate and CA certificate) body, ignores TLSCert
	TLSKeyBody         []byte        // TLS PEM Private key body, ignores TLSKey
	ClientCA           string        // Client certificate authority to verify clients with
	MinTLSVersion      string        // MinTLSVersion contains the minimum TLS version that is acceptable.
}

Config contains options for the http Server

func DefaultCfg added in v1.61.0

func DefaultCfg() Config

DefaultCfg is the default values used for Config

func (*Config) AddFlagsPrefix added in v1.61.0

func (cfg *Config) AddFlagsPrefix(flagSet *pflag.FlagSet, prefix string)

AddFlagsPrefix adds flags for the httplib

type CustomAuthFn added in v1.61.0

type CustomAuthFn func(user, pass string) (value interface{}, err error)

CustomAuthFn if used will be used to authenticate user, pass. If an error is returned then the user is not authenticated.

If a non nil value is returned then it is added to the context under the key

type LoggedBasicAuth added in v1.61.0

type LoggedBasicAuth struct {
	goauth.BasicAuth
}

LoggedBasicAuth simply wraps the goauth.BasicAuth struct

func NewLoggedBasicAuthenticator added in v1.61.0

func NewLoggedBasicAuthenticator(realm string, secrets goauth.SecretProvider) *LoggedBasicAuth

NewLoggedBasicAuthenticator instantiates a new instance of LoggedBasicAuthenticator

func (*LoggedBasicAuth) CheckAuth added in v1.61.0

func (a *LoggedBasicAuth) CheckAuth(r *http.Request) string

CheckAuth extends BasicAuth.CheckAuth to emit a log entry for unauthorised requests

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware function signature required by chi.Router.Use()

func MiddlewareAuthBasic added in v1.61.0

func MiddlewareAuthBasic(user, pass, realm, salt string) Middleware

MiddlewareAuthBasic instantiates middleware that authenticates for a single user

func MiddlewareAuthCustom added in v1.61.0

func MiddlewareAuthCustom(fn CustomAuthFn, realm string) Middleware

MiddlewareAuthCustom instantiates middleware that authenticates using a custom function

func MiddlewareAuthHtpasswd added in v1.61.0

func MiddlewareAuthHtpasswd(path, realm string) Middleware

MiddlewareAuthHtpasswd instantiates middleware that authenticates against the passed htpasswd file

func MiddlewareCORS added in v1.61.0

func MiddlewareCORS(allowOrigin string) Middleware

MiddlewareCORS instantiates middleware that handles basic CORS protections for rcd

func MiddlewareStripPrefix added in v1.61.0

func MiddlewareStripPrefix(prefix string) Middleware

MiddlewareStripPrefix instantiates middleware that removes the BaseURL from the path

type Option added in v1.61.0

type Option func(*Server)

Option allows customizing the server

func WithAuth added in v1.61.0

func WithAuth(cfg AuthConfig) Option

WithAuth option initializes the appropriate auth middleware

func WithConfig added in v1.61.0

func WithConfig(cfg Config) Option

WithConfig option applies the Config to the server, overriding defaults

func WithTemplate added in v1.61.0

func WithTemplate(cfg TemplateConfig) Option

WithTemplate option allows the parsing of a template

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server contains info about the running http server

func NewServer

func NewServer(ctx context.Context, options ...Option) (*Server, error)

NewServer instantiates a new http server using provided listeners and options This function is provided if the default http server does not meet a services requirements and should not generally be used A http server can listen using multiple listeners. For example, a listener for port 80, and a listener for port 443. tlsListeners are ignored if opt.TLSKey is not provided

func (*Server) HTMLTemplate added in v1.61.0

func (s *Server) HTMLTemplate() *template.Template

HTMLTemplate returns the parsed template, if WithTemplate option was passed.

func (*Server) Router

func (s *Server) Router() chi.Router

Router returns the server base router

func (*Server) Serve added in v1.61.0

func (s *Server) Serve()

Serve starts the HTTP server on each listener

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown gracefully shuts down the server

func (*Server) URLs added in v1.61.0

func (s *Server) URLs() []string

URLs returns all configured URLS

func (*Server) UsingAuth added in v1.61.0

func (s *Server) UsingAuth() bool

UsingAuth returns true if authentication is required

func (*Server) Wait added in v1.61.0

func (s *Server) Wait()

Wait blocks while the server is serving requests

type TemplateConfig added in v1.61.0

type TemplateConfig struct {
	Path string
}

TemplateConfig for the templating functionality

func DefaultTemplateCfg added in v1.61.0

func DefaultTemplateCfg() TemplateConfig

DefaultTemplateCfg returns a new config which can be customized by command line flags

func (*TemplateConfig) AddFlagsPrefix added in v1.61.0

func (cfg *TemplateConfig) AddFlagsPrefix(flagSet *pflag.FlagSet, prefix string)

AddFlagsPrefix for the templating functionality

Directories

Path Synopsis
Package serve deals with serving objects over HTTP
Package serve deals with serving objects over HTTP

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL