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.
 
 
 

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