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.
 
 
 

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