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.

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