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.
 
 
 

414 lines
9.5 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. func HttpAuthCredentials(user string, pass string) OptionFn {
  147. return func(srvr *Server) {
  148. srvr.AuthUser = user
  149. srvr.AuthPass = pass
  150. }
  151. }
  152. type Server struct {
  153. AuthUser string
  154. AuthPass string
  155. tlsConfig *tls.Config
  156. profilerEnabled bool
  157. locks map[string]*sync.Mutex
  158. rateLimitRequests int
  159. storage Storage
  160. forceHTTPs bool
  161. VirusTotalKey string
  162. ClamAVDaemonHost string
  163. tempPath string
  164. webPath string
  165. ListenerString string
  166. TLSListenerString string
  167. ProfileListenerString string
  168. Certificate string
  169. LetsEncryptCache string
  170. }
  171. func New(options ...OptionFn) (*Server, error) {
  172. s := &Server{
  173. locks: map[string]*sync.Mutex{},
  174. }
  175. for _, optionFn := range options {
  176. optionFn(s)
  177. }
  178. return s, nil
  179. }
  180. func init() {
  181. rand.Seed(time.Now().UTC().UnixNano())
  182. }
  183. func (s *Server) Run() {
  184. if s.profilerEnabled {
  185. go func() {
  186. fmt.Println("Profiled listening at: :6060")
  187. http.ListenAndServe(":6060", nil)
  188. }()
  189. }
  190. r := mux.NewRouter()
  191. var fs http.FileSystem
  192. if s.webPath != "" {
  193. log.Println("Using static file path: ", s.webPath)
  194. fs = http.Dir(s.webPath)
  195. htmlTemplates, _ = htmlTemplates.ParseGlob(s.webPath + "*.html")
  196. textTemplates, _ = textTemplates.ParseGlob(s.webPath + "*.txt")
  197. } else {
  198. fs = &assetfs.AssetFS{
  199. Asset: web.Asset,
  200. AssetDir: web.AssetDir,
  201. AssetInfo: func(path string) (os.FileInfo, error) {
  202. return os.Stat(path)
  203. },
  204. Prefix: web.Prefix,
  205. }
  206. for _, path := range web.AssetNames() {
  207. bytes, err := web.Asset(path)
  208. if err != nil {
  209. log.Panicf("Unable to parse: path=%s, err=%s", path, err)
  210. }
  211. htmlTemplates.New(stripPrefix(path)).Parse(string(bytes))
  212. textTemplates.New(stripPrefix(path)).Parse(string(bytes))
  213. }
  214. }
  215. staticHandler := http.FileServer(fs)
  216. r.PathPrefix("/images/").Handler(staticHandler)
  217. r.PathPrefix("/styles/").Handler(staticHandler)
  218. r.PathPrefix("/scripts/").Handler(staticHandler)
  219. r.PathPrefix("/fonts/").Handler(staticHandler)
  220. r.PathPrefix("/ico/").Handler(staticHandler)
  221. r.PathPrefix("/favicon.ico").Handler(staticHandler)
  222. r.PathPrefix("/robots.txt").Handler(staticHandler)
  223. r.HandleFunc("/health.html", healthHandler).Methods("GET")
  224. r.HandleFunc("/", s.viewHandler).Methods("GET")
  225. r.HandleFunc("/({files:.*}).zip", s.zipHandler).Methods("GET")
  226. r.HandleFunc("/({files:.*}).tar", s.tarHandler).Methods("GET")
  227. r.HandleFunc("/({files:.*}).tar.gz", s.tarGzHandler).Methods("GET")
  228. r.HandleFunc("/{token}/{filename}", s.previewHandler).MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) (match bool) {
  229. match = false
  230. // The file will show a preview page when opening the link in browser directly or
  231. // from external link. If the referer url path and current path are the same it will be
  232. // downloaded.
  233. if !acceptsHTML(r.Header) {
  234. return false
  235. }
  236. match = (r.Referer() == "")
  237. u, err := url.Parse(r.Referer())
  238. if err != nil {
  239. log.Fatal(err)
  240. return
  241. }
  242. match = match || (u.Path != r.URL.Path)
  243. return
  244. }).Methods("GET")
  245. getHandlerFn := s.getHandler
  246. if s.rateLimitRequests > 0 {
  247. getHandlerFn = ratelimit.Request(ratelimit.IP).Rate(s.rateLimitRequests, 60*time.Second).LimitBy(memory.New())(http.HandlerFunc(getHandlerFn)).ServeHTTP
  248. }
  249. r.HandleFunc("/{token}/{filename}", getHandlerFn).Methods("GET")
  250. r.HandleFunc("/get/{token}/{filename}", getHandlerFn).Methods("GET")
  251. r.HandleFunc("/download/{token}/{filename}", getHandlerFn).Methods("GET")
  252. r.HandleFunc("/{filename}/virustotal", s.virusTotalHandler).Methods("PUT")
  253. r.HandleFunc("/{filename}/scan", s.scanHandler).Methods("PUT")
  254. r.HandleFunc("/put/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  255. r.HandleFunc("/upload/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  256. r.HandleFunc("/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  257. r.HandleFunc("/", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("POST")
  258. // r.HandleFunc("/{page}", viewHandler).Methods("GET")
  259. r.NotFoundHandler = http.HandlerFunc(s.notFoundHandler)
  260. mime.AddExtensionType(".md", "text/x-markdown")
  261. 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())
  262. log.Printf("---------------------------")
  263. h := handlers.PanicHandler(handlers.LogHandler(LoveHandler(s.RedirectHandler(r)), handlers.NewLogOptions(log.Printf, "_default_")), nil)
  264. srvr := &http.Server{
  265. Addr: s.ListenerString,
  266. Handler: h,
  267. }
  268. go func() {
  269. srvr.ListenAndServe()
  270. }()
  271. if s.TLSListenerString != "" {
  272. go func() {
  273. s := &http.Server{
  274. Addr: s.TLSListenerString,
  275. Handler: h,
  276. TLSConfig: s.tlsConfig,
  277. }
  278. if err := s.ListenAndServeTLS("", ""); err != nil {
  279. panic(err)
  280. }
  281. }()
  282. }
  283. /*
  284. cacheDir := "/var/cache/autocert"
  285. if s.LetsEncryptCache != "" {
  286. cacheDir = s.LetsEncryptCache
  287. }
  288. m := autocert.Manager{
  289. Prompt: autocert.AcceptTOS,
  290. Cache: autocert.DirCache(cacheDir),
  291. HostPolicy: func(_ context.Context, host string) error {
  292. if !strings.HasSuffix(host, "transfer.sh") {
  293. return errors.New("acme/autocert: host not configured")
  294. }
  295. return nil
  296. },
  297. }
  298. if s.TLSListenerString != "" {
  299. go func() {
  300. s := &http.Server{
  301. Addr: ":https",
  302. Handler: lh,
  303. TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
  304. }
  305. if err := s.ListenAndServeTLS("", ""); err != nil {
  306. panic(err)
  307. }
  308. }()
  309. if err := http.ListenAndServe(c.ListenerString, RedirectHandler()); err != nil {
  310. panic(err)
  311. }
  312. }
  313. */
  314. term := make(chan os.Signal, 1)
  315. signal.Notify(term, os.Interrupt)
  316. signal.Notify(term, syscall.SIGTERM)
  317. <-term
  318. log.Printf("Server stopped.")
  319. }