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.
 
 
 

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