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.
 
 
 

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