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.

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