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.

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