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.

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