linx-server/server.go

254 lines
7.7 KiB
Go
Raw Normal View History

2015-09-24 05:44:49 +00:00
package main
import (
"flag"
"log"
"net"
"net/http"
"net/http/fcgi"
2015-10-30 22:36:47 +00:00
"net/url"
2015-09-26 02:03:14 +00:00
"os"
2015-09-28 02:17:12 +00:00
"regexp"
"strconv"
"strings"
2015-09-30 19:54:30 +00:00
"time"
2015-09-24 05:44:49 +00:00
"github.com/GeertJohan/go.rice"
"github.com/flosch/pongo2"
"github.com/vharitonsky/iniflags"
2015-10-07 16:48:44 +00:00
"github.com/zenazn/goji/graceful"
"github.com/zenazn/goji/web"
"github.com/zenazn/goji/web/middleware"
2015-09-24 05:44:49 +00:00
)
type headerList []string
func (h *headerList) String() string {
return strings.Join(*h, ",")
}
func (h *headerList) Set(value string) error {
*h = append(*h, value)
return nil
}
2015-09-24 05:44:49 +00:00
var Config struct {
bind string
filesDir string
metaDir string
siteName string
siteURL string
2015-10-30 22:36:47 +00:00
sitePath string
2015-10-07 16:48:44 +00:00
certFile string
keyFile string
contentSecurityPolicy string
fileContentSecurityPolicy string
xFrameOptions string
maxSize int64
2015-10-12 00:32:28 +00:00
realIp bool
2015-10-06 06:51:49 +00:00
noLogs bool
allowHotlink bool
fastcgi bool
remoteUploads bool
authFile string
remoteAuthFile string
addHeaders headerList
2015-09-24 05:44:49 +00:00
}
var Templates = make(map[string]*pongo2.Template)
var TemplateSet *pongo2.TemplateSet
2015-09-30 19:54:30 +00:00
var staticBox *rice.Box
var timeStarted time.Time
var timeStartedStr string
var remoteAuthKeys []string
func setup() *web.Mux {
mux := web.New()
// middleware
mux.Use(middleware.RequestID)
2015-10-12 00:32:28 +00:00
if Config.realIp {
mux.Use(middleware.RealIP)
}
if !Config.noLogs {
mux.Use(middleware.Logger)
}
mux.Use(middleware.Recoverer)
mux.Use(middleware.AutomaticOptions)
mux.Use(ContentSecurityPolicy(CSPOptions{
policy: Config.contentSecurityPolicy,
frame: Config.xFrameOptions,
}))
mux.Use(AddHeaders(Config.addHeaders))
if Config.authFile != "" {
mux.Use(UploadAuth(AuthOptions{
AuthFile: Config.authFile,
UnauthMethods: []string{"GET", "HEAD", "OPTIONS", "TRACE"},
}))
}
2015-09-28 02:17:12 +00:00
// make directories if needed
err := os.MkdirAll(Config.filesDir, 0755)
2015-09-26 02:03:14 +00:00
if err != nil {
2015-10-06 06:49:57 +00:00
log.Fatal("Could not create files directory:", err)
2015-09-26 02:03:14 +00:00
}
2015-09-28 02:17:12 +00:00
err = os.MkdirAll(Config.metaDir, 0700)
if err != nil {
2015-10-06 06:49:57 +00:00
log.Fatal("Could not create metadata directory:", err)
2015-09-28 02:17:12 +00:00
}
if Config.siteURL != "" {
// ensure siteURL ends wth '/'
if lastChar := Config.siteURL[len(Config.siteURL)-1:]; lastChar != "/" {
Config.siteURL = Config.siteURL + "/"
}
2015-09-28 02:17:12 +00:00
parsedUrl, err := url.Parse(Config.siteURL)
if err != nil {
log.Fatal("Could not parse siteurl:", err)
}
2015-10-30 22:36:47 +00:00
Config.sitePath = parsedUrl.Path
} else {
Config.sitePath = "/"
}
2015-10-30 22:36:47 +00:00
// Template setup
2015-09-29 01:58:50 +00:00
p2l, err := NewPongo2TemplatesLoader()
if err != nil {
2015-10-06 06:49:57 +00:00
log.Fatal("Error: could not load templates", err)
}
TemplateSet := pongo2.NewSet("templates", p2l)
TemplateSet.Globals["sitename"] = Config.siteName
2015-10-30 22:36:47 +00:00
TemplateSet.Globals["sitepath"] = Config.sitePath
TemplateSet.Globals["using_auth"] = Config.authFile != ""
err = populateTemplatesMap(TemplateSet, Templates)
if err != nil {
2015-10-06 06:49:57 +00:00
log.Fatal("Error: could not load templates", err)
}
2015-09-30 19:54:30 +00:00
staticBox = rice.MustFindBox("static")
timeStarted = time.Now()
timeStartedStr = strconv.FormatInt(timeStarted.Unix(), 10)
2015-09-30 19:54:30 +00:00
// Routing setup
2015-10-30 22:36:47 +00:00
nameRe := regexp.MustCompile("^" + Config.sitePath + `(?P<name>[a-z0-9-\.]+)$`)
selifRe := regexp.MustCompile("^" + Config.sitePath + `selif/(?P<name>[a-z0-9-\.]+)$`)
selifIndexRe := regexp.MustCompile("^" + Config.sitePath + `selif/$`)
torrentRe := regexp.MustCompile("^" + Config.sitePath + `(?P<name>[a-z0-9-\.]+)/torrent$`)
2015-09-24 05:44:49 +00:00
if Config.authFile == "" {
2015-10-30 22:36:47 +00:00
mux.Get(Config.sitePath, indexHandler)
mux.Get(Config.sitePath+"paste/", pasteHandler)
} else {
2015-10-30 22:36:47 +00:00
mux.Get(Config.sitePath, http.RedirectHandler(Config.sitePath+"API", 303))
mux.Get(Config.sitePath+"paste/", http.RedirectHandler(Config.sitePath+"API/", 303))
}
2015-10-30 22:36:47 +00:00
mux.Get(Config.sitePath+"paste", http.RedirectHandler(Config.sitePath+"paste/", 301))
2015-10-30 22:36:47 +00:00
mux.Get(Config.sitePath+"API/", apiDocHandler)
mux.Get(Config.sitePath+"API", http.RedirectHandler(Config.sitePath+"API/", 301))
2015-10-02 00:58:08 +00:00
if Config.remoteUploads {
2015-10-30 22:36:47 +00:00
mux.Get(Config.sitePath+"upload", uploadRemote)
mux.Get(Config.sitePath+"upload/", uploadRemote)
if Config.remoteAuthFile != "" {
remoteAuthKeys = readAuthKeys(Config.remoteAuthFile)
}
2015-10-02 00:58:08 +00:00
}
2015-10-30 22:36:47 +00:00
mux.Post(Config.sitePath+"upload", uploadPostHandler)
mux.Post(Config.sitePath+"upload/", uploadPostHandler)
mux.Put(Config.sitePath+"upload", uploadPutHandler)
mux.Put(Config.sitePath+"upload/", uploadPutHandler)
mux.Put(Config.sitePath+"upload/:name", uploadPutHandler)
2015-10-30 22:36:47 +00:00
mux.Delete(Config.sitePath+":name", deleteHandler)
2015-10-30 22:36:47 +00:00
mux.Get(Config.sitePath+"static/*", staticHandler)
mux.Get(Config.sitePath+"favicon.ico", staticHandler)
mux.Get(Config.sitePath+"robots.txt", staticHandler)
mux.Get(nameRe, fileDisplayHandler)
mux.Get(selifRe, fileServeHandler)
mux.Get(selifIndexRe, unauthorizedHandler)
mux.Get(torrentRe, fileTorrentHandler)
mux.NotFound(notFoundHandler)
return mux
}
func main() {
flag.StringVar(&Config.bind, "bind", "127.0.0.1:8080",
"host to bind to (default: 127.0.0.1:8080)")
flag.StringVar(&Config.filesDir, "filespath", "files/",
"path to files directory")
flag.StringVar(&Config.metaDir, "metapath", "meta/",
"path to metadata directory")
flag.BoolVar(&Config.noLogs, "nologs", false,
"remove stdout output for each request")
2015-09-29 23:28:10 +00:00
flag.BoolVar(&Config.allowHotlink, "allowhotlink", false,
"Allow hotlinking of files")
flag.StringVar(&Config.siteName, "sitename", "linx",
"name of the site")
flag.StringVar(&Config.siteURL, "siteurl", "",
"site base url (including trailing slash)")
flag.Int64Var(&Config.maxSize, "maxsize", 4*1024*1024*1024,
"maximum upload file size in bytes (default 4GB)")
2015-10-07 16:48:44 +00:00
flag.StringVar(&Config.certFile, "certfile", "",
"path to ssl certificate (for https)")
flag.StringVar(&Config.keyFile, "keyfile", "",
"path to ssl key (for https)")
2015-10-12 00:32:28 +00:00
flag.BoolVar(&Config.realIp, "realip", false,
"use X-Real-IP/X-Forwarded-For headers as original host")
flag.BoolVar(&Config.fastcgi, "fastcgi", false,
"serve through fastcgi")
2015-10-02 00:58:08 +00:00
flag.BoolVar(&Config.remoteUploads, "remoteuploads", false,
"enable remote uploads")
flag.StringVar(&Config.authFile, "authfile", "",
"path to a file containing newline-separated scrypted auth keys")
flag.StringVar(&Config.remoteAuthFile, "remoteauthfile", "",
"path to a file containing newline-separated scrypted auth keys for remote uploads")
2015-10-05 02:43:42 +00:00
flag.StringVar(&Config.contentSecurityPolicy, "contentsecuritypolicy",
"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; referrer origin;",
"value of default Content-Security-Policy header")
2015-10-05 02:43:42 +00:00
flag.StringVar(&Config.fileContentSecurityPolicy, "filecontentsecuritypolicy",
"default-src 'none'; img-src 'self'; object-src 'self'; media-src 'self'; style-src 'self' 'unsafe-inline'; referrer origin;",
"value of Content-Security-Policy header for file access")
2015-10-05 02:43:42 +00:00
flag.StringVar(&Config.xFrameOptions, "xframeoptions", "SAMEORIGIN",
"value of X-Frame-Options header")
flag.Var(&Config.addHeaders, "addheader",
"Add an arbitrary header to the response. This option can be used multiple times.")
iniflags.Parse()
mux := setup()
if Config.fastcgi {
2015-10-07 16:48:44 +00:00
listener, err := net.Listen("tcp", Config.bind)
if err != nil {
log.Fatal("Could not bind: ", err)
}
log.Printf("Serving over fastcgi, bound on %s", Config.bind)
fcgi.Serve(listener, mux)
2015-10-07 16:48:44 +00:00
} else if Config.certFile != "" {
log.Printf("Serving over https, bound on %s", Config.bind)
err := graceful.ListenAndServeTLS(Config.bind, Config.certFile, Config.keyFile, mux)
2015-10-07 16:48:44 +00:00
if err != nil {
log.Fatal(err)
}
} else {
log.Printf("Serving over http, bound on %s", Config.bind)
err := graceful.ListenAndServe(Config.bind, mux)
2015-10-07 16:48:44 +00:00
if err != nil {
log.Fatal(err)
}
}
2015-09-24 05:44:49 +00:00
}