webServer.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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/tls"
  22. "encoding/json"
  23. "fmt"
  24. "io/ioutil"
  25. golanglog "log"
  26. "net"
  27. "net/http"
  28. "sync"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  30. )
  31. type webServer struct {
  32. support *SupportServices
  33. serveMux *http.ServeMux
  34. }
  35. // RunWebServer runs a web server which supports tunneled and untunneled
  36. // Psiphon API requests.
  37. //
  38. // The HTTP request handlers are light wrappers around the base Psiphon
  39. // API request handlers from the SSH API transport. The SSH API transport
  40. // is preferred by new clients; however the web API transport is still
  41. // required for untunneled final status requests. The web API transport
  42. // may be retired once untunneled final status requests are made obsolete
  43. // (e.g., by server-side bytes transferred stats, by client-side local
  44. // storage of stats for retry, or some other future development).
  45. //
  46. // The API is compatible with all tunnel-core clients but not backwards
  47. // compatible with older clients.
  48. //
  49. func RunWebServer(
  50. support *SupportServices,
  51. shutdownBroadcast <-chan struct{}) error {
  52. webServer := &webServer{
  53. support: support,
  54. }
  55. serveMux := http.NewServeMux()
  56. serveMux.HandleFunc("/handshake", webServer.handshakeHandler)
  57. serveMux.HandleFunc("/connected", webServer.connectedHandler)
  58. serveMux.HandleFunc("/status", webServer.statusHandler)
  59. serveMux.HandleFunc("/client_verification", webServer.clientVerificationHandler)
  60. certificate, err := tls.X509KeyPair(
  61. []byte(support.Config.WebServerCertificate),
  62. []byte(support.Config.WebServerPrivateKey))
  63. if err != nil {
  64. return psiphon.ContextError(err)
  65. }
  66. tlsConfig := &tls.Config{
  67. Certificates: []tls.Certificate{certificate},
  68. }
  69. // TODO: inherits global log config?
  70. logWriter := NewLogWriter()
  71. defer logWriter.Close()
  72. server := &psiphon.HTTPSServer{
  73. http.Server{
  74. MaxHeaderBytes: MAX_API_PARAMS_SIZE,
  75. Handler: serveMux,
  76. TLSConfig: tlsConfig,
  77. ReadTimeout: WEB_SERVER_READ_TIMEOUT,
  78. WriteTimeout: WEB_SERVER_WRITE_TIMEOUT,
  79. ErrorLog: golanglog.New(logWriter, "", 0),
  80. },
  81. }
  82. listener, err := net.Listen(
  83. "tcp", fmt.Sprintf("%s:%d",
  84. support.Config.ServerIPAddress,
  85. support.Config.WebServerPort))
  86. if err != nil {
  87. return psiphon.ContextError(err)
  88. }
  89. log.WithContext().Info("starting")
  90. err = nil
  91. errors := make(chan error)
  92. waitGroup := new(sync.WaitGroup)
  93. waitGroup.Add(1)
  94. go func() {
  95. defer waitGroup.Done()
  96. // Note: will be interrupted by listener.Close()
  97. err := server.ServeTLS(listener)
  98. // Can't check for the exact error that Close() will cause in Accept(),
  99. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  100. // explicit stop signal to stop gracefully.
  101. select {
  102. case <-shutdownBroadcast:
  103. default:
  104. if err != nil {
  105. select {
  106. case errors <- psiphon.ContextError(err):
  107. default:
  108. }
  109. }
  110. }
  111. log.WithContext().Info("stopped")
  112. }()
  113. select {
  114. case <-shutdownBroadcast:
  115. case err = <-errors:
  116. }
  117. listener.Close()
  118. waitGroup.Wait()
  119. log.WithContext().Info("exiting")
  120. return err
  121. }
  122. // convertHTTPRequestToAPIRequest converts the HTTP request query
  123. // parameters and request body to the JSON object import format
  124. // expected by the API request handlers.
  125. func convertHTTPRequestToAPIRequest(
  126. w http.ResponseWriter,
  127. r *http.Request,
  128. requestBodyName string) (requestJSONObject, error) {
  129. params := make(requestJSONObject)
  130. for name, values := range r.URL.Query() {
  131. for _, value := range values {
  132. params[name] = value
  133. // Note: multiple values per name are ignored
  134. break
  135. }
  136. }
  137. if requestBodyName != "" {
  138. r.Body = http.MaxBytesReader(w, r.Body, MAX_API_PARAMS_SIZE)
  139. body, err := ioutil.ReadAll(r.Body)
  140. if err != nil {
  141. return nil, psiphon.ContextError(err)
  142. }
  143. var bodyParams requestJSONObject
  144. err = json.Unmarshal(body, &bodyParams)
  145. if err != nil {
  146. return nil, psiphon.ContextError(err)
  147. }
  148. params[requestBodyName] = bodyParams
  149. }
  150. return params, nil
  151. }
  152. func (webServer *webServer) lookupGeoIPData(params requestJSONObject) GeoIPData {
  153. clientSessionID, err := getStringRequestParam(params, "client_session_id")
  154. if err != nil {
  155. // Not all clients send this parameter
  156. return NewGeoIPData()
  157. }
  158. return webServer.support.GeoIPService.GetSessionCache(clientSessionID)
  159. }
  160. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  161. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  162. var responsePayload []byte
  163. if err == nil {
  164. responsePayload, err = handshakeAPIRequestHandler(
  165. webServer.support, webServer.lookupGeoIPData(params), params)
  166. }
  167. if err != nil {
  168. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  169. w.WriteHeader(http.StatusNotFound)
  170. return
  171. }
  172. // The legacy response format is newline seperated, name prefixed values.
  173. // Within that legacy format, the modern JSON response (containing all the
  174. // legacy response values and more) is single value with a "Config:" prefix.
  175. // This response uses the legacy format but omits all but the JSON value.
  176. responseBody := append([]byte("Config: "), responsePayload...)
  177. w.WriteHeader(http.StatusOK)
  178. w.Write(responseBody)
  179. }
  180. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  181. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  182. var responsePayload []byte
  183. if err == nil {
  184. responsePayload, err = connectedAPIRequestHandler(
  185. webServer.support, webServer.lookupGeoIPData(params), params)
  186. }
  187. if err != nil {
  188. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  189. w.WriteHeader(http.StatusNotFound)
  190. return
  191. }
  192. w.WriteHeader(http.StatusOK)
  193. w.Write(responsePayload)
  194. }
  195. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  196. params, err := convertHTTPRequestToAPIRequest(w, r, "statusData")
  197. if err == nil {
  198. _, err = statusAPIRequestHandler(
  199. webServer.support, webServer.lookupGeoIPData(params), params)
  200. }
  201. if err != nil {
  202. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  203. w.WriteHeader(http.StatusNotFound)
  204. return
  205. }
  206. w.WriteHeader(http.StatusOK)
  207. }
  208. func (webServer *webServer) clientVerificationHandler(w http.ResponseWriter, r *http.Request) {
  209. params, err := convertHTTPRequestToAPIRequest(w, r, "verificationData")
  210. if err == nil {
  211. _, err = clientVerificationAPIRequestHandler(
  212. webServer.support, webServer.lookupGeoIPData(params), params)
  213. }
  214. if err != nil {
  215. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  216. w.WriteHeader(http.StatusNotFound)
  217. return
  218. }
  219. w.WriteHeader(http.StatusOK)
  220. }