Contains the Concourse pipeline definition for building a line-server container
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

260 lines
8.0 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package main
  2. import (
  3. "flag"
  4. "log"
  5. "net"
  6. "net/http"
  7. "net/http/fcgi"
  8. "net/url"
  9. "os"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/GeertJohan/go.rice"
  15. "github.com/andreimarcu/linx-server/backends"
  16. "github.com/andreimarcu/linx-server/backends/localfs"
  17. "github.com/flosch/pongo2"
  18. "github.com/vharitonsky/iniflags"
  19. "github.com/zenazn/goji/graceful"
  20. "github.com/zenazn/goji/web"
  21. "github.com/zenazn/goji/web/middleware"
  22. )
  23. type headerList []string
  24. func (h *headerList) String() string {
  25. return strings.Join(*h, ",")
  26. }
  27. func (h *headerList) Set(value string) error {
  28. *h = append(*h, value)
  29. return nil
  30. }
  31. var Config struct {
  32. bind string
  33. filesDir string
  34. metaDir string
  35. siteName string
  36. siteURL string
  37. sitePath string
  38. certFile string
  39. keyFile string
  40. contentSecurityPolicy string
  41. fileContentSecurityPolicy string
  42. xFrameOptions string
  43. maxSize int64
  44. realIp bool
  45. noLogs bool
  46. allowHotlink bool
  47. fastcgi bool
  48. remoteUploads bool
  49. authFile string
  50. remoteAuthFile string
  51. addHeaders headerList
  52. }
  53. var Templates = make(map[string]*pongo2.Template)
  54. var TemplateSet *pongo2.TemplateSet
  55. var staticBox *rice.Box
  56. var timeStarted time.Time
  57. var timeStartedStr string
  58. var remoteAuthKeys []string
  59. var metaBackend backends.StorageBackend
  60. var fileBackend backends.StorageBackend
  61. func setup() *web.Mux {
  62. mux := web.New()
  63. // middleware
  64. mux.Use(middleware.RequestID)
  65. if Config.realIp {
  66. mux.Use(middleware.RealIP)
  67. }
  68. if !Config.noLogs {
  69. mux.Use(middleware.Logger)
  70. }
  71. mux.Use(middleware.Recoverer)
  72. mux.Use(middleware.AutomaticOptions)
  73. mux.Use(ContentSecurityPolicy(CSPOptions{
  74. policy: Config.contentSecurityPolicy,
  75. frame: Config.xFrameOptions,
  76. }))
  77. mux.Use(AddHeaders(Config.addHeaders))
  78. if Config.authFile != "" {
  79. mux.Use(UploadAuth(AuthOptions{
  80. AuthFile: Config.authFile,
  81. UnauthMethods: []string{"GET", "HEAD", "OPTIONS", "TRACE"},
  82. }))
  83. }
  84. // make directories if needed
  85. err := os.MkdirAll(Config.filesDir, 0755)
  86. if err != nil {
  87. log.Fatal("Could not create files directory:", err)
  88. }
  89. err = os.MkdirAll(Config.metaDir, 0700)
  90. if err != nil {
  91. log.Fatal("Could not create metadata directory:", err)
  92. }
  93. if Config.siteURL != "" {
  94. // ensure siteURL ends wth '/'
  95. if lastChar := Config.siteURL[len(Config.siteURL)-1:]; lastChar != "/" {
  96. Config.siteURL = Config.siteURL + "/"
  97. }
  98. parsedUrl, err := url.Parse(Config.siteURL)
  99. if err != nil {
  100. log.Fatal("Could not parse siteurl:", err)
  101. }
  102. Config.sitePath = parsedUrl.Path
  103. } else {
  104. Config.sitePath = "/"
  105. }
  106. metaBackend = localfs.NewLocalfsBackend(Config.metaDir)
  107. fileBackend = localfs.NewLocalfsBackend(Config.filesDir)
  108. // Template setup
  109. p2l, err := NewPongo2TemplatesLoader()
  110. if err != nil {
  111. log.Fatal("Error: could not load templates", err)
  112. }
  113. TemplateSet := pongo2.NewSet("templates", p2l)
  114. TemplateSet.Globals["sitename"] = Config.siteName
  115. TemplateSet.Globals["sitepath"] = Config.sitePath
  116. TemplateSet.Globals["using_auth"] = Config.authFile != ""
  117. err = populateTemplatesMap(TemplateSet, Templates)
  118. if err != nil {
  119. log.Fatal("Error: could not load templates", err)
  120. }
  121. staticBox = rice.MustFindBox("static")
  122. timeStarted = time.Now()
  123. timeStartedStr = strconv.FormatInt(timeStarted.Unix(), 10)
  124. // Routing setup
  125. nameRe := regexp.MustCompile("^" + Config.sitePath + `(?P<name>[a-z0-9-\.]+)$`)
  126. selifRe := regexp.MustCompile("^" + Config.sitePath + `selif/(?P<name>[a-z0-9-\.]+)$`)
  127. selifIndexRe := regexp.MustCompile("^" + Config.sitePath + `selif/$`)
  128. torrentRe := regexp.MustCompile("^" + Config.sitePath + `(?P<name>[a-z0-9-\.]+)/torrent$`)
  129. if Config.authFile == "" {
  130. mux.Get(Config.sitePath, indexHandler)
  131. mux.Get(Config.sitePath+"paste/", pasteHandler)
  132. } else {
  133. mux.Get(Config.sitePath, http.RedirectHandler(Config.sitePath+"API", 303))
  134. mux.Get(Config.sitePath+"paste/", http.RedirectHandler(Config.sitePath+"API/", 303))
  135. }
  136. mux.Get(Config.sitePath+"paste", http.RedirectHandler(Config.sitePath+"paste/", 301))
  137. mux.Get(Config.sitePath+"API/", apiDocHandler)
  138. mux.Get(Config.sitePath+"API", http.RedirectHandler(Config.sitePath+"API/", 301))
  139. if Config.remoteUploads {
  140. mux.Get(Config.sitePath+"upload", uploadRemote)
  141. mux.Get(Config.sitePath+"upload/", uploadRemote)
  142. if Config.remoteAuthFile != "" {
  143. remoteAuthKeys = readAuthKeys(Config.remoteAuthFile)
  144. }
  145. }
  146. mux.Post(Config.sitePath+"upload", uploadPostHandler)
  147. mux.Post(Config.sitePath+"upload/", uploadPostHandler)
  148. mux.Put(Config.sitePath+"upload", uploadPutHandler)
  149. mux.Put(Config.sitePath+"upload/", uploadPutHandler)
  150. mux.Put(Config.sitePath+"upload/:name", uploadPutHandler)
  151. mux.Delete(Config.sitePath+":name", deleteHandler)
  152. mux.Get(Config.sitePath+"static/*", staticHandler)
  153. mux.Get(Config.sitePath+"favicon.ico", staticHandler)
  154. mux.Get(Config.sitePath+"robots.txt", staticHandler)
  155. mux.Get(nameRe, fileDisplayHandler)
  156. mux.Get(selifRe, fileServeHandler)
  157. mux.Get(selifIndexRe, unauthorizedHandler)
  158. mux.Get(torrentRe, fileTorrentHandler)
  159. mux.NotFound(notFoundHandler)
  160. return mux
  161. }
  162. func main() {
  163. flag.StringVar(&Config.bind, "bind", "127.0.0.1:8080",
  164. "host to bind to (default: 127.0.0.1:8080)")
  165. flag.StringVar(&Config.filesDir, "filespath", "files/",
  166. "path to files directory")
  167. flag.StringVar(&Config.metaDir, "metapath", "meta/",
  168. "path to metadata directory")
  169. flag.BoolVar(&Config.noLogs, "nologs", false,
  170. "remove stdout output for each request")
  171. flag.BoolVar(&Config.allowHotlink, "allowhotlink", false,
  172. "Allow hotlinking of files")
  173. flag.StringVar(&Config.siteName, "sitename", "linx",
  174. "name of the site")
  175. flag.StringVar(&Config.siteURL, "siteurl", "",
  176. "site base url (including trailing slash)")
  177. flag.Int64Var(&Config.maxSize, "maxsize", 4*1024*1024*1024,
  178. "maximum upload file size in bytes (default 4GB)")
  179. flag.StringVar(&Config.certFile, "certfile", "",
  180. "path to ssl certificate (for https)")
  181. flag.StringVar(&Config.keyFile, "keyfile", "",
  182. "path to ssl key (for https)")
  183. flag.BoolVar(&Config.realIp, "realip", false,
  184. "use X-Real-IP/X-Forwarded-For headers as original host")
  185. flag.BoolVar(&Config.fastcgi, "fastcgi", false,
  186. "serve through fastcgi")
  187. flag.BoolVar(&Config.remoteUploads, "remoteuploads", false,
  188. "enable remote uploads")
  189. flag.StringVar(&Config.authFile, "authfile", "",
  190. "path to a file containing newline-separated scrypted auth keys")
  191. flag.StringVar(&Config.remoteAuthFile, "remoteauthfile", "",
  192. "path to a file containing newline-separated scrypted auth keys for remote uploads")
  193. flag.StringVar(&Config.contentSecurityPolicy, "contentsecuritypolicy",
  194. "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; referrer origin;",
  195. "value of default Content-Security-Policy header")
  196. flag.StringVar(&Config.fileContentSecurityPolicy, "filecontentsecuritypolicy",
  197. "default-src 'none'; img-src 'self'; object-src 'self'; media-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; referrer origin;",
  198. "value of Content-Security-Policy header for file access")
  199. flag.StringVar(&Config.xFrameOptions, "xframeoptions", "SAMEORIGIN",
  200. "value of X-Frame-Options header")
  201. flag.Var(&Config.addHeaders, "addheader",
  202. "Add an arbitrary header to the response. This option can be used multiple times.")
  203. iniflags.Parse()
  204. mux := setup()
  205. if Config.fastcgi {
  206. listener, err := net.Listen("tcp", Config.bind)
  207. if err != nil {
  208. log.Fatal("Could not bind: ", err)
  209. }
  210. log.Printf("Serving over fastcgi, bound on %s", Config.bind)
  211. fcgi.Serve(listener, mux)
  212. } else if Config.certFile != "" {
  213. log.Printf("Serving over https, bound on %s", Config.bind)
  214. err := graceful.ListenAndServeTLS(Config.bind, Config.certFile, Config.keyFile, mux)
  215. if err != nil {
  216. log.Fatal(err)
  217. }
  218. } else {
  219. log.Printf("Serving over http, bound on %s", Config.bind)
  220. err := graceful.ListenAndServe(Config.bind, mux)
  221. if err != nil {
  222. log.Fatal(err)
  223. }
  224. }
  225. }