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.
 
 
 

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