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.

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