webServer.go 7.3 KB

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