hello.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. package hello
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "fmt"
  7. "html/template"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "os"
  12. "time"
  13. "github.com/cloudflare/cloudflared/logger"
  14. "github.com/gorilla/websocket"
  15. "github.com/cloudflare/cloudflared/tlsconfig"
  16. )
  17. type templateData struct {
  18. ServerName string
  19. Request *http.Request
  20. Body string
  21. }
  22. type OriginUpTime struct {
  23. StartTime time.Time `json:"startTime"`
  24. UpTime string `json:"uptime"`
  25. }
  26. const defaultServerName = "the Argo Tunnel test server"
  27. const indexTemplate = `
  28. <!DOCTYPE html>
  29. <html lang="en">
  30. <head>
  31. <meta charset="utf-8">
  32. <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  33. <title>
  34. Argo Tunnel Connection
  35. </title>
  36. <meta name="author" content="">
  37. <meta name="description" content="Argo Tunnel Connection">
  38. <meta name="viewport" content="width=device-width, initial-scale=1">
  39. <style>
  40. html{line-height:1.15;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}section{display:block}h1{font-size:2em;margin:.67em 0}a{background-color:transparent;-webkit-text-decoration-skip:objects}/* 1 */::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}/* 1 */a,body,dd,div,dl,dt,h1,h4,html,p,section{box-sizing:border-box}.bt{border-top-style:solid;border-top-width:1px}.bl{border-left-style:solid;border-left-width:1px}.b--orange{border-color:#f38020}.br1{border-radius:.125rem}.bw2{border-width:.25rem}.dib{display:inline-block}.sans-serif{font-family:open sans,-apple-system,BlinkMacSystemFont,avenir next,avenir,helvetica neue,helvetica,ubuntu,roboto,noto,segoe ui,arial,sans-serif}.overflow-x-auto{overflow-x:auto}.code{font-family:Consolas,monaco,monospace}.b{font-weight:700}.fw3{font-weight:300}.fw4{font-weight:400}.fw5{font-weight:500}.fw6{font-weight:600}.lh-copy{line-height:1.5}.link{text-decoration:none}.link,.link:active,.link:focus,.link:hover,.link:link,.link:visited{transition:color .15s ease-in}.link:focus{outline:1px dotted currentColor}.mw-100{max-width:100%}.mw4{max-width:8rem}.mw7{max-width:48rem}.bg-light-gray{background-color:#f7f7f7}.link-hover:hover{background-color:#1f679e}.white{color:#fff}.bg-white{background-color:#fff}.bg-blue{background-color:#408bc9}.pb2{padding-bottom:.5rem}.pb6{padding-bottom:8rem}.pt3{padding-top:1rem}.pt5{padding-top:4rem}.pv2{padding-top:.5rem;padding-bottom:.5rem}.ph3{padding-left:1rem;padding-right:1rem}.ph4{padding-left:2rem;padding-right:2rem}.ml0{margin-left:0}.mb1{margin-bottom:.25rem}.mb2{margin-bottom:.5rem}.mb3{margin-bottom:1rem}.mt5{margin-top:4rem}.ttu{text-transform:uppercase}.f4{font-size:1.25rem}.f5{font-size:1rem}.f6{font-size:.875rem}.f7{font-size:.75rem}.measure{max-width:30em}.center{margin-left:auto}.center{margin-right:auto}@media screen and (min-width:30em){.f2-ns{font-size:2.25rem}}@media screen and (min-width:30em) and (max-width:60em){.f5-m{font-size:1rem}}@media screen and (min-width:60em){.f4-l{font-size:1.25rem}}
  41. .st0{fill:#FFF}.st1{fill:#f48120}.st2{fill:#faad3f}.st3{fill:#404041}
  42. </style>
  43. </head>
  44. <body class="sans-serif black">
  45. <div class="bt bw2 b--orange bg-white pb6">
  46. <div class="mw7 center ph4 pt3">
  47. <svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 109 40.5" class="mw4">
  48. <path class="st0" d="M98.6 14.2L93 12.9l-1-.4-25.7.2v12.4l32.3.1z"/>
  49. <path class="st1" d="M88.1 24c.3-1 .2-2-.3-2.6-.5-.6-1.2-1-2.1-1.1l-17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 2.6-1.5 3.7-3.7 3.7-2.3-.1-3.7-1.2-3.7-3.7M45 29h3.1c2.8 0 4.5 1.6 4.5 3.9s-1.7 4-4.5 4h-3V29zm3.1 5.9c1.3 0 2.2-.7 2.2-2s-.9-2-2.2-2h-.9v4h.9zM55.7 29H62v1.9h-4.1v1.3h3.7V34h-3.7v2.9h-2.2zM65.1 29h2.2v6h3.8v1.9h-6zM76.8 28.9H79l3.4 8H80l-.6-1.4h-3.1l-.6 1.4h-2.3l3.4-8zm2 4.9l-.9-2.2-.9 2.2h1.8zM85.2 29h3.7c1.2 0 2 .3 2.6.9.5.5.7 1.1.7 1.8 0 1.2-.6 2-1.6 2.4l1.9 2.8H90l-1.6-2.4h-1v2.4h-2.2V29zm3.6 3.8c.7 0 1.2-.4 1.2-.9 0-.6-.5-.9-1.2-.9h-1.4v1.9h1.4zM95.3 29h6.4v1.8h-4.2V32h3.8v1.8h-3.8V35h4.3v1.9h-6.5zM10 33.9c-.3.7-1 1.2-1.8 1.2-1.2 0-2-1-2-2.1s.8-2.1 2-2.1c.9 0 1.6.6 1.9 1.3h2.3c-.4-1.9-2-3.3-4.2-3.3-2.4 0-4.3 1.8-4.3 4.1s1.8 4.1 4.2 4.1c2.1 0 3.7-1.4 4.2-3.2H10z"/>
  52. </svg>
  53. <h1 class="f4 f2-ns mt5 fw5">Congrats! You created a tunnel!</h1>
  54. <p class="f6 f5-m f4-l measure lh-copy fw3">
  55. Argo Tunnel exposes locally running applications to the internet by
  56. running an encrypted, virtual tunnel from your laptop or server to
  57. Cloudflare's edge network.
  58. </p>
  59. <p class="b f5 mt5 fw6">Ready for the next step?</p>
  60. <a
  61. class="fw6 link white bg-blue ph4 pv2 br1 dib f5 link-hover"
  62. style="border-bottom: 1px solid #1f679e"
  63. href="https://developers.cloudflare.com/argo-tunnel/">
  64. Get started here
  65. </a>
  66. <section>
  67. <h4 class="f6 fw4 pt5 mb2">Request</h4>
  68. <dl class="bl bw2 b--orange ph3 pt3 pb2 bg-light-gray f7 code overflow-x-auto mw-100">
  69. <dd class="ml0 mb3 f5">Method: {{.Request.Method}}</dd>
  70. <dd class="ml0 mb3 f5">Protocol: {{.Request.Proto}}</dd>
  71. <dd class="ml0 mb3 f5">Request URL: {{.Request.URL}}</dd>
  72. <dd class="ml0 mb3 f5">Transfer encoding: {{.Request.TransferEncoding}}</dd>
  73. <dd class="ml0 mb3 f5">Host: {{.Request.Host}}</dd>
  74. <dd class="ml0 mb3 f5">Remote address: {{.Request.RemoteAddr}}</dd>
  75. <dd class="ml0 mb3 f5">Request URI: {{.Request.RequestURI}}</dd>
  76. {{range $key, $value := .Request.Header}}
  77. <dd class="ml0 mb3 f5">Header: {{$key}}, Value: {{$value}}</dd>
  78. {{end}}
  79. <dd class="ml0 mb3 f5">Body: {{.Body}}</dd>
  80. </dl>
  81. </section>
  82. </div>
  83. </div>
  84. </body>
  85. </html>
  86. `
  87. func StartHelloWorldServer(logger logger.Service, listener net.Listener, shutdownC <-chan struct{}) error {
  88. logger.Infof("Starting Hello World server at %s", listener.Addr())
  89. serverName := defaultServerName
  90. if hostname, err := os.Hostname(); err == nil {
  91. serverName = hostname
  92. }
  93. upgrader := websocket.Upgrader{
  94. ReadBufferSize: 1024,
  95. WriteBufferSize: 1024,
  96. }
  97. muxer := http.NewServeMux()
  98. muxer.HandleFunc("/uptime", uptimeHandler(time.Now()))
  99. muxer.HandleFunc("/ws", websocketHandler(logger, upgrader))
  100. muxer.HandleFunc("/", rootHandler(serverName))
  101. httpServer := &http.Server{Addr: listener.Addr().String(), Handler: muxer}
  102. go func() {
  103. <-shutdownC
  104. httpServer.Close()
  105. }()
  106. err := httpServer.Serve(listener)
  107. return err
  108. }
  109. func CreateTLSListener(address string) (net.Listener, error) {
  110. certificate, err := tlsconfig.GetHelloCertificate()
  111. if err != nil {
  112. return nil, err
  113. }
  114. // If the port in address is empty, a port number is automatically chosen
  115. listener, err := tls.Listen(
  116. "tcp",
  117. address,
  118. &tls.Config{Certificates: []tls.Certificate{certificate}})
  119. return listener, err
  120. }
  121. func uptimeHandler(startTime time.Time) http.HandlerFunc {
  122. return func(w http.ResponseWriter, r *http.Request) {
  123. // Note that if autoupdate is enabled, the uptime is reset when a new client
  124. // release is available
  125. resp := &OriginUpTime{StartTime: startTime, UpTime: time.Now().Sub(startTime).String()}
  126. respJson, err := json.Marshal(resp)
  127. if err != nil {
  128. w.WriteHeader(http.StatusInternalServerError)
  129. } else {
  130. w.Header().Set("Content-Type", "application/json")
  131. w.Write(respJson)
  132. }
  133. }
  134. }
  135. // This handler will echo message
  136. func websocketHandler(logger logger.Service, upgrader websocket.Upgrader) http.HandlerFunc {
  137. return func(w http.ResponseWriter, r *http.Request) {
  138. conn, err := upgrader.Upgrade(w, r, nil)
  139. if err != nil {
  140. return
  141. }
  142. defer conn.Close()
  143. for {
  144. mt, message, err := conn.ReadMessage()
  145. if err != nil {
  146. logger.Errorf("websocket read message error: %s", err)
  147. break
  148. }
  149. if err := conn.WriteMessage(mt, message); err != nil {
  150. logger.Errorf("websocket write message error: %s", err)
  151. break
  152. }
  153. }
  154. }
  155. }
  156. func rootHandler(serverName string) http.HandlerFunc {
  157. responseTemplate := template.Must(template.New("index").Parse(indexTemplate))
  158. return func(w http.ResponseWriter, r *http.Request) {
  159. var buffer bytes.Buffer
  160. var body string
  161. rawBody, err := ioutil.ReadAll(r.Body)
  162. if err == nil {
  163. body = string(rawBody)
  164. } else {
  165. body = ""
  166. }
  167. err = responseTemplate.Execute(&buffer, &templateData{
  168. ServerName: serverName,
  169. Request: r,
  170. Body: body,
  171. })
  172. if err != nil {
  173. w.WriteHeader(http.StatusInternalServerError)
  174. fmt.Fprintf(w, "error: %v", err)
  175. } else {
  176. buffer.WriteTo(w)
  177. }
  178. }
  179. }