webService.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  31. )
  32. type webServer struct {
  33. serveMux *http.ServeMux
  34. config *Config
  35. }
  36. func RunWebServer(config *Config, shutdownBroadcast <-chan struct{}) error {
  37. webServer := &webServer{
  38. config: config,
  39. }
  40. serveMux := http.NewServeMux()
  41. serveMux.HandleFunc("/handshake", webServer.handshakeHandler)
  42. serveMux.HandleFunc("/connected", webServer.connectedHandler)
  43. serveMux.HandleFunc("/status", webServer.statusHandler)
  44. certificate, err := tls.X509KeyPair(
  45. []byte(config.WebServerCertificate),
  46. []byte(config.WebServerPrivateKey))
  47. if err != nil {
  48. return psiphon.ContextError(err)
  49. }
  50. tlsConfig := &tls.Config{
  51. Certificates: []tls.Certificate{certificate},
  52. }
  53. // TODO: inherits global log config?
  54. logWriter := NewLogWriter()
  55. defer logWriter.Close()
  56. server := &psiphon.HTTPSServer{
  57. http.Server{
  58. Handler: serveMux,
  59. TLSConfig: tlsConfig,
  60. ReadTimeout: WEB_SERVER_READ_TIMEOUT,
  61. WriteTimeout: WEB_SERVER_WRITE_TIMEOUT,
  62. ErrorLog: golanglog.New(logWriter, "", 0),
  63. },
  64. }
  65. listener, err := net.Listen(
  66. "tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, config.WebServerPort))
  67. if err != nil {
  68. return psiphon.ContextError(err)
  69. }
  70. log.WithContext().Info("starting")
  71. err = nil
  72. errors := make(chan error)
  73. waitGroup := new(sync.WaitGroup)
  74. waitGroup.Add(1)
  75. go func() {
  76. defer waitGroup.Done()
  77. // Note: will be interrupted by listener.Close()
  78. err := server.ServeTLS(listener)
  79. // Can't check for the exact error that Close() will cause in Accept(),
  80. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  81. // explicit stop signal to stop gracefully.
  82. select {
  83. case <-shutdownBroadcast:
  84. default:
  85. if err != nil {
  86. select {
  87. case errors <- psiphon.ContextError(err):
  88. default:
  89. }
  90. }
  91. }
  92. log.WithContext().Info("stopped")
  93. }()
  94. select {
  95. case <-shutdownBroadcast:
  96. case err = <-errors:
  97. }
  98. listener.Close()
  99. waitGroup.Wait()
  100. log.WithContext().Info("exiting")
  101. return err
  102. }
  103. func (webServer *webServer) checkWebServerSecret(r *http.Request) bool {
  104. return subtle.ConstantTimeCompare(
  105. []byte(r.URL.Query().Get("server_secret")),
  106. []byte(webServer.config.WebServerSecret)) == 1
  107. }
  108. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  109. if !webServer.checkWebServerSecret(r) {
  110. // TODO: log more details?
  111. log.WithContext().Warning("checkWebServerSecret failed")
  112. // TODO: psi_web returns NotFound in this case
  113. w.WriteHeader(http.StatusForbidden)
  114. return
  115. }
  116. // TODO: validate; proper log
  117. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("handshake")
  118. // TODO: necessary, in case client sends bogus request body?
  119. _, err := ioutil.ReadAll(r.Body)
  120. if err != nil {
  121. w.WriteHeader(http.StatusInternalServerError)
  122. return
  123. }
  124. // TODO: backwards compatibility cases (only sending the new JSON format response line)
  125. // TODO: share struct definition with psiphon/serverApi.go?
  126. // TODO: populate more response data
  127. var handshakeConfig struct {
  128. Homepages []string `json:"homepages"`
  129. UpgradeClientVersion string `json:"upgrade_client_version"`
  130. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  131. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  132. EncodedServerList []string `json:"encoded_server_list"`
  133. ClientRegion string `json:"client_region"`
  134. ServerTimestamp string `json:"server_timestamp"`
  135. }
  136. handshakeConfig.ServerTimestamp = psiphon.GetCurrentTimestamp()
  137. jsonPayload, err := json.Marshal(handshakeConfig)
  138. if err != nil {
  139. w.WriteHeader(http.StatusInternalServerError)
  140. return
  141. }
  142. responseBody := append([]byte("Config: "), jsonPayload...)
  143. w.WriteHeader(http.StatusOK)
  144. w.Write(responseBody)
  145. }
  146. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  147. if !webServer.checkWebServerSecret(r) {
  148. // TODO: log more details?
  149. log.WithContext().Warning("checkWebServerSecret failed")
  150. // TODO: psi_web does NotFound in this case
  151. w.WriteHeader(http.StatusForbidden)
  152. return
  153. }
  154. // TODO: validate; proper log
  155. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("connected")
  156. // TODO: necessary, in case client sends bogus request body?
  157. _, err := ioutil.ReadAll(r.Body)
  158. if err != nil {
  159. w.WriteHeader(http.StatusInternalServerError)
  160. return
  161. }
  162. var connectedResponse struct {
  163. ConnectedTimestamp string `json:"connected_timestamp"`
  164. }
  165. connectedResponse.ConnectedTimestamp =
  166. psiphon.TruncateTimestampToHour(psiphon.GetCurrentTimestamp())
  167. responseBody, err := json.Marshal(connectedResponse)
  168. if err != nil {
  169. w.WriteHeader(http.StatusInternalServerError)
  170. return
  171. }
  172. w.WriteHeader(http.StatusOK)
  173. w.Write(responseBody)
  174. }
  175. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  176. if !webServer.checkWebServerSecret(r) {
  177. // TODO: log more details?
  178. log.WithContext().Warning("checkWebServerSecret failed")
  179. // TODO: psi_web does NotFound in this case
  180. w.WriteHeader(http.StatusForbidden)
  181. return
  182. }
  183. // TODO: validate; proper log
  184. log.WithContextFields(LogFields{"queryParams": r.URL.Query()}).Info("status")
  185. // TODO: use json.NewDecoder(r.Body)? But will that handle bogus extra data in request body?
  186. requestBody, err := ioutil.ReadAll(r.Body)
  187. if err != nil {
  188. w.WriteHeader(http.StatusInternalServerError)
  189. return
  190. }
  191. // TODO: parse payload; validate; proper logs
  192. log.WithContextFields(LogFields{"payload": string(requestBody)}).Info("status payload")
  193. w.WriteHeader(http.StatusOK)
  194. }