server.go 13 KB

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