webServer.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  31. )
  32. const WEB_SERVER_IO_TIMEOUT = 10 * time.Second
  33. type webServer struct {
  34. support *SupportServices
  35. serveMux *http.ServeMux
  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. support *SupportServices,
  53. shutdownBroadcast <-chan struct{}) error {
  54. webServer := &webServer{
  55. support: support,
  56. }
  57. serveMux := http.NewServeMux()
  58. serveMux.HandleFunc("/handshake", webServer.handshakeHandler)
  59. serveMux.HandleFunc("/connected", webServer.connectedHandler)
  60. serveMux.HandleFunc("/status", webServer.statusHandler)
  61. serveMux.HandleFunc("/client_verification", webServer.clientVerificationHandler)
  62. certificate, err := tls.X509KeyPair(
  63. []byte(support.Config.WebServerCertificate),
  64. []byte(support.Config.WebServerPrivateKey))
  65. if err != nil {
  66. return psiphon.ContextError(err)
  67. }
  68. tlsConfig := &tls.Config{
  69. Certificates: []tls.Certificate{certificate},
  70. }
  71. // TODO: inherits global log config?
  72. logWriter := NewLogWriter()
  73. defer logWriter.Close()
  74. // Note: WriteTimeout includes time awaiting request, as per:
  75. // https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts
  76. server := &psiphon.HTTPSServer{
  77. http.Server{
  78. MaxHeaderBytes: MAX_API_PARAMS_SIZE,
  79. Handler: serveMux,
  80. TLSConfig: tlsConfig,
  81. ReadTimeout: WEB_SERVER_IO_TIMEOUT,
  82. WriteTimeout: WEB_SERVER_IO_TIMEOUT,
  83. ErrorLog: golanglog.New(logWriter, "", 0),
  84. },
  85. }
  86. listener, err := net.Listen(
  87. "tcp", fmt.Sprintf("%s:%d",
  88. support.Config.ServerIPAddress,
  89. support.Config.WebServerPort))
  90. if err != nil {
  91. return psiphon.ContextError(err)
  92. }
  93. log.WithContext().Info("starting")
  94. err = nil
  95. errors := make(chan error)
  96. waitGroup := new(sync.WaitGroup)
  97. waitGroup.Add(1)
  98. go func() {
  99. defer waitGroup.Done()
  100. // Note: will be interrupted by listener.Close()
  101. err := server.ServeTLS(listener)
  102. // Can't check for the exact error that Close() will cause in Accept(),
  103. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  104. // explicit stop signal to stop gracefully.
  105. select {
  106. case <-shutdownBroadcast:
  107. default:
  108. if err != nil {
  109. select {
  110. case errors <- psiphon.ContextError(err):
  111. default:
  112. }
  113. }
  114. }
  115. log.WithContext().Info("stopped")
  116. }()
  117. select {
  118. case <-shutdownBroadcast:
  119. case err = <-errors:
  120. }
  121. listener.Close()
  122. waitGroup.Wait()
  123. log.WithContext().Info("exiting")
  124. return err
  125. }
  126. // convertHTTPRequestToAPIRequest converts the HTTP request query
  127. // parameters and request body to the JSON object import format
  128. // expected by the API request handlers.
  129. func convertHTTPRequestToAPIRequest(
  130. w http.ResponseWriter,
  131. r *http.Request,
  132. requestBodyName string) (requestJSONObject, error) {
  133. params := make(requestJSONObject)
  134. for name, values := range r.URL.Query() {
  135. for _, value := range values {
  136. // Note: multiple values per name are ignored
  137. // TODO: faster lookup?
  138. isArray := false
  139. for _, paramSpec := range baseRequestParams {
  140. if paramSpec.name == name {
  141. isArray = (paramSpec.flags&requestParamArray != 0)
  142. break
  143. }
  144. }
  145. if isArray {
  146. // Special case: a JSON encoded array
  147. var arrayValue []interface{}
  148. err := json.Unmarshal([]byte(value), &arrayValue)
  149. if err != nil {
  150. return nil, psiphon.ContextError(err)
  151. }
  152. params[name] = arrayValue
  153. } else {
  154. // All other query parameters are simple strings
  155. params[name] = value
  156. }
  157. break
  158. }
  159. }
  160. if requestBodyName != "" {
  161. r.Body = http.MaxBytesReader(w, r.Body, MAX_API_PARAMS_SIZE)
  162. body, err := ioutil.ReadAll(r.Body)
  163. if err != nil {
  164. return nil, psiphon.ContextError(err)
  165. }
  166. var bodyParams requestJSONObject
  167. err = json.Unmarshal(body, &bodyParams)
  168. if err != nil {
  169. return nil, psiphon.ContextError(err)
  170. }
  171. params[requestBodyName] = bodyParams
  172. }
  173. return params, nil
  174. }
  175. func (webServer *webServer) lookupGeoIPData(params requestJSONObject) GeoIPData {
  176. clientSessionID, err := getStringRequestParam(params, "client_session_id")
  177. if err != nil {
  178. // Not all clients send this parameter
  179. return NewGeoIPData()
  180. }
  181. return webServer.support.GeoIPService.GetSessionCache(clientSessionID)
  182. }
  183. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  184. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  185. var responsePayload []byte
  186. if err == nil {
  187. responsePayload, err = handshakeAPIRequestHandler(
  188. webServer.support, webServer.lookupGeoIPData(params), params)
  189. }
  190. if err != nil {
  191. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  192. w.WriteHeader(http.StatusNotFound)
  193. return
  194. }
  195. // The legacy response format is newline seperated, name prefixed values.
  196. // Within that legacy format, the modern JSON response (containing all the
  197. // legacy response values and more) is single value with a "Config:" prefix.
  198. // This response uses the legacy format but omits all but the JSON value.
  199. responseBody := append([]byte("Config: "), responsePayload...)
  200. w.WriteHeader(http.StatusOK)
  201. w.Write(responseBody)
  202. }
  203. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  204. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  205. var responsePayload []byte
  206. if err == nil {
  207. responsePayload, err = connectedAPIRequestHandler(
  208. webServer.support, webServer.lookupGeoIPData(params), params)
  209. }
  210. if err != nil {
  211. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  212. w.WriteHeader(http.StatusNotFound)
  213. return
  214. }
  215. w.WriteHeader(http.StatusOK)
  216. w.Write(responsePayload)
  217. }
  218. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  219. params, err := convertHTTPRequestToAPIRequest(w, r, "statusData")
  220. if err == nil {
  221. _, err = statusAPIRequestHandler(
  222. webServer.support, webServer.lookupGeoIPData(params), params)
  223. }
  224. if err != nil {
  225. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  226. w.WriteHeader(http.StatusNotFound)
  227. return
  228. }
  229. w.WriteHeader(http.StatusOK)
  230. }
  231. func (webServer *webServer) clientVerificationHandler(w http.ResponseWriter, r *http.Request) {
  232. params, err := convertHTTPRequestToAPIRequest(w, r, "verificationData")
  233. if err == nil {
  234. _, err = clientVerificationAPIRequestHandler(
  235. webServer.support, webServer.lookupGeoIPData(params), params)
  236. }
  237. if err != nil {
  238. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  239. w.WriteHeader(http.StatusNotFound)
  240. return
  241. }
  242. w.WriteHeader(http.StatusOK)
  243. }