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.

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