Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

475 строки
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. "context"
  23. "crypto/tls"
  24. "errors"
  25. "log"
  26. "math/rand"
  27. "mime"
  28. "net/http"
  29. _ "net/http/pprof"
  30. "net/url"
  31. "os"
  32. "os/signal"
  33. "path/filepath"
  34. "strings"
  35. "sync"
  36. "syscall"
  37. "time"
  38. "github.com/PuerkitoBio/ghost/handlers"
  39. "github.com/VojtechVitek/ratelimit"
  40. "github.com/VojtechVitek/ratelimit/memory"
  41. web "github.com/dutchcoders/transfer.sh-web"
  42. "github.com/dutchcoders/transfer.sh/server/storage"
  43. assetfs "github.com/elazarl/go-bindata-assetfs"
  44. "github.com/gorilla/mux"
  45. "golang.org/x/crypto/acme/autocert"
  46. )
  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 LifeTime(lifetime int) OptionFn {
  143. return func(srvr *Server) {
  144. srvr.lifetime = time.Hour * 24 * time.Duration(lifetime)
  145. }
  146. }
  147. func UseStorage(s storage.Storage) OptionFn {
  148. return func(srvr *Server) {
  149. srvr.storage = s
  150. }
  151. }
  152. func UseLetsEncrypt(hosts []string) OptionFn {
  153. return func(srvr *Server) {
  154. cacheDir := "./cache/"
  155. m := autocert.Manager{
  156. Prompt: autocert.AcceptTOS,
  157. Cache: autocert.DirCache(cacheDir),
  158. HostPolicy: func(_ context.Context, host string) error {
  159. found := false
  160. for _, h := range hosts {
  161. found = found || strings.HasSuffix(host, h)
  162. }
  163. if !found {
  164. return errors.New("acme/autocert: host not configured")
  165. }
  166. return nil
  167. },
  168. }
  169. srvr.tlsConfig = &tls.Config{
  170. GetCertificate: m.GetCertificate,
  171. }
  172. }
  173. }
  174. func TLSConfig(cert, pk string) OptionFn {
  175. certificate, err := tls.LoadX509KeyPair(cert, pk)
  176. return func(srvr *Server) {
  177. srvr.tlsConfig = &tls.Config{
  178. GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  179. return &certificate, err
  180. },
  181. }
  182. }
  183. }
  184. func HttpAuthCredentials(user string, pass string) OptionFn {
  185. return func(srvr *Server) {
  186. srvr.AuthUser = user
  187. srvr.AuthPass = pass
  188. }
  189. }
  190. func FilterOptions(options IPFilterOptions) OptionFn {
  191. for i, allowedIP := range options.AllowedIPs {
  192. options.AllowedIPs[i] = strings.TrimSpace(allowedIP)
  193. }
  194. for i, blockedIP := range options.BlockedIPs {
  195. options.BlockedIPs[i] = strings.TrimSpace(blockedIP)
  196. }
  197. return func(srvr *Server) {
  198. srvr.ipFilterOptions = &options
  199. }
  200. }
  201. type Server struct {
  202. AuthUser string
  203. AuthPass string
  204. logger *log.Logger
  205. tlsConfig *tls.Config
  206. profilerEnabled bool
  207. locks map[string]*sync.Mutex
  208. rateLimitRequests int
  209. storage storage.Storage
  210. lifetime time.Duration
  211. forceHTTPs bool
  212. ipFilterOptions *IPFilterOptions
  213. VirusTotalKey string
  214. ClamAVDaemonHost string
  215. tempPath string
  216. webPath string
  217. proxyPath string
  218. gaKey string
  219. userVoiceKey string
  220. TLSListenerOnly bool
  221. ListenerString string
  222. TLSListenerString string
  223. ProfileListenerString string
  224. Certificate string
  225. LetsEncryptCache string
  226. }
  227. func New(options ...OptionFn) (*Server, error) {
  228. s := &Server{
  229. locks: map[string]*sync.Mutex{},
  230. }
  231. for _, optionFn := range options {
  232. optionFn(s)
  233. }
  234. return s, nil
  235. }
  236. func init() {
  237. rand.Seed(time.Now().UTC().UnixNano())
  238. }
  239. func (s *Server) Run() {
  240. listening := false
  241. if s.profilerEnabled {
  242. listening = true
  243. go func() {
  244. s.logger.Println("Profiled listening at: :6060")
  245. _ = http.ListenAndServe(":6060", nil)
  246. }()
  247. }
  248. r := mux.NewRouter()
  249. var fs http.FileSystem
  250. if s.webPath != "" {
  251. s.logger.Println("Using static file path: ", s.webPath)
  252. fs = http.Dir(s.webPath)
  253. htmlTemplates, _ = htmlTemplates.ParseGlob(s.webPath + "*.html")
  254. textTemplates, _ = textTemplates.ParseGlob(s.webPath + "*.txt")
  255. } else {
  256. fs = &assetfs.AssetFS{
  257. Asset: web.Asset,
  258. AssetDir: web.AssetDir,
  259. AssetInfo: func(path string) (os.FileInfo, error) {
  260. return os.Stat(path)
  261. },
  262. Prefix: web.Prefix,
  263. }
  264. for _, path := range web.AssetNames() {
  265. bytes, err := web.Asset(path)
  266. if err != nil {
  267. s.logger.Panicf("Unable to parse: path=%s, err=%s", path, err)
  268. }
  269. _, _ = htmlTemplates.New(stripPrefix(path)).Parse(string(bytes))
  270. _, _ = textTemplates.New(stripPrefix(path)).Parse(string(bytes))
  271. }
  272. }
  273. staticHandler := http.FileServer(fs)
  274. r.PathPrefix("/images/").Handler(staticHandler).Methods("GET")
  275. r.PathPrefix("/styles/").Handler(staticHandler).Methods("GET")
  276. r.PathPrefix("/scripts/").Handler(staticHandler).Methods("GET")
  277. r.PathPrefix("/fonts/").Handler(staticHandler).Methods("GET")
  278. r.PathPrefix("/ico/").Handler(staticHandler).Methods("GET")
  279. r.HandleFunc("/favicon.ico", staticHandler.ServeHTTP).Methods("GET")
  280. r.HandleFunc("/robots.txt", staticHandler.ServeHTTP).Methods("GET")
  281. r.HandleFunc("/{filename:(?:favicon\\.ico|robots\\.txt|health\\.html)}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  282. r.HandleFunc("/health.html", s.healthHandler).Methods("GET")
  283. r.HandleFunc("/", s.viewHandler).Methods("GET")
  284. r.HandleFunc("/({files:.*}).zip", s.zipHandler).Methods("GET")
  285. r.HandleFunc("/({files:.*}).tar", s.tarHandler).Methods("GET")
  286. r.HandleFunc("/({files:.*}).tar.gz", s.tarGzHandler).Methods("GET")
  287. r.HandleFunc("/{token}/{filename}", s.headHandler).Methods("HEAD")
  288. r.HandleFunc("/{action:(?:download|get|inline)}/{token}/{filename}", s.headHandler).Methods("HEAD")
  289. r.HandleFunc("/{token}/{filename}", s.previewHandler).MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) (match bool) {
  290. match = false
  291. // The file will show a preview page when opening the link in browser directly or
  292. // from external link. If the referer url path and current path are the same it will be
  293. // downloaded.
  294. if !acceptsHTML(r.Header) {
  295. return false
  296. }
  297. match = r.Referer() == ""
  298. u, err := url.Parse(r.Referer())
  299. if err != nil {
  300. s.logger.Fatal(err)
  301. return
  302. }
  303. match = match || (u.Path != r.URL.Path)
  304. return
  305. }).Methods("GET")
  306. getHandlerFn := s.getHandler
  307. if s.rateLimitRequests > 0 {
  308. getHandlerFn = ratelimit.Request(ratelimit.IP).Rate(s.rateLimitRequests, 60*time.Second).LimitBy(memory.New())(http.HandlerFunc(getHandlerFn)).ServeHTTP
  309. }
  310. r.HandleFunc("/{token}/{filename}", getHandlerFn).Methods("GET")
  311. r.HandleFunc("/{action:(?:download|get|inline)}/{token}/{filename}", getHandlerFn).Methods("GET")
  312. r.HandleFunc("/{filename}/virustotal", s.virusTotalHandler).Methods("PUT")
  313. r.HandleFunc("/{filename}/scan", s.scanHandler).Methods("PUT")
  314. r.HandleFunc("/put/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  315. r.HandleFunc("/upload/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  316. r.HandleFunc("/{filename}", s.BasicAuthHandler(http.HandlerFunc(s.putHandler))).Methods("PUT")
  317. r.HandleFunc("/", s.BasicAuthHandler(http.HandlerFunc(s.postHandler))).Methods("POST")
  318. // r.HandleFunc("/{page}", viewHandler).Methods("GET")
  319. r.HandleFunc("/{token}/{filename}/{deletionToken}", s.deleteHandler).Methods("DELETE")
  320. r.NotFoundHandler = http.HandlerFunc(s.notFoundHandler)
  321. _ = mime.AddExtensionType(".md", "text/x-markdown")
  322. s.logger.Printf("Transfer.sh server started.\nusing temp folder: %s\nusing storage provider: %s", s.tempPath, s.storage.Type())
  323. h := handlers.PanicHandler(
  324. IPFilterHandler(
  325. handlers.LogHandler(
  326. LoveHandler(
  327. s.RedirectHandler(r)),
  328. handlers.NewLogOptions(s.logger.Printf, "_default_"),
  329. ),
  330. s.ipFilterOptions,
  331. ),
  332. nil,
  333. )
  334. if !s.TLSListenerOnly {
  335. srvr := &http.Server{
  336. Addr: s.ListenerString,
  337. Handler: h,
  338. }
  339. listening = true
  340. s.logger.Printf("listening on port: %v\n", s.ListenerString)
  341. go func() {
  342. _ = srvr.ListenAndServe()
  343. }()
  344. }
  345. if s.TLSListenerString != "" {
  346. listening = true
  347. s.logger.Printf("listening on port: %v\n", s.TLSListenerString)
  348. go func() {
  349. s := &http.Server{
  350. Addr: s.TLSListenerString,
  351. Handler: h,
  352. TLSConfig: s.tlsConfig,
  353. }
  354. if err := s.ListenAndServeTLS("", ""); err != nil {
  355. panic(err)
  356. }
  357. }()
  358. }
  359. s.logger.Printf("---------------------------")
  360. term := make(chan os.Signal, 1)
  361. signal.Notify(term, os.Interrupt)
  362. signal.Notify(term, syscall.SIGTERM)
  363. if listening {
  364. <-term
  365. } else {
  366. s.logger.Printf("No listener active.")
  367. }
  368. s.logger.Printf("Server stopped.")
  369. }