選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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