webServer.go 8.8 KB

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