webServer.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. // Note: multiple values per name are ignored
  133. // TODO: faster lookup?
  134. isArray := false
  135. for _, paramSpec := range baseRequestParams {
  136. if paramSpec.name == name {
  137. isArray = (paramSpec.flags&requestParamArray != 0)
  138. break
  139. }
  140. }
  141. if isArray {
  142. // Special case: a JSON encoded array
  143. var arrayValue []interface{}
  144. err := json.Unmarshal([]byte(value), &arrayValue)
  145. if err != nil {
  146. return nil, psiphon.ContextError(err)
  147. }
  148. params[name] = arrayValue
  149. } else {
  150. // All other query parameters are simple strings
  151. params[name] = value
  152. }
  153. break
  154. }
  155. }
  156. if requestBodyName != "" {
  157. r.Body = http.MaxBytesReader(w, r.Body, MAX_API_PARAMS_SIZE)
  158. body, err := ioutil.ReadAll(r.Body)
  159. if err != nil {
  160. return nil, psiphon.ContextError(err)
  161. }
  162. var bodyParams requestJSONObject
  163. err = json.Unmarshal(body, &bodyParams)
  164. if err != nil {
  165. return nil, psiphon.ContextError(err)
  166. }
  167. params[requestBodyName] = bodyParams
  168. }
  169. return params, nil
  170. }
  171. func (webServer *webServer) lookupGeoIPData(params requestJSONObject) GeoIPData {
  172. clientSessionID, err := getStringRequestParam(params, "client_session_id")
  173. if err != nil {
  174. // Not all clients send this parameter
  175. return NewGeoIPData()
  176. }
  177. return webServer.support.GeoIPService.GetSessionCache(clientSessionID)
  178. }
  179. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  180. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  181. var responsePayload []byte
  182. if err == nil {
  183. responsePayload, err = handshakeAPIRequestHandler(
  184. webServer.support, webServer.lookupGeoIPData(params), params)
  185. }
  186. if err != nil {
  187. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  188. w.WriteHeader(http.StatusNotFound)
  189. return
  190. }
  191. // The legacy response format is newline seperated, name prefixed values.
  192. // Within that legacy format, the modern JSON response (containing all the
  193. // legacy response values and more) is single value with a "Config:" prefix.
  194. // This response uses the legacy format but omits all but the JSON value.
  195. responseBody := append([]byte("Config: "), responsePayload...)
  196. w.WriteHeader(http.StatusOK)
  197. w.Write(responseBody)
  198. }
  199. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  200. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  201. var responsePayload []byte
  202. if err == nil {
  203. responsePayload, err = connectedAPIRequestHandler(
  204. webServer.support, 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. w.Write(responsePayload)
  213. }
  214. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  215. params, err := convertHTTPRequestToAPIRequest(w, r, "statusData")
  216. if err == nil {
  217. _, err = statusAPIRequestHandler(
  218. webServer.support, webServer.lookupGeoIPData(params), params)
  219. }
  220. if err != nil {
  221. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  222. w.WriteHeader(http.StatusNotFound)
  223. return
  224. }
  225. w.WriteHeader(http.StatusOK)
  226. }
  227. func (webServer *webServer) clientVerificationHandler(w http.ResponseWriter, r *http.Request) {
  228. params, err := convertHTTPRequestToAPIRequest(w, r, "verificationData")
  229. if err == nil {
  230. _, err = clientVerificationAPIRequestHandler(
  231. webServer.support, webServer.lookupGeoIPData(params), params)
  232. }
  233. if err != nil {
  234. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  235. w.WriteHeader(http.StatusNotFound)
  236. return
  237. }
  238. w.WriteHeader(http.StatusOK)
  239. }