Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

584 rindas
14 KiB

  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014 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 main
  21. import (
  22. // _ "transfer.sh/app/handlers"
  23. // _ "transfer.sh/app/utils"
  24. "archive/tar"
  25. "archive/zip"
  26. "bytes"
  27. "compress/gzip"
  28. "errors"
  29. "fmt"
  30. "github.com/dutchcoders/go-clamd"
  31. "github.com/gorilla/mux"
  32. "github.com/kennygrant/sanitize"
  33. "github.com/russross/blackfriday"
  34. html_template "html/template"
  35. "io"
  36. "io/ioutil"
  37. "log"
  38. "math/rand"
  39. "mime"
  40. "net/http"
  41. "os"
  42. "path/filepath"
  43. "strconv"
  44. "strings"
  45. text_template "text/template"
  46. "time"
  47. )
  48. func healthHandler(w http.ResponseWriter, r *http.Request) {
  49. fmt.Fprintf(w, "Approaching Neutral Zone, all systems normal and functioning.")
  50. }
  51. /* The preview handler will show a preview of the content for browsers (accept type text/html), and referer is not transfer.sh */
  52. func previewHandler(w http.ResponseWriter, r *http.Request) {
  53. vars := mux.Vars(r)
  54. token := vars["token"]
  55. filename := vars["filename"]
  56. contentType, contentLength, err := storage.Head(token, filename)
  57. if err != nil {
  58. http.Error(w, http.StatusText(404), 404)
  59. }
  60. var templatePath string
  61. var content html_template.HTML
  62. switch {
  63. case strings.HasPrefix(contentType, "image/"):
  64. templatePath = "static/download.image.html"
  65. case strings.HasPrefix(contentType, "text/x-markdown"):
  66. templatePath = "static/download.md.html"
  67. var reader io.ReadCloser
  68. if reader, _, _, err = storage.Get(token, filename); err != nil {
  69. http.Error(w, err.Error(), http.StatusInternalServerError)
  70. }
  71. var data []byte
  72. if data, err = ioutil.ReadAll(reader); err != nil {
  73. http.Error(w, err.Error(), http.StatusInternalServerError)
  74. }
  75. output := blackfriday.MarkdownCommon(data)
  76. content = html_template.HTML(output)
  77. case strings.HasPrefix(contentType, "text/"):
  78. templatePath = "static/download.md.html"
  79. default:
  80. templatePath = "static/download.html"
  81. }
  82. tmpl, err := html_template.ParseFiles(templatePath)
  83. if err != nil {
  84. http.Error(w, err.Error(), http.StatusInternalServerError)
  85. return
  86. }
  87. data := struct {
  88. ContentType string
  89. Content html_template.HTML
  90. Filename string
  91. Url string
  92. ContentLength uint64
  93. }{
  94. contentType,
  95. content,
  96. filename,
  97. r.URL.String(),
  98. contentLength,
  99. }
  100. if err := tmpl.Execute(w, data); err != nil {
  101. http.Error(w, err.Error(), http.StatusInternalServerError)
  102. return
  103. }
  104. }
  105. // this handler will output html or text, depending on the
  106. // support of the client (Accept header).
  107. func viewHandler(w http.ResponseWriter, r *http.Request) {
  108. // vars := mux.Vars(r)
  109. if acceptsHtml(r.Header) {
  110. tmpl, err := html_template.ParseFiles("static/index.html")
  111. if err != nil {
  112. http.Error(w, err.Error(), http.StatusInternalServerError)
  113. return
  114. }
  115. if err := tmpl.Execute(w, nil); err != nil {
  116. http.Error(w, err.Error(), http.StatusInternalServerError)
  117. return
  118. }
  119. } else {
  120. tmpl, err := text_template.ParseFiles("static/index.txt")
  121. if err != nil {
  122. http.Error(w, err.Error(), http.StatusInternalServerError)
  123. return
  124. }
  125. if err := tmpl.Execute(w, nil); err != nil {
  126. http.Error(w, err.Error(), http.StatusInternalServerError)
  127. return
  128. }
  129. }
  130. }
  131. func notFoundHandler(w http.ResponseWriter, r *http.Request) {
  132. http.Error(w, http.StatusText(404), 404)
  133. }
  134. func postHandler(w http.ResponseWriter, r *http.Request) {
  135. if err := r.ParseMultipartForm(_24K); nil != err {
  136. log.Println(err)
  137. http.Error(w, "Error occured copying to output stream", 500)
  138. return
  139. }
  140. token := Encode(10000000 + int64(rand.Intn(1000000000)))
  141. w.Header().Set("Content-Type", "text/plain")
  142. for _, fheaders := range r.MultipartForm.File {
  143. for _, fheader := range fheaders {
  144. filename := sanitize.Path(filepath.Base(fheader.Filename))
  145. contentType := fheader.Header.Get("Content-Type")
  146. if contentType == "" {
  147. contentType = mime.TypeByExtension(filepath.Ext(fheader.Filename))
  148. }
  149. var f io.Reader
  150. var err error
  151. if f, err = fheader.Open(); err != nil {
  152. log.Print(err)
  153. http.Error(w, err.Error(), 500)
  154. return
  155. }
  156. var b bytes.Buffer
  157. n, err := io.CopyN(&b, f, _24K+1)
  158. if err != nil && err != io.EOF {
  159. log.Print(err)
  160. http.Error(w, err.Error(), 500)
  161. return
  162. }
  163. var reader io.Reader
  164. if n > _24K {
  165. file, err := ioutil.TempFile(config.Temp, "transfer-")
  166. if err != nil {
  167. log.Fatal(err)
  168. }
  169. defer file.Close()
  170. n, err = io.Copy(file, io.MultiReader(&b, f))
  171. if err != nil {
  172. os.Remove(file.Name())
  173. log.Print(err)
  174. http.Error(w, err.Error(), 500)
  175. return
  176. }
  177. reader, err = os.Open(file.Name())
  178. } else {
  179. reader = bytes.NewReader(b.Bytes())
  180. }
  181. contentLength := n
  182. log.Printf("Uploading %s %s %d %s", token, filename, contentLength, contentType)
  183. if err = storage.Put(token, filename, reader, contentType, uint64(contentLength)); err != nil {
  184. log.Print(err)
  185. http.Error(w, err.Error(), 500)
  186. return
  187. }
  188. fmt.Fprintf(w, "https://%s/%s/%s\n", ipAddrFromRemoteAddr(r.Host), token, filename)
  189. }
  190. }
  191. }
  192. func scanHandler(w http.ResponseWriter, r *http.Request) {
  193. vars := mux.Vars(r)
  194. filename := sanitize.Path(filepath.Base(vars["filename"]))
  195. contentLength := r.ContentLength
  196. contentType := r.Header.Get("Content-Type")
  197. log.Printf("Scanning %s %d %s", filename, contentLength, contentType)
  198. var reader io.Reader
  199. reader = r.Body
  200. c := clamd.NewClamd(config.CLAMAV_DAEMON_HOST)
  201. response, err := c.ScanStream(reader)
  202. if err != nil {
  203. http.Error(w, err.Error(), 500)
  204. }
  205. var b string
  206. for s := range response {
  207. b += s
  208. if !strings.HasPrefix(s, "stream: ") {
  209. continue
  210. }
  211. w.Write([]byte(fmt.Sprintf("%v\n", s[8:])))
  212. }
  213. }
  214. func putHandler(w http.ResponseWriter, r *http.Request) {
  215. vars := mux.Vars(r)
  216. filename := sanitize.Path(filepath.Base(vars["filename"]))
  217. contentLength := r.ContentLength
  218. var reader io.Reader
  219. reader = r.Body
  220. if contentLength == -1 {
  221. // queue file to disk, because s3 needs content length
  222. var err error
  223. var f io.Reader
  224. f = reader
  225. var b bytes.Buffer
  226. n, err := io.CopyN(&b, f, _24K+1)
  227. if err != nil && err != io.EOF {
  228. log.Print(err)
  229. http.Error(w, err.Error(), 500)
  230. return
  231. }
  232. if n > _24K {
  233. file, err := ioutil.TempFile(config.Temp, "transfer-")
  234. if err != nil {
  235. log.Print(err)
  236. http.Error(w, err.Error(), 500)
  237. return
  238. }
  239. defer file.Close()
  240. n, err = io.Copy(file, io.MultiReader(&b, f))
  241. if err != nil {
  242. os.Remove(file.Name())
  243. log.Print(err)
  244. http.Error(w, err.Error(), 500)
  245. return
  246. }
  247. reader, err = os.Open(file.Name())
  248. } else {
  249. reader = bytes.NewReader(b.Bytes())
  250. }
  251. contentLength = n
  252. }
  253. contentType := r.Header.Get("Content-Type")
  254. if contentType == "" {
  255. contentType = mime.TypeByExtension(filepath.Ext(vars["filename"]))
  256. }
  257. token := Encode(10000000 + int64(rand.Intn(1000000000)))
  258. log.Printf("Uploading %s %d %s", token, filename, contentLength, contentType)
  259. var err error
  260. if err = storage.Put(token, filename, reader, contentType, uint64(contentLength)); err != nil {
  261. http.Error(w, errors.New("Could not save file").Error(), 500)
  262. return
  263. }
  264. // w.Statuscode = 200
  265. w.Header().Set("Content-Type", "text/plain")
  266. fmt.Fprintf(w, "https://%s/%s/%s\n", ipAddrFromRemoteAddr(r.Host), token, filename)
  267. }
  268. func zipHandler(w http.ResponseWriter, r *http.Request) {
  269. vars := mux.Vars(r)
  270. files := vars["files"]
  271. zipfilename := fmt.Sprintf("transfersh-%d.zip", uint16(time.Now().UnixNano()))
  272. w.Header().Set("Content-Type", "application/zip")
  273. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", zipfilename))
  274. w.Header().Set("Connection", "close")
  275. zw := zip.NewWriter(w)
  276. for _, key := range strings.Split(files, ",") {
  277. token := sanitize.Path(strings.Split(key, "/")[0])
  278. filename := sanitize.Path(strings.Split(key, "/")[1])
  279. reader, _, _, err := storage.Get(token, filename)
  280. if err != nil {
  281. if err.Error() == "The specified key does not exist." {
  282. http.Error(w, "File not found", 404)
  283. return
  284. } else {
  285. log.Printf("%s", err.Error())
  286. http.Error(w, "Could not retrieve file.", 500)
  287. return
  288. }
  289. }
  290. defer reader.Close()
  291. header := &zip.FileHeader{
  292. Name: strings.Split(key, "/")[1],
  293. Method: zip.Store,
  294. ModifiedTime: uint16(time.Now().UnixNano()),
  295. ModifiedDate: uint16(time.Now().UnixNano()),
  296. }
  297. fw, err := zw.CreateHeader(header)
  298. if err != nil {
  299. log.Printf("%s", err.Error())
  300. http.Error(w, "Internal server error.", 500)
  301. return
  302. }
  303. if _, err = io.Copy(fw, reader); err != nil {
  304. log.Printf("%s", err.Error())
  305. http.Error(w, "Internal server error.", 500)
  306. return
  307. }
  308. }
  309. if err := zw.Close(); err != nil {
  310. log.Printf("%s", err.Error())
  311. http.Error(w, "Internal server error.", 500)
  312. return
  313. }
  314. }
  315. func tarGzHandler(w http.ResponseWriter, r *http.Request) {
  316. vars := mux.Vars(r)
  317. files := vars["files"]
  318. tarfilename := fmt.Sprintf("transfersh-%d.tar.gz", uint16(time.Now().UnixNano()))
  319. w.Header().Set("Content-Type", "application/x-gzip")
  320. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
  321. w.Header().Set("Connection", "close")
  322. os := gzip.NewWriter(w)
  323. defer os.Close()
  324. zw := tar.NewWriter(os)
  325. defer zw.Close()
  326. for _, key := range strings.Split(files, ",") {
  327. token := strings.Split(key, "/")[0]
  328. filename := strings.Split(key, "/")[1]
  329. reader, _, contentLength, err := storage.Get(token, filename)
  330. if err != nil {
  331. if err.Error() == "The specified key does not exist." {
  332. http.Error(w, "File not found", 404)
  333. return
  334. } else {
  335. log.Printf("%s", err.Error())
  336. http.Error(w, "Could not retrieve file.", 500)
  337. return
  338. }
  339. }
  340. defer reader.Close()
  341. header := &tar.Header{
  342. Name: strings.Split(key, "/")[1],
  343. Size: int64(contentLength),
  344. }
  345. err = zw.WriteHeader(header)
  346. if err != nil {
  347. log.Printf("%s", err.Error())
  348. http.Error(w, "Internal server error.", 500)
  349. return
  350. }
  351. if _, err = io.Copy(zw, reader); err != nil {
  352. log.Printf("%s", err.Error())
  353. http.Error(w, "Internal server error.", 500)
  354. return
  355. }
  356. }
  357. }
  358. func tarHandler(w http.ResponseWriter, r *http.Request) {
  359. vars := mux.Vars(r)
  360. files := vars["files"]
  361. tarfilename := fmt.Sprintf("transfersh-%d.tar", uint16(time.Now().UnixNano()))
  362. w.Header().Set("Content-Type", "application/x-tar")
  363. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
  364. w.Header().Set("Connection", "close")
  365. zw := tar.NewWriter(w)
  366. defer zw.Close()
  367. for _, key := range strings.Split(files, ",") {
  368. token := strings.Split(key, "/")[0]
  369. filename := strings.Split(key, "/")[1]
  370. reader, _, contentLength, err := storage.Get(token, filename)
  371. if err != nil {
  372. if err.Error() == "The specified key does not exist." {
  373. http.Error(w, "File not found", 404)
  374. return
  375. } else {
  376. log.Printf("%s", err.Error())
  377. http.Error(w, "Could not retrieve file.", 500)
  378. return
  379. }
  380. }
  381. defer reader.Close()
  382. header := &tar.Header{
  383. Name: strings.Split(key, "/")[1],
  384. Size: int64(contentLength),
  385. }
  386. err = zw.WriteHeader(header)
  387. if err != nil {
  388. log.Printf("%s", err.Error())
  389. http.Error(w, "Internal server error.", 500)
  390. return
  391. }
  392. if _, err = io.Copy(zw, reader); err != nil {
  393. log.Printf("%s", err.Error())
  394. http.Error(w, "Internal server error.", 500)
  395. return
  396. }
  397. }
  398. }
  399. func getHandler(w http.ResponseWriter, r *http.Request) {
  400. vars := mux.Vars(r)
  401. token := vars["token"]
  402. filename := vars["filename"]
  403. reader, contentType, contentLength, err := storage.Get(token, filename)
  404. if err != nil {
  405. if err.Error() == "The specified key does not exist." {
  406. http.Error(w, "File not found", 404)
  407. return
  408. } else {
  409. log.Printf("%s", err.Error())
  410. http.Error(w, "Could not retrieve file.", 500)
  411. return
  412. }
  413. }
  414. defer reader.Close()
  415. w.Header().Set("Content-Type", contentType)
  416. w.Header().Set("Content-Length", strconv.FormatUint(contentLength, 10))
  417. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  418. w.Header().Set("Connection", "close")
  419. if _, err = io.Copy(w, reader); err != nil {
  420. http.Error(w, "Error occured copying to output stream", 500)
  421. return
  422. }
  423. }
  424. func RedirectHandler(h http.Handler) http.HandlerFunc {
  425. return func(w http.ResponseWriter, r *http.Request) {
  426. if r.URL.Path == "/health.html" {
  427. } else if ipAddrFromRemoteAddr(r.Host) == "127.0.0.1" {
  428. } else if ipAddrFromRemoteAddr(r.Host) == "transfersh.elasticbeanstalk.com" {
  429. } else if ipAddrFromRemoteAddr(r.Host) == "jxm5d6emw5rknovg.onion" {
  430. if r.Header.Get("X-Forwarded-Proto") != "https" && r.Method == "GET" {
  431. http.Redirect(w, r, "https://jxm5d6emw5rknovg.onion"+r.RequestURI, 301)
  432. return
  433. }
  434. } else if ipAddrFromRemoteAddr(r.Host) == "transfer.sh" {
  435. if r.Header.Get("X-Forwarded-Proto") != "https" && r.Method == "GET" {
  436. http.Redirect(w, r, "https://transfer.sh"+r.RequestURI, 301)
  437. return
  438. }
  439. } else if ipAddrFromRemoteAddr(r.Host) != "transfer.sh" {
  440. http.Redirect(w, r, "https://transfer.sh"+r.RequestURI, 301)
  441. return
  442. }
  443. h.ServeHTTP(w, r)
  444. }
  445. }
  446. // Create a log handler for every request it receives.
  447. func LoveHandler(h http.Handler) http.HandlerFunc {
  448. return func(w http.ResponseWriter, r *http.Request) {
  449. w.Header().Set("x-made-with", "<3 by DutchCoders")
  450. w.Header().Set("x-served-by", "Proudly served by DutchCoders")
  451. w.Header().Set("Server", "Transfer.sh HTTP Server 1.0")
  452. h.ServeHTTP(w, r)
  453. }
  454. }