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.
 
 
 

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