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.
 
 
 

508 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. "errors"
  23. gorillaHandlers "github.com/gorilla/handlers"
  24. "log"
  25. crypto_rand "crypto/rand"
  26. "encoding/binary"
  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 RateLimit(requests int) OptionFn {
  141. return func(srvr *Server) {
  142. srvr.rateLimitRequests = requests
  143. }
  144. }
  145. func ForceHTTPs() OptionFn {
  146. return func(srvr *Server) {
  147. srvr.forceHTTPs = true
  148. }
  149. }
  150. func EnableProfiler() OptionFn {
  151. return func(srvr *Server) {
  152. srvr.profilerEnabled = true
  153. }
  154. }
  155. func UseStorage(s Storage) OptionFn {
  156. return func(srvr *Server) {
  157. srvr.storage = s
  158. }
  159. }
  160. func UseLetsEncrypt(hosts []string) OptionFn {
  161. return func(srvr *Server) {
  162. cacheDir := "./cache/"
  163. m := autocert.Manager{
  164. Prompt: autocert.AcceptTOS,
  165. Cache: autocert.DirCache(cacheDir),
  166. HostPolicy: func(_ context.Context, host string) error {
  167. found := false
  168. for _, h := range hosts {
  169. found = found || strings.HasSuffix(host, h)
  170. }
  171. if !found {
  172. return errors.New("acme/autocert: host not configured")
  173. }
  174. return nil
  175. },
  176. }
  177. srvr.tlsConfig = &tls.Config{
  178. GetCertificate: m.GetCertificate,
  179. }
  180. }
  181. }
  182. func TLSConfig(cert, pk string) OptionFn {
  183. certificate, err := tls.LoadX509KeyPair(cert, pk)
  184. return func(srvr *Server) {
  185. srvr.tlsConfig = &tls.Config{
  186. GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  187. return &certificate, err
  188. },
  189. }
  190. }
  191. }
  192. func HttpAuthCredentials(user string, pass string) OptionFn {
  193. return func(srvr *Server) {
  194. srvr.AuthUser = user
  195. srvr.AuthPass = pass
  196. }
  197. }
  198. func FilterOptions(options IPFilterOptions) OptionFn {
  199. for i, allowedIP := range options.AllowedIPs {
  200. options.AllowedIPs[i] = strings.TrimSpace(allowedIP)
  201. }
  202. for i, blockedIP := range options.BlockedIPs {
  203. options.BlockedIPs[i] = strings.TrimSpace(blockedIP)
  204. }
  205. return func(srvr *Server) {
  206. srvr.ipFilterOptions = &options
  207. }
  208. }
  209. type Server struct {
  210. AuthUser string
  211. AuthPass string
  212. logger *log.Logger
  213. tlsConfig *tls.Config
  214. profilerEnabled bool
  215. locks map[string]*sync.Mutex
  216. rateLimitRequests int
  217. storage Storage
  218. forceHTTPs bool
  219. ipFilterOptions *IPFilterOptions
  220. VirusTotalKey string
  221. ClamAVDaemonHost string
  222. tempPath string
  223. webPath string
  224. proxyPath string
  225. proxyPort string
  226. gaKey string
  227. userVoiceKey string
  228. TLSListenerOnly bool
  229. CorsDomains string
  230. ListenerString string
  231. TLSListenerString string
  232. ProfileListenerString string
  233. Certificate string
  234. LetsEncryptCache string
  235. }
  236. func New(options ...OptionFn) (*Server, error) {
  237. s := &Server{
  238. locks: map[string]*sync.Mutex{},
  239. }
  240. for _, optionFn := range options {
  241. optionFn(s)
  242. }
  243. return s, nil
  244. }
  245. func init() {
  246. var seedBytes [8]byte
  247. if _, err := crypto_rand.Read(seedBytes[:]); err != nil {
  248. panic("cannot obtain cryptographically secure seed")
  249. }
  250. rand.Seed(int64(binary.LittleEndian.Uint64(seedBytes[:])))
  251. }
  252. func (s *Server) Run() {
  253. listening := false
  254. if s.profilerEnabled {
  255. listening = true
  256. go func() {
  257. s.logger.Println("Profiled listening at: :6060")
  258. http.ListenAndServe(":6060", nil)
  259. }()
  260. }
  261. r := mux.NewRouter()
  262. var fs http.FileSystem
  263. if s.webPath != "" {
  264. s.logger.Println("Using static file path: ", s.webPath)
  265. fs = http.Dir(s.webPath)
  266. htmlTemplates, _ = htmlTemplates.ParseGlob(s.webPath + "*.html")
  267. textTemplates, _ = textTemplates.ParseGlob(s.webPath + "*.txt")
  268. } else {
  269. fs = &assetfs.AssetFS{
  270. Asset: web.Asset,
  271. AssetDir: web.AssetDir,
  272. AssetInfo: func(path string) (os.FileInfo, error) {
  273. return os.Stat(path)
  274. },
  275. Prefix: web.Prefix,
  276. }
  277. for _, path := range web.AssetNames() {
  278. bytes, err := web.Asset(path)
  279. if err != nil {
  280. s.logger.Panicf("Unable to parse: path=%s, err=%s", path, err)
  281. }
  282. htmlTemplates.New(stripPrefix(path)).Parse(string(bytes))
  283. textTemplates.New(stripPrefix(path)).Parse(string(bytes))
  284. }
  285. }
  286. staticHandler := http.FileServer(fs)
  287. r.PathPrefix("/images/").Handler(staticHandler).Methods("GET")
  288. r.PathPrefix("/styles/").Handler(staticHandler).Methods("GET")
  289. r.PathPrefix("/scripts/").Handler(staticHandler).Methods("GET")
  290. r.PathPrefix("/fonts/").Handler(staticHandler).Methods("GET")
  291. r.PathPrefix("/ico/").Handler(staticHandler).Methods("GET")
  292. r.HandleFunc("/favicon.ico", staticHandler.ServeHTTP).Methods("GET")
  293. r.HandleFunc("/robots.txt", staticHandler.ServeHTTP).Methods("GET")
  294. r.HandleFunc("/{filename:(?:favicon\\.ico|robots\\.txt|health\\.html)}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  295. r.HandleFunc("/health.html", healthHandler).Methods("GET")
  296. r.HandleFunc("/", s.viewHandler).Methods("GET")
  297. r.HandleFunc("/({files:.*}).zip", s.zipHandler).Methods("GET")
  298. r.HandleFunc("/({files:.*}).tar", s.tarHandler).Methods("GET")
  299. r.HandleFunc("/({files:.*}).tar.gz", s.tarGzHandler).Methods("GET")
  300. r.HandleFunc("/{token}/{filename}", s.headHandler).Methods("HEAD")
  301. r.HandleFunc("/{action:(?:download|get|inline)}/{token}/{filename}", s.headHandler).Methods("HEAD")
  302. r.HandleFunc("/{token}/{filename}", s.previewHandler).MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) (match bool) {
  303. match = false
  304. // The file will show a preview page when opening the link in browser directly or
  305. // from external link. If the referer url path and current path are the same it will be
  306. // downloaded.
  307. if !acceptsHTML(r.Header) {
  308. return false
  309. }
  310. match = (r.Referer() == "")
  311. u, err := url.Parse(r.Referer())
  312. if err != nil {
  313. s.logger.Fatal(err)
  314. return
  315. }
  316. match = match || (u.Path != r.URL.Path)
  317. return
  318. }).Methods("GET")
  319. getHandlerFn := s.getHandler
  320. if s.rateLimitRequests > 0 {
  321. getHandlerFn = ratelimit.Request(ratelimit.IP).Rate(s.rateLimitRequests, 60*time.Second).LimitBy(memory.New())(http.HandlerFunc(getHandlerFn)).ServeHTTP
  322. }
  323. r.HandleFunc("/{token}/{filename}", getHandlerFn).Methods("GET")
  324. r.HandleFunc("/{action:(?:download|get|inline)}/{token}/{filename}", getHandlerFn).Methods("GET")
  325. r.HandleFunc("/{filename}/virustotal", s.virusTotalHandler).Methods("PUT")
  326. r.HandleFunc("/{filename}/scan", s.scanHandler).Methods("PUT")
  327. r.HandleFunc("/put/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  328. r.HandleFunc("/upload/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  329. r.HandleFunc("/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  330. r.HandleFunc("/", s.BasicAuthHandler(http.HandlerFunc(s.postHandler))).Methods("POST")
  331. // r.HandleFunc("/{page}", viewHandler).Methods("GET")
  332. r.HandleFunc("/{token}/{filename}/{deletionToken}", s.deleteHandler).Methods("DELETE")
  333. r.NotFoundHandler = http.HandlerFunc(s.notFoundHandler)
  334. mime.AddExtensionType(".md", "text/x-markdown")
  335. s.logger.Printf("Transfer.sh server started.\nusing temp folder: %s\nusing storage provider: %s", s.tempPath, s.storage.Type())
  336. var cors func(http.Handler) http.Handler
  337. if len(s.CorsDomains) > 0 {
  338. cors = gorillaHandlers.CORS(
  339. gorillaHandlers.AllowedHeaders([]string{"*"}),
  340. gorillaHandlers.AllowedOrigins(strings.Split(s.CorsDomains, ",")),
  341. gorillaHandlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"}),
  342. )
  343. } else {
  344. cors = func(h http.Handler) http.Handler {
  345. return h
  346. }
  347. }
  348. h := handlers.PanicHandler(
  349. IPFilterHandler(
  350. handlers.LogHandler(
  351. LoveHandler(
  352. s.RedirectHandler(cors(r))),
  353. handlers.NewLogOptions(s.logger.Printf, "_default_"),
  354. ),
  355. s.ipFilterOptions,
  356. ),
  357. nil,
  358. )
  359. if !s.TLSListenerOnly {
  360. srvr := &http.Server{
  361. Addr: s.ListenerString,
  362. Handler: h,
  363. }
  364. listening = true
  365. s.logger.Printf("listening on port: %v\n", s.ListenerString)
  366. go func() {
  367. srvr.ListenAndServe()
  368. }()
  369. }
  370. if s.TLSListenerString != "" {
  371. listening = true
  372. s.logger.Printf("listening on port: %v\n", s.TLSListenerString)
  373. go func() {
  374. s := &http.Server{
  375. Addr: s.TLSListenerString,
  376. Handler: h,
  377. TLSConfig: s.tlsConfig,
  378. }
  379. if err := s.ListenAndServeTLS("", ""); err != nil {
  380. panic(err)
  381. }
  382. }()
  383. }
  384. s.logger.Printf("---------------------------")
  385. term := make(chan os.Signal, 1)
  386. signal.Notify(term, os.Interrupt)
  387. signal.Notify(term, syscall.SIGTERM)
  388. if listening {
  389. <-term
  390. } else {
  391. s.logger.Printf("No listener active.")
  392. }
  393. s.logger.Printf("Server stopped.")
  394. }