webServer.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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/common"
  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 common.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 := &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. // Disable auto HTTP/2 (https://golang.org/doc/go1.6)
  85. TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
  86. },
  87. }
  88. localAddress := fmt.Sprintf("%s:%d",
  89. support.Config.ServerIPAddress, support.Config.WebServerPort)
  90. listener, err := net.Listen("tcp", localAddress)
  91. if err != nil {
  92. return common.ContextError(err)
  93. }
  94. log.WithContextFields(
  95. LogFields{"localAddress": localAddress}).Info("starting")
  96. err = nil
  97. errors := make(chan error)
  98. waitGroup := new(sync.WaitGroup)
  99. waitGroup.Add(1)
  100. go func() {
  101. defer waitGroup.Done()
  102. // Note: will be interrupted by listener.Close()
  103. err := server.ServeTLS(listener)
  104. // Can't check for the exact error that Close() will cause in Accept(),
  105. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  106. // explicit stop signal to stop gracefully.
  107. select {
  108. case <-shutdownBroadcast:
  109. default:
  110. if err != nil {
  111. select {
  112. case errors <- common.ContextError(err):
  113. default:
  114. }
  115. }
  116. }
  117. log.WithContextFields(
  118. LogFields{"localAddress": localAddress}).Info("stopped")
  119. }()
  120. select {
  121. case <-shutdownBroadcast:
  122. case err = <-errors:
  123. }
  124. listener.Close()
  125. waitGroup.Wait()
  126. log.WithContextFields(
  127. LogFields{"localAddress": localAddress}).Info("exiting")
  128. return err
  129. }
  130. // convertHTTPRequestToAPIRequest converts the HTTP request query
  131. // parameters and request body to the JSON object import format
  132. // expected by the API request handlers.
  133. func convertHTTPRequestToAPIRequest(
  134. w http.ResponseWriter,
  135. r *http.Request,
  136. requestBodyName string) (requestJSONObject, error) {
  137. params := make(requestJSONObject)
  138. for name, values := range r.URL.Query() {
  139. for _, value := range values {
  140. // Note: multiple values per name are ignored
  141. // TODO: faster lookup?
  142. isArray := false
  143. for _, paramSpec := range baseRequestParams {
  144. if paramSpec.name == name {
  145. isArray = (paramSpec.flags&requestParamArray != 0)
  146. break
  147. }
  148. }
  149. if isArray {
  150. // Special case: a JSON encoded array
  151. var arrayValue []interface{}
  152. err := json.Unmarshal([]byte(value), &arrayValue)
  153. if err != nil {
  154. return nil, common.ContextError(err)
  155. }
  156. params[name] = arrayValue
  157. } else {
  158. // All other query parameters are simple strings
  159. params[name] = value
  160. }
  161. break
  162. }
  163. }
  164. if requestBodyName != "" {
  165. r.Body = http.MaxBytesReader(w, r.Body, MAX_API_PARAMS_SIZE)
  166. body, err := ioutil.ReadAll(r.Body)
  167. if err != nil {
  168. return nil, common.ContextError(err)
  169. }
  170. var bodyParams map[string]interface{}
  171. if len(body) != 0 {
  172. err = json.Unmarshal(body, &bodyParams)
  173. if err != nil {
  174. return nil, common.ContextError(err)
  175. }
  176. params[requestBodyName] = bodyParams
  177. }
  178. }
  179. return params, nil
  180. }
  181. func (webServer *webServer) lookupGeoIPData(params requestJSONObject) GeoIPData {
  182. clientSessionID, err := getStringRequestParam(params, "client_session_id")
  183. if err != nil {
  184. // Not all clients send this parameter
  185. return NewGeoIPData()
  186. }
  187. return webServer.support.GeoIPService.GetSessionCache(clientSessionID)
  188. }
  189. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  190. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  191. var responsePayload []byte
  192. if err == nil {
  193. responsePayload, err = dispatchAPIRequestHandler(
  194. webServer.support,
  195. webServer.lookupGeoIPData(params),
  196. common.PSIPHON_API_HANDSHAKE_REQUEST_NAME,
  197. params)
  198. }
  199. if err != nil {
  200. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  201. w.WriteHeader(http.StatusNotFound)
  202. return
  203. }
  204. // The legacy response format is newline seperated, name prefixed values.
  205. // Within that legacy format, the modern JSON response (containing all the
  206. // legacy response values and more) is single value with a "Config:" prefix.
  207. // This response uses the legacy format but omits all but the JSON value.
  208. responseBody := append([]byte("Config: "), responsePayload...)
  209. w.WriteHeader(http.StatusOK)
  210. w.Write(responseBody)
  211. }
  212. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  213. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  214. var responsePayload []byte
  215. if err == nil {
  216. responsePayload, err = dispatchAPIRequestHandler(
  217. webServer.support,
  218. webServer.lookupGeoIPData(params),
  219. common.PSIPHON_API_CONNECTED_REQUEST_NAME,
  220. params)
  221. }
  222. if err != nil {
  223. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  224. w.WriteHeader(http.StatusNotFound)
  225. return
  226. }
  227. w.WriteHeader(http.StatusOK)
  228. w.Write(responsePayload)
  229. }
  230. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  231. params, err := convertHTTPRequestToAPIRequest(w, r, "statusData")
  232. if err == nil {
  233. _, err = dispatchAPIRequestHandler(
  234. webServer.support,
  235. webServer.lookupGeoIPData(params),
  236. common.PSIPHON_API_STATUS_REQUEST_NAME,
  237. params)
  238. }
  239. if err != nil {
  240. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  241. w.WriteHeader(http.StatusNotFound)
  242. return
  243. }
  244. w.WriteHeader(http.StatusOK)
  245. }
  246. func (webServer *webServer) clientVerificationHandler(w http.ResponseWriter, r *http.Request) {
  247. params, err := convertHTTPRequestToAPIRequest(w, r, "verificationData")
  248. var responsePayload []byte
  249. if err == nil {
  250. responsePayload, err = dispatchAPIRequestHandler(
  251. webServer.support,
  252. webServer.lookupGeoIPData(params),
  253. common.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME,
  254. params)
  255. }
  256. if err != nil {
  257. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  258. w.WriteHeader(http.StatusNotFound)
  259. return
  260. }
  261. w.WriteHeader(http.StatusOK)
  262. w.Write(responsePayload)
  263. }