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.
 
 
 

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