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.
 
 
 

240 lines
6.4 KiB

  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014 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 main
  21. import (
  22. "flag"
  23. "fmt"
  24. "log"
  25. "math/rand"
  26. "mime"
  27. "net/http"
  28. "net/url"
  29. "os"
  30. "os/signal"
  31. "runtime"
  32. "syscall"
  33. "time"
  34. "github.com/PuerkitoBio/ghost/handlers"
  35. "github.com/gorilla/mux"
  36. _ "net/http/pprof"
  37. web "github.com/dutchcoders/transfer.sh-web"
  38. assetfs "github.com/elazarl/go-bindata-assetfs"
  39. )
  40. const SERVER_INFO = "transfer.sh"
  41. // parse request with maximum memory of _24Kilobits
  42. const _24K = (1 << 20) * 24
  43. var storage Storage
  44. type Server struct {
  45. AWS_ACCESS_KEY string
  46. AWS_SECRET_KEY string
  47. BUCKET string
  48. VIRUSTOTAL_KEY string
  49. CLAMAV_DAEMON_HOST string "/tmp/clamd.socket"
  50. Temp string
  51. Path string
  52. }
  53. func New() *Server {
  54. s := &Server{}
  55. s.AWS_ACCESS_KEY = os.Getenv("AWS_ACCESS_KEY_ID")
  56. s.AWS_SECRET_KEY = os.Getenv("AWS_SECRET_KEY")
  57. s.BUCKET = os.Getenv("BUCKET")
  58. s.VIRUSTOTAL_KEY = os.Getenv("VIRUSTOTAL_KEY")
  59. if os.Getenv("CLAMAV_DAEMON_HOST") != "" {
  60. s.CLAMAV_DAEMON_HOST = os.Getenv("CLAMAV_DAEMON_HOST")
  61. }
  62. s.Temp = os.TempDir()
  63. s.Path = "" // "../transfer.sh-web/dist/"
  64. return s
  65. }
  66. func (s *Server) Run() {
  67. rand.Seed(time.Now().UTC().UnixNano())
  68. nCPU := runtime.NumCPU()
  69. runtime.GOMAXPROCS(nCPU)
  70. fmt.Println("Number of CPUs: ", nCPU)
  71. go func() {
  72. fmt.Println("Profiled listening at: :6060")
  73. http.ListenAndServe(":6060", nil)
  74. }()
  75. r := mux.NewRouter()
  76. var fs http.FileSystem
  77. if config.Path != "" {
  78. log.Println("Using static file path: ", config.Path)
  79. fs = http.Dir(config.Path)
  80. html_templates, _ = html_templates.ParseGlob(config.Path + "*.html")
  81. text_templates, _ = text_templates.ParseGlob(config.Path + "*.txt")
  82. } else {
  83. fs = &assetfs.AssetFS{
  84. Asset: web.Asset,
  85. AssetDir: web.AssetDir,
  86. AssetInfo: func(path string) (os.FileInfo, error) {
  87. return os.Stat(path)
  88. },
  89. Prefix: web.Prefix,
  90. }
  91. for _, path := range web.AssetNames() {
  92. bytes, err := web.Asset(path)
  93. if err != nil {
  94. log.Panicf("Unable to parse: path=%s, err=%s", path, err)
  95. }
  96. html_templates.New(stripPrefix(path)).Parse(string(bytes))
  97. text_templates.New(stripPrefix(path)).Parse(string(bytes))
  98. }
  99. }
  100. staticHandler := http.FileServer(fs)
  101. r.PathPrefix("/images/").Handler(staticHandler)
  102. r.PathPrefix("/styles/").Handler(staticHandler)
  103. r.PathPrefix("/scripts/").Handler(staticHandler)
  104. r.PathPrefix("/fonts/").Handler(staticHandler)
  105. r.PathPrefix("/ico/").Handler(staticHandler)
  106. r.PathPrefix("/favicon.ico").Handler(staticHandler)
  107. r.PathPrefix("/robots.txt").Handler(staticHandler)
  108. r.HandleFunc("/({files:.*}).zip", zipHandler).Methods("GET")
  109. r.HandleFunc("/({files:.*}).tar", tarHandler).Methods("GET")
  110. r.HandleFunc("/({files:.*}).tar.gz", tarGzHandler).Methods("GET")
  111. r.HandleFunc("/download/{token}/{filename}", getHandler).Methods("GET")
  112. r.HandleFunc("/{token}/{filename}", previewHandler).MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) (match bool) {
  113. match = false
  114. // The file will show a preview page when opening the link in browser directly or
  115. // from external link. If the referer url path and current path are the same it will be
  116. // downloaded.
  117. if !acceptsHtml(r.Header) {
  118. return false
  119. }
  120. match = (r.Referer() == "")
  121. u, err := url.Parse(r.Referer())
  122. if err != nil {
  123. log.Fatal(err)
  124. return
  125. }
  126. match = match || (u.Path != r.URL.Path)
  127. return
  128. }).Methods("GET")
  129. r.HandleFunc("/{token}/{filename}", getHandler).Methods("GET")
  130. r.HandleFunc("/get/{token}/{filename}", getHandler).Methods("GET")
  131. r.HandleFunc("/{filename}/virustotal", virusTotalHandler).Methods("PUT")
  132. r.HandleFunc("/{filename}/scan", scanHandler).Methods("PUT")
  133. r.HandleFunc("/put/{filename}", putHandler).Methods("PUT")
  134. r.HandleFunc("/upload/{filename}", putHandler).Methods("PUT")
  135. r.HandleFunc("/{filename}", putHandler).Methods("PUT")
  136. r.HandleFunc("/health.html", healthHandler).Methods("GET")
  137. r.HandleFunc("/", postHandler).Methods("POST")
  138. // r.HandleFunc("/{page}", viewHandler).Methods("GET")
  139. r.HandleFunc("/", viewHandler).Methods("GET")
  140. r.NotFoundHandler = http.HandlerFunc(notFoundHandler)
  141. port := flag.String("port", "8080", "port number, default: 8080")
  142. temp := flag.String("temp", config.Temp, "")
  143. basedir := flag.String("basedir", "", "")
  144. logpath := flag.String("log", "", "")
  145. provider := flag.String("provider", "s3", "")
  146. flag.Parse()
  147. if *logpath != "" {
  148. f, err := os.OpenFile(*logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  149. if err != nil {
  150. log.Fatalf("error opening file: %v", err)
  151. }
  152. defer f.Close()
  153. log.SetOutput(f)
  154. }
  155. config.Temp = *temp
  156. var err error
  157. switch *provider {
  158. case "s3":
  159. storage, err = NewS3Storage()
  160. case "local":
  161. if *basedir == "" {
  162. log.Panic("basedir not set")
  163. }
  164. storage, err = NewLocalStorage(*basedir)
  165. }
  166. if err != nil {
  167. log.Panic("Error while creating storage.", err)
  168. }
  169. mime.AddExtensionType(".md", "text/x-markdown")
  170. log.Printf("Transfer.sh server started. :\nlistening on port: %v\nusing temp folder: %s\nusing storage provider: %s", *port, config.Temp, *provider)
  171. log.Printf("---------------------------")
  172. s := &http.Server{
  173. Addr: fmt.Sprintf(":%s", *port),
  174. Handler: handlers.PanicHandler(LoveHandler(RedirectHandler(handlers.LogHandler(r, handlers.NewLogOptions(log.Printf, "_default_")))), nil),
  175. }
  176. go func() {
  177. s.ListenAndServe()
  178. }()
  179. term := make(chan os.Signal, 1)
  180. signal.Notify(term, os.Interrupt)
  181. signal.Notify(term, syscall.SIGTERM)
  182. <-term
  183. log.Printf("Server stopped.")
  184. }