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.
 
 
 

502 lines
11 KiB

  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2017 DutchCoders [https://github.com/dutchcoders/]
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. package server
  21. import (
  22. "errors"
  23. gorillaHandlers "github.com/gorilla/handlers"
  24. "log"
  25. "math/rand"
  26. "mime"
  27. "net/http"
  28. "net/url"
  29. "os"
  30. "os/signal"
  31. "strings"
  32. "sync"
  33. "syscall"
  34. "time"
  35. context "golang.org/x/net/context"
  36. "github.com/PuerkitoBio/ghost/handlers"
  37. "github.com/VojtechVitek/ratelimit"
  38. "github.com/VojtechVitek/ratelimit/memory"
  39. "github.com/gorilla/mux"
  40. _ "net/http/pprof"
  41. "crypto/tls"
  42. web "github.com/dutchcoders/transfer.sh-web"
  43. assetfs "github.com/elazarl/go-bindata-assetfs"
  44. autocert "golang.org/x/crypto/acme/autocert"
  45. "path/filepath"
  46. )
  47. const SERVER_INFO = "transfer.sh"
  48. // parse request with maximum memory of _24Kilobits
  49. const _24K = (1 << 3) * 24
  50. // parse request with maximum memory of _5Megabytes
  51. const _5M = (1 << 20) * 5
  52. type OptionFn func(*Server)
  53. func ClamavHost(s string) OptionFn {
  54. return func(srvr *Server) {
  55. srvr.ClamAVDaemonHost = s
  56. }
  57. }
  58. func VirustotalKey(s string) OptionFn {
  59. return func(srvr *Server) {
  60. srvr.VirusTotalKey = s
  61. }
  62. }
  63. func Listener(s string) OptionFn {
  64. return func(srvr *Server) {
  65. srvr.ListenerString = s
  66. }
  67. }
  68. func CorsDomains(s string) OptionFn {
  69. return func(srvr *Server) {
  70. srvr.CorsDomains = s
  71. }
  72. }
  73. func GoogleAnalytics(gaKey string) OptionFn {
  74. return func(srvr *Server) {
  75. srvr.gaKey = gaKey
  76. }
  77. }
  78. func UserVoice(userVoiceKey string) OptionFn {
  79. return func(srvr *Server) {
  80. srvr.userVoiceKey = userVoiceKey
  81. }
  82. }
  83. func TLSListener(s string, t bool) OptionFn {
  84. return func(srvr *Server) {
  85. srvr.TLSListenerString = s
  86. srvr.TLSListenerOnly = t
  87. }
  88. }
  89. func ProfileListener(s string) OptionFn {
  90. return func(srvr *Server) {
  91. srvr.ProfileListenerString = s
  92. }
  93. }
  94. func WebPath(s string) OptionFn {
  95. return func(srvr *Server) {
  96. if s[len(s)-1:] != "/" {
  97. s = s + string(filepath.Separator)
  98. }
  99. srvr.webPath = s
  100. }
  101. }
  102. func ProxyPath(s string) OptionFn {
  103. return func(srvr *Server) {
  104. if s[len(s)-1:] != "/" {
  105. s = s + string(filepath.Separator)
  106. }
  107. srvr.proxyPath = s
  108. }
  109. }
  110. func ProxyPort(s string) OptionFn {
  111. return func(srvr *Server) {
  112. srvr.proxyPort = s
  113. }
  114. }
  115. func TempPath(s string) OptionFn {
  116. return func(srvr *Server) {
  117. if s[len(s)-1:] != "/" {
  118. s = s + string(filepath.Separator)
  119. }
  120. srvr.tempPath = s
  121. }
  122. }
  123. func LogFile(logger *log.Logger, s string) OptionFn {
  124. return func(srvr *Server) {
  125. f, err := os.OpenFile(s, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  126. if err != nil {
  127. log.Fatalf("error opening file: %v", err)
  128. }
  129. logger.SetOutput(f)
  130. srvr.logger = logger
  131. }
  132. }
  133. func Logger(logger *log.Logger) OptionFn {
  134. return func(srvr *Server) {
  135. srvr.logger = logger
  136. }
  137. }
  138. func RateLimit(requests int) OptionFn {
  139. return func(srvr *Server) {
  140. srvr.rateLimitRequests = requests
  141. }
  142. }
  143. func ForceHTTPs() OptionFn {
  144. return func(srvr *Server) {
  145. srvr.forceHTTPs = true
  146. }
  147. }
  148. func EnableProfiler() OptionFn {
  149. return func(srvr *Server) {
  150. srvr.profilerEnabled = true
  151. }
  152. }
  153. func UseStorage(s Storage) OptionFn {
  154. return func(srvr *Server) {
  155. srvr.storage = s
  156. }
  157. }
  158. func UseLetsEncrypt(hosts []string) OptionFn {
  159. return func(srvr *Server) {
  160. cacheDir := "./cache/"
  161. m := autocert.Manager{
  162. Prompt: autocert.AcceptTOS,
  163. Cache: autocert.DirCache(cacheDir),
  164. HostPolicy: func(_ context.Context, host string) error {
  165. found := false
  166. for _, h := range hosts {
  167. found = found || strings.HasSuffix(host, h)
  168. }
  169. if !found {
  170. return errors.New("acme/autocert: host not configured")
  171. }
  172. return nil
  173. },
  174. }
  175. srvr.tlsConfig = &tls.Config{
  176. GetCertificate: m.GetCertificate,
  177. }
  178. }
  179. }
  180. func TLSConfig(cert, pk string) OptionFn {
  181. certificate, err := tls.LoadX509KeyPair(cert, pk)
  182. return func(srvr *Server) {
  183. srvr.tlsConfig = &tls.Config{
  184. GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  185. return &certificate, err
  186. },
  187. }
  188. }
  189. }
  190. func HttpAuthCredentials(user string, pass string) OptionFn {
  191. return func(srvr *Server) {
  192. srvr.AuthUser = user
  193. srvr.AuthPass = pass
  194. }
  195. }
  196. func FilterOptions(options IPFilterOptions) OptionFn {
  197. for i, allowedIP := range options.AllowedIPs {
  198. options.AllowedIPs[i] = strings.TrimSpace(allowedIP)
  199. }
  200. for i, blockedIP := range options.BlockedIPs {
  201. options.BlockedIPs[i] = strings.TrimSpace(blockedIP)
  202. }
  203. return func(srvr *Server) {
  204. srvr.ipFilterOptions = &options
  205. }
  206. }
  207. type Server struct {
  208. AuthUser string
  209. AuthPass string
  210. logger *log.Logger
  211. tlsConfig *tls.Config
  212. profilerEnabled bool
  213. locks map[string]*sync.Mutex
  214. rateLimitRequests int
  215. storage Storage
  216. forceHTTPs bool
  217. ipFilterOptions *IPFilterOptions
  218. VirusTotalKey string
  219. ClamAVDaemonHost string
  220. tempPath string
  221. webPath string
  222. proxyPath string
  223. proxyPort string
  224. gaKey string
  225. userVoiceKey string
  226. TLSListenerOnly bool
  227. CorsDomains string
  228. ListenerString string
  229. TLSListenerString string
  230. ProfileListenerString string
  231. Certificate string
  232. LetsEncryptCache string
  233. }
  234. func New(options ...OptionFn) (*Server, error) {
  235. s := &Server{
  236. locks: map[string]*sync.Mutex{},
  237. }
  238. for _, optionFn := range options {
  239. optionFn(s)
  240. }
  241. return s, nil
  242. }
  243. func init() {
  244. rand.Seed(time.Now().UTC().UnixNano())
  245. }
  246. func (s *Server) Run() {
  247. listening := false
  248. if s.profilerEnabled {
  249. listening = true
  250. go func() {
  251. s.logger.Println("Profiled listening at: :6060")
  252. http.ListenAndServe(":6060", nil)
  253. }()
  254. }
  255. r := mux.NewRouter()
  256. var fs http.FileSystem
  257. if s.webPath != "" {
  258. s.logger.Println("Using static file path: ", s.webPath)
  259. fs = http.Dir(s.webPath)
  260. htmlTemplates, _ = htmlTemplates.ParseGlob(s.webPath + "*.html")
  261. textTemplates, _ = textTemplates.ParseGlob(s.webPath + "*.txt")
  262. } else {
  263. fs = &assetfs.AssetFS{
  264. Asset: web.Asset,
  265. AssetDir: web.AssetDir,
  266. AssetInfo: func(path string) (os.FileInfo, error) {
  267. return os.Stat(path)
  268. },
  269. Prefix: web.Prefix,
  270. }
  271. for _, path := range web.AssetNames() {
  272. bytes, err := web.Asset(path)
  273. if err != nil {
  274. s.logger.Panicf("Unable to parse: path=%s, err=%s", path, err)
  275. }
  276. htmlTemplates.New(stripPrefix(path)).Parse(string(bytes))
  277. textTemplates.New(stripPrefix(path)).Parse(string(bytes))
  278. }
  279. }
  280. staticHandler := http.FileServer(fs)
  281. r.PathPrefix("/images/").Handler(staticHandler).Methods("GET")
  282. r.PathPrefix("/styles/").Handler(staticHandler).Methods("GET")
  283. r.PathPrefix("/scripts/").Handler(staticHandler).Methods("GET")
  284. r.PathPrefix("/fonts/").Handler(staticHandler).Methods("GET")
  285. r.PathPrefix("/ico/").Handler(staticHandler).Methods("GET")
  286. r.HandleFunc("/favicon.ico", staticHandler.ServeHTTP).Methods("GET")
  287. r.HandleFunc("/robots.txt", staticHandler.ServeHTTP).Methods("GET")
  288. r.HandleFunc("/{filename:(?:favicon\\.ico|robots\\.txt|health\\.html)}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  289. r.HandleFunc("/health.html", healthHandler).Methods("GET")
  290. r.HandleFunc("/", s.viewHandler).Methods("GET")
  291. r.HandleFunc("/({files:.*}).zip", s.zipHandler).Methods("GET")
  292. r.HandleFunc("/({files:.*}).tar", s.tarHandler).Methods("GET")
  293. r.HandleFunc("/({files:.*}).tar.gz", s.tarGzHandler).Methods("GET")
  294. r.HandleFunc("/{token}/{filename}", s.headHandler).Methods("HEAD")
  295. r.HandleFunc("/{action:(?:download|get|inline)}/{token}/{filename}", s.headHandler).Methods("HEAD")
  296. r.HandleFunc("/{token}/{filename}", s.previewHandler).MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) (match bool) {
  297. match = false
  298. // The file will show a preview page when opening the link in browser directly or
  299. // from external link. If the referer url path and current path are the same it will be
  300. // downloaded.
  301. if !acceptsHTML(r.Header) {
  302. return false
  303. }
  304. match = (r.Referer() == "")
  305. u, err := url.Parse(r.Referer())
  306. if err != nil {
  307. s.logger.Fatal(err)
  308. return
  309. }
  310. match = match || (u.Path != r.URL.Path)
  311. return
  312. }).Methods("GET")
  313. getHandlerFn := s.getHandler
  314. if s.rateLimitRequests > 0 {
  315. getHandlerFn = ratelimit.Request(ratelimit.IP).Rate(s.rateLimitRequests, 60*time.Second).LimitBy(memory.New())(http.HandlerFunc(getHandlerFn)).ServeHTTP
  316. }
  317. r.HandleFunc("/{token}/{filename}", getHandlerFn).Methods("GET")
  318. r.HandleFunc("/{action:(?:download|get|inline)}/{token}/{filename}", getHandlerFn).Methods("GET")
  319. r.HandleFunc("/{filename}/virustotal", s.virusTotalHandler).Methods("PUT")
  320. r.HandleFunc("/{filename}/scan", s.scanHandler).Methods("PUT")
  321. r.HandleFunc("/put/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  322. r.HandleFunc("/upload/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  323. r.HandleFunc("/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  324. r.HandleFunc("/", s.BasicAuthHandler(http.HandlerFunc(s.postHandler))).Methods("POST")
  325. // r.HandleFunc("/{page}", viewHandler).Methods("GET")
  326. r.HandleFunc("/{token}/{filename}/{deletionToken}", s.deleteHandler).Methods("DELETE")
  327. r.NotFoundHandler = http.HandlerFunc(s.notFoundHandler)
  328. mime.AddExtensionType(".md", "text/x-markdown")
  329. s.logger.Printf("Transfer.sh server started.\nusing temp folder: %s\nusing storage provider: %s", s.tempPath, s.storage.Type())
  330. var cors func(http.Handler) http.Handler
  331. if len(s.CorsDomains) > 0 {
  332. cors = gorillaHandlers.CORS(
  333. gorillaHandlers.AllowedHeaders([]string{"*"}),
  334. gorillaHandlers.AllowedOrigins(strings.Split(s.CorsDomains, ",")),
  335. gorillaHandlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"}),
  336. )
  337. } else {
  338. cors = func(h http.Handler) http.Handler {
  339. return h
  340. }
  341. }
  342. h := handlers.PanicHandler(
  343. IPFilterHandler(
  344. handlers.LogHandler(
  345. LoveHandler(
  346. s.RedirectHandler(cors(r))),
  347. handlers.NewLogOptions(s.logger.Printf, "_default_"),
  348. ),
  349. s.ipFilterOptions,
  350. ),
  351. nil,
  352. )
  353. if !s.TLSListenerOnly {
  354. srvr := &http.Server{
  355. Addr: s.ListenerString,
  356. Handler: h,
  357. }
  358. listening = true
  359. s.logger.Printf("listening on port: %v\n", s.ListenerString)
  360. go func() {
  361. srvr.ListenAndServe()
  362. }()
  363. }
  364. if s.TLSListenerString != "" {
  365. listening = true
  366. s.logger.Printf("listening on port: %v\n", s.TLSListenerString)
  367. go func() {
  368. s := &http.Server{
  369. Addr: s.TLSListenerString,
  370. Handler: h,
  371. TLSConfig: s.tlsConfig,
  372. }
  373. if err := s.ListenAndServeTLS("", ""); err != nil {
  374. panic(err)
  375. }
  376. }()
  377. }
  378. s.logger.Printf("---------------------------")
  379. term := make(chan os.Signal, 1)
  380. signal.Notify(term, os.Interrupt)
  381. signal.Notify(term, syscall.SIGTERM)
  382. if listening {
  383. <-term
  384. } else {
  385. s.logger.Printf("No listener active.")
  386. }
  387. s.logger.Printf("Server stopped.")
  388. }