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.

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