hello.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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/gorilla/websocket"
  14. "github.com/rs/zerolog"
  15. "github.com/cloudflare/cloudflared/tlsconfig"
  16. )
  17. const (
  18. UptimeRoute = "/uptime"
  19. WSRoute = "/ws"
  20. SSERoute = "/sse"
  21. HealthRoute = "/_health"
  22. defaultSSEFreq = time.Second * 10
  23. )
  24. type templateData struct {
  25. ServerName string
  26. Request *http.Request
  27. Body string
  28. }
  29. type OriginUpTime struct {
  30. StartTime time.Time `json:"startTime"`
  31. UpTime string `json:"uptime"`
  32. }
  33. const defaultServerName = "the Argo Tunnel test server"
  34. const indexTemplate = `
  35. <!DOCTYPE html>
  36. <html lang="en">
  37. <head>
  38. <meta charset="utf-8">
  39. <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  40. <title>
  41. Argo Tunnel Connection
  42. </title>
  43. <meta name="author" content="">
  44. <meta name="description" content="Argo Tunnel Connection">
  45. <meta name="viewport" content="width=device-width, initial-scale=1">
  46. <style>
  47. 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}}
  48. .st0{fill:#FFF}.st1{fill:#f48120}.st2{fill:#faad3f}.st3{fill:#404041}
  49. </style>
  50. </head>
  51. <body class="sans-serif black">
  52. <div class="bt bw2 b--orange bg-white pb6">
  53. <div class="mw7 center ph4 pt3">
  54. <svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 109 40.5" class="mw4">
  55. <path class="st0" d="M98.6 14.2L93 12.9l-1-.4-25.7.2v12.4l32.3.1z"/>
  56. <path class="st1" d="M88.1 24c.3-1 .2-2-.3-2.6-.5-.6-1.2-1-2.1-1.1l-17.4-.2c-.1 0-.2-.1-.3-.1-.1-.1-.1-.2 0-.3.1-.2.2-.3.4-.3l17.5-.2c2.1-.1 4.3-1.8 5.1-3.8l1-2.6c0-.1.1-.2 0-.3-1.1-5.1-5.7-8.9-11.1-8.9-5 0-9.3 3.2-10.8 7.7-1-.7-2.2-1.1-3.6-1-2.4.2-4.3 2.2-4.6 4.6-.1.6 0 1.2.1 1.8-3.9.1-7.1 3.3-7.1 7.3 0 .4 0 .7.1 1.1 0 .2.2.3.3.3h32.1c.2 0 .4-.1.4-.3l.3-1.1z"/>
  57. <path class="st2" d="M93.6 12.8h-.5c-.1 0-.2.1-.3.2l-.7 2.4c-.3 1-.2 2 .3 2.6.5.6 1.2 1 2.1 1.1l3.7.2c.1 0 .2.1.3.1.1.1.1.2 0 .3-.1.2-.2.3-.4.3l-3.8.2c-2.1.1-4.3 1.8-5.1 3.8l-.2.9c-.1.1 0 .3.2.3h13.2c.2 0 .3-.1.3-.3.2-.8.4-1.7.4-2.6 0-5.2-4.3-9.5-9.5-9.5"/>
  58. <path class="st3" d="M104.4 30.8c-.5 0-.9-.4-.9-.9s.4-.9.9-.9.9.4.9.9-.4.9-.9.9m0-1.6c-.4 0-.7.3-.7.7 0 .4.3.7.7.7.4 0 .7-.3.7-.7 0-.4-.3-.7-.7-.7m.4 1.2h-.2l-.2-.3h-.2v.3h-.2v-.9h.5c.2 0 .3.1.3.3 0 .1-.1.2-.2.3l.2.3zm-.3-.5c.1 0 .1 0 .1-.1s-.1-.1-.1-.1h-.3v.3h.3zM14.8 29H17v6h3.8v1.9h-6zM23.1 32.9c0-2.3 1.8-4.1 4.3-4.1s4.2 1.8 4.2 4.1-1.8 4.1-4.3 4.1c-2.4 0-4.2-1.8-4.2-4.1m6.3 0c0-1.2-.8-2.2-2-2.2s-2 1-2 2.1.8 2.1 2 2.1c1.2.2 2-.8 2-2M34.3 33.4V29h2.2v4.4c0 1.1.6 1.7 1.5 1.7s1.5-.5 1.5-1.6V29h2.2v4.4c0 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"/>
  59. </svg>
  60. <h1 class="f4 f2-ns mt5 fw5">Congrats! You created a tunnel!</h1>
  61. <p class="f6 f5-m f4-l measure lh-copy fw3">
  62. Argo Tunnel exposes locally running applications to the internet by
  63. running an encrypted, virtual tunnel from your laptop or server to
  64. Cloudflare's edge network.
  65. </p>
  66. <p class="b f5 mt5 fw6">Ready for the next step?</p>
  67. <a
  68. class="fw6 link white bg-blue ph4 pv2 br1 dib f5 link-hover"
  69. style="border-bottom: 1px solid #1f679e"
  70. href="https://developers.cloudflare.com/argo-tunnel/">
  71. Get started here
  72. </a>
  73. <section>
  74. <h4 class="f6 fw4 pt5 mb2">Request</h4>
  75. <dl class="bl bw2 b--orange ph3 pt3 pb2 bg-light-gray f7 code overflow-x-auto mw-100">
  76. <dd class="ml0 mb3 f5">Method: {{.Request.Method}}</dd>
  77. <dd class="ml0 mb3 f5">Protocol: {{.Request.Proto}}</dd>
  78. <dd class="ml0 mb3 f5">Request URL: {{.Request.URL}}</dd>
  79. <dd class="ml0 mb3 f5">Transfer encoding: {{.Request.TransferEncoding}}</dd>
  80. <dd class="ml0 mb3 f5">Host: {{.Request.Host}}</dd>
  81. <dd class="ml0 mb3 f5">Remote address: {{.Request.RemoteAddr}}</dd>
  82. <dd class="ml0 mb3 f5">Request URI: {{.Request.RequestURI}}</dd>
  83. {{range $key, $value := .Request.Header}}
  84. <dd class="ml0 mb3 f5">Header: {{$key}}, Value: {{$value}}</dd>
  85. {{end}}
  86. <dd class="ml0 mb3 f5">Body: {{.Body}}</dd>
  87. </dl>
  88. </section>
  89. </div>
  90. </div>
  91. </body>
  92. </html>
  93. `
  94. func StartHelloWorldServer(log *zerolog.Logger, listener net.Listener, shutdownC <-chan struct{}) error {
  95. log.Info().Msgf("Starting Hello World server at %s", listener.Addr())
  96. serverName := defaultServerName
  97. if hostname, err := os.Hostname(); err == nil {
  98. serverName = hostname
  99. }
  100. upgrader := websocket.Upgrader{
  101. ReadBufferSize: 1024,
  102. WriteBufferSize: 1024,
  103. }
  104. muxer := http.NewServeMux()
  105. muxer.HandleFunc(UptimeRoute, uptimeHandler(time.Now()))
  106. muxer.HandleFunc(WSRoute, websocketHandler(log, upgrader))
  107. muxer.HandleFunc(SSERoute, sseHandler(log))
  108. muxer.HandleFunc(HealthRoute, healthHandler())
  109. muxer.HandleFunc("/", rootHandler(serverName))
  110. httpServer := &http.Server{Addr: listener.Addr().String(), Handler: muxer}
  111. go func() {
  112. <-shutdownC
  113. _ = httpServer.Close()
  114. }()
  115. err := httpServer.Serve(listener)
  116. return err
  117. }
  118. func CreateTLSListener(address string) (net.Listener, error) {
  119. certificate, err := tlsconfig.GetHelloCertificate()
  120. if err != nil {
  121. return nil, err
  122. }
  123. // If the port in address is empty, a port number is automatically chosen
  124. listener, err := tls.Listen(
  125. "tcp",
  126. address,
  127. &tls.Config{Certificates: []tls.Certificate{certificate}})
  128. return listener, err
  129. }
  130. func uptimeHandler(startTime time.Time) http.HandlerFunc {
  131. return func(w http.ResponseWriter, r *http.Request) {
  132. // Note that if autoupdate is enabled, the uptime is reset when a new client
  133. // release is available
  134. resp := &OriginUpTime{StartTime: startTime, UpTime: time.Now().Sub(startTime).String()}
  135. respJson, err := json.Marshal(resp)
  136. if err != nil {
  137. w.WriteHeader(http.StatusInternalServerError)
  138. } else {
  139. w.Header().Set("Content-Type", "application/json")
  140. _, _ = w.Write(respJson)
  141. }
  142. }
  143. }
  144. // This handler will echo message
  145. func websocketHandler(log *zerolog.Logger, upgrader websocket.Upgrader) http.HandlerFunc {
  146. return func(w http.ResponseWriter, r *http.Request) {
  147. // This addresses the issue of r.Host includes port but origin header doesn't
  148. host, _, err := net.SplitHostPort(r.Host)
  149. if err == nil {
  150. r.Host = host
  151. }
  152. conn, err := upgrader.Upgrade(w, r, nil)
  153. if err != nil {
  154. log.Err(err).Msg("failed to upgrade to websocket connection")
  155. return
  156. }
  157. defer conn.Close()
  158. for {
  159. mt, message, err := conn.ReadMessage()
  160. if err != nil {
  161. log.Err(err).Msg("websocket read message error")
  162. break
  163. }
  164. if err := conn.WriteMessage(mt, message); err != nil {
  165. log.Err(err).Msg("websocket write message error")
  166. break
  167. }
  168. }
  169. }
  170. }
  171. func sseHandler(log *zerolog.Logger) http.HandlerFunc {
  172. return func(w http.ResponseWriter, r *http.Request) {
  173. w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
  174. flusher, ok := w.(http.Flusher)
  175. if !ok {
  176. w.WriteHeader(http.StatusInternalServerError)
  177. log.Error().Msgf("Can't support SSE. ResponseWriter %T doesn't implement http.Flusher interface", w)
  178. return
  179. }
  180. freq := defaultSSEFreq
  181. if requestedFreq := r.URL.Query()["freq"]; len(requestedFreq) > 0 {
  182. parsedFreq, err := time.ParseDuration(requestedFreq[0])
  183. if err == nil {
  184. freq = parsedFreq
  185. }
  186. }
  187. log.Info().Msgf("Server Sent Events every %s", freq)
  188. ticker := time.NewTicker(freq)
  189. counter := 0
  190. for {
  191. select {
  192. case <-r.Context().Done():
  193. return
  194. case <-ticker.C:
  195. }
  196. _, err := fmt.Fprintf(w, "%d\n\n", counter)
  197. if err != nil {
  198. return
  199. }
  200. flusher.Flush()
  201. counter++
  202. }
  203. }
  204. }
  205. func healthHandler() http.HandlerFunc {
  206. return func(w http.ResponseWriter, r *http.Request) {
  207. w.Write([]byte("ok"))
  208. }
  209. }
  210. func rootHandler(serverName string) http.HandlerFunc {
  211. responseTemplate := template.Must(template.New("index").Parse(indexTemplate))
  212. return func(w http.ResponseWriter, r *http.Request) {
  213. var buffer bytes.Buffer
  214. var body string
  215. rawBody, err := ioutil.ReadAll(r.Body)
  216. if err == nil {
  217. body = string(rawBody)
  218. } else {
  219. body = ""
  220. }
  221. err = responseTemplate.Execute(&buffer, &templateData{
  222. ServerName: serverName,
  223. Request: r,
  224. Body: body,
  225. })
  226. if err != nil {
  227. w.WriteHeader(http.StatusInternalServerError)
  228. _, _ = fmt.Fprintf(w, "error: %v", err)
  229. } else {
  230. _, _ = buffer.WriteTo(w)
  231. }
  232. }
  233. }