webService.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "crypto/subtle"
  22. "crypto/tls"
  23. "encoding/json"
  24. "fmt"
  25. "io/ioutil"
  26. golanglog "log"
  27. "net"
  28. "net/http"
  29. "sync"
  30. log "github.com/Psiphon-Inc/logrus"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  32. )
  33. type webServer struct {
  34. serveMux *http.ServeMux
  35. config *Config
  36. }
  37. func RunWebServer(config *Config, shutdownBroadcast <-chan struct{}) error {
  38. webServer := &webServer{
  39. config: config,
  40. }
  41. serveMux := http.NewServeMux()
  42. serveMux.HandleFunc("/handshake", webServer.handshakeHandler)
  43. serveMux.HandleFunc("/connected", webServer.connectedHandler)
  44. serveMux.HandleFunc("/status", webServer.statusHandler)
  45. certificate, err := tls.X509KeyPair(
  46. []byte(config.WebServerCertificate),
  47. []byte(config.WebServerPrivateKey))
  48. if err != nil {
  49. return psiphon.ContextError(err)
  50. }
  51. tlsConfig := &tls.Config{
  52. Certificates: []tls.Certificate{certificate},
  53. }
  54. // TODO: inherit global log config?
  55. logWriter := log.StandardLogger().Writer()
  56. defer logWriter.Close()
  57. server := &psiphon.HTTPSServer{
  58. http.Server{
  59. Handler: serveMux,
  60. TLSConfig: tlsConfig,
  61. ReadTimeout: WEB_SERVER_READ_TIMEOUT,
  62. WriteTimeout: WEB_SERVER_WRITE_TIMEOUT,
  63. ErrorLog: golanglog.New(logWriter, "", 0),
  64. },
  65. }
  66. listener, err := net.Listen(
  67. "tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, config.WebServerPort))
  68. if err != nil {
  69. return psiphon.ContextError(err)
  70. }
  71. log.Info("RunWebServer: starting server")
  72. err = nil
  73. errors := make(chan error)
  74. waitGroup := new(sync.WaitGroup)
  75. waitGroup.Add(1)
  76. go func() {
  77. defer waitGroup.Done()
  78. // Note: will be interrupted by listener.Close()
  79. err := server.ServeTLS(listener)
  80. // Can't check for the exact error that Close() will cause in Accept(),
  81. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  82. // explicit stop signal to stop gracefully.
  83. select {
  84. case <-shutdownBroadcast:
  85. default:
  86. if err != nil {
  87. select {
  88. case errors <- psiphon.ContextError(err):
  89. default:
  90. }
  91. }
  92. }
  93. log.Info("RunWebServer: server stopped")
  94. }()
  95. select {
  96. case <-shutdownBroadcast:
  97. case err = <-errors:
  98. }
  99. listener.Close()
  100. waitGroup.Wait()
  101. log.Info("RunWebServer: exiting")
  102. return err
  103. }
  104. func (webServer *webServer) checkWebServerSecret(r *http.Request) bool {
  105. return subtle.ConstantTimeCompare(
  106. []byte(r.URL.Query().Get("server_secret")),
  107. []byte(webServer.config.WebServerSecret)) == 1
  108. }
  109. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  110. if !webServer.checkWebServerSecret(r) {
  111. // TODO: log more details?
  112. log.Warning("handshakeHandler: checkWebServerSecret failed")
  113. // TODO: psi_web returns NotFound in this case
  114. w.WriteHeader(http.StatusForbidden)
  115. return
  116. }
  117. // TODO: validate; proper log
  118. log.Info("handshake: %+v", r.URL.Query())
  119. // TODO: necessary, in case client sends bogus request body?
  120. _, err := ioutil.ReadAll(r.Body)
  121. if err != nil {
  122. w.WriteHeader(http.StatusInternalServerError)
  123. return
  124. }
  125. // TODO: backwards compatibility cases (only sending the new JSON format response line)
  126. // TODO: share struct definition with psiphon/serverApi.go?
  127. // TODO: populate more response data
  128. var handshakeConfig struct {
  129. Homepages []string `json:"homepages"`
  130. UpgradeClientVersion string `json:"upgrade_client_version"`
  131. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  132. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  133. EncodedServerList []string `json:"encoded_server_list"`
  134. ClientRegion string `json:"client_region"`
  135. ServerTimestamp string `json:"server_timestamp"`
  136. }
  137. handshakeConfig.ServerTimestamp = psiphon.GetCurrentTimestamp()
  138. jsonPayload, err := json.Marshal(handshakeConfig)
  139. if err != nil {
  140. w.WriteHeader(http.StatusInternalServerError)
  141. return
  142. }
  143. responseBody := append([]byte("Config: "), jsonPayload...)
  144. w.WriteHeader(http.StatusOK)
  145. w.Write(responseBody)
  146. }
  147. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  148. if !webServer.checkWebServerSecret(r) {
  149. // TODO: log more details?
  150. log.Warning("handshakeHandler: checkWebServerSecret failed")
  151. // TODO: psi_web does NotFound in this case
  152. w.WriteHeader(http.StatusForbidden)
  153. return
  154. }
  155. // TODO: validate; proper log
  156. log.Info("connected: %+v", r.URL.Query())
  157. // TODO: necessary, in case client sends bogus request body?
  158. _, err := ioutil.ReadAll(r.Body)
  159. if err != nil {
  160. w.WriteHeader(http.StatusInternalServerError)
  161. return
  162. }
  163. var connectedResponse struct {
  164. ConnectedTimestamp string `json:"connected_timestamp"`
  165. }
  166. connectedResponse.ConnectedTimestamp =
  167. psiphon.TruncateTimestampToHour(psiphon.GetCurrentTimestamp())
  168. responseBody, err := json.Marshal(connectedResponse)
  169. if err != nil {
  170. w.WriteHeader(http.StatusInternalServerError)
  171. return
  172. }
  173. w.WriteHeader(http.StatusOK)
  174. w.Write(responseBody)
  175. }
  176. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  177. if !webServer.checkWebServerSecret(r) {
  178. // TODO: log more details?
  179. log.Warning("handshakeHandler: checkWebServerSecret failed")
  180. // TODO: psi_web does NotFound in this case
  181. w.WriteHeader(http.StatusForbidden)
  182. return
  183. }
  184. // TODO: validate; proper log
  185. log.Info("status: %+v", r.URL.Query())
  186. // TODO: use json.NewDecoder(r.Body)? But will that handle bogus extra data in request body?
  187. requestBody, err := ioutil.ReadAll(r.Body)
  188. if err != nil {
  189. w.WriteHeader(http.StatusInternalServerError)
  190. return
  191. }
  192. // TODO: parse payload; validate; proper logs
  193. log.Info("status payload: %s", string(requestBody))
  194. w.WriteHeader(http.StatusOK)
  195. }