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

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