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.

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