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.
 
 
 

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