webServer.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. serveMux *http.ServeMux
  33. config *Config
  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(config *Config, shutdownBroadcast <-chan struct{}) error {
  50. webServer := &webServer{
  51. config: config,
  52. }
  53. serveMux := http.NewServeMux()
  54. serveMux.HandleFunc("/handshake", webServer.handshakeHandler)
  55. serveMux.HandleFunc("/connected", webServer.connectedHandler)
  56. serveMux.HandleFunc("/status", webServer.statusHandler)
  57. serveMux.HandleFunc("/client_verification", webServer.clientVerificationHandler)
  58. certificate, err := tls.X509KeyPair(
  59. []byte(config.WebServerCertificate),
  60. []byte(config.WebServerPrivateKey))
  61. if err != nil {
  62. return psiphon.ContextError(err)
  63. }
  64. tlsConfig := &tls.Config{
  65. Certificates: []tls.Certificate{certificate},
  66. }
  67. // TODO: inherits global log config?
  68. logWriter := NewLogWriter()
  69. defer logWriter.Close()
  70. server := &psiphon.HTTPSServer{
  71. http.Server{
  72. MaxHeaderBytes: MAX_API_PARAMS_SIZE,
  73. Handler: serveMux,
  74. TLSConfig: tlsConfig,
  75. ReadTimeout: WEB_SERVER_READ_TIMEOUT,
  76. WriteTimeout: WEB_SERVER_WRITE_TIMEOUT,
  77. ErrorLog: golanglog.New(logWriter, "", 0),
  78. },
  79. }
  80. listener, err := net.Listen(
  81. "tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, config.WebServerPort))
  82. if err != nil {
  83. return psiphon.ContextError(err)
  84. }
  85. log.WithContext().Info("starting")
  86. err = nil
  87. errors := make(chan error)
  88. waitGroup := new(sync.WaitGroup)
  89. waitGroup.Add(1)
  90. go func() {
  91. defer waitGroup.Done()
  92. // Note: will be interrupted by listener.Close()
  93. err := server.ServeTLS(listener)
  94. // Can't check for the exact error that Close() will cause in Accept(),
  95. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  96. // explicit stop signal to stop gracefully.
  97. select {
  98. case <-shutdownBroadcast:
  99. default:
  100. if err != nil {
  101. select {
  102. case errors <- psiphon.ContextError(err):
  103. default:
  104. }
  105. }
  106. }
  107. log.WithContext().Info("stopped")
  108. }()
  109. select {
  110. case <-shutdownBroadcast:
  111. case err = <-errors:
  112. }
  113. listener.Close()
  114. waitGroup.Wait()
  115. log.WithContext().Info("exiting")
  116. return err
  117. }
  118. // convertHTTPRequestToAPIRequest converts the HTTP request query
  119. // parameters and request body to the JSON object import format
  120. // expected by the API request handlers.
  121. func convertHTTPRequestToAPIRequest(
  122. w http.ResponseWriter,
  123. r *http.Request,
  124. requestBodyName string) (requestJSONObject, error) {
  125. params := make(requestJSONObject)
  126. for name, values := range r.URL.Query() {
  127. for _, value := range values {
  128. params[name] = value
  129. // Note: multiple values per name are ignored
  130. break
  131. }
  132. }
  133. if requestBodyName != "" {
  134. r.Body = http.MaxBytesReader(w, r.Body, MAX_API_PARAMS_SIZE)
  135. body, err := ioutil.ReadAll(r.Body)
  136. if err != nil {
  137. return nil, psiphon.ContextError(err)
  138. }
  139. var bodyParams requestJSONObject
  140. err = json.Unmarshal(body, &bodyParams)
  141. if err != nil {
  142. return nil, psiphon.ContextError(err)
  143. }
  144. params[requestBodyName] = bodyParams
  145. }
  146. return params, nil
  147. }
  148. func (webServer *webServer) lookupGeoIPData(params requestJSONObject) GeoIPData {
  149. // TODO: implement
  150. return NewGeoIPData()
  151. }
  152. func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
  153. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  154. var responsePayload []byte
  155. if err == nil {
  156. responsePayload, err = handshakeAPIRequestHandler(
  157. webServer.config, webServer.lookupGeoIPData(params), params)
  158. }
  159. if err != nil {
  160. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  161. w.WriteHeader(http.StatusNotFound)
  162. return
  163. }
  164. // The legacy response format is newline seperated, name prefixed values.
  165. // Within that legacy format, the modern JSON response (containing all the
  166. // legacy response values and more) is single value with a "Config:" prefix.
  167. // This response uses the legacy format but omits all but the JSON value.
  168. responseBody := append([]byte("Config: "), responsePayload...)
  169. w.WriteHeader(http.StatusOK)
  170. w.Write(responseBody)
  171. }
  172. func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
  173. params, err := convertHTTPRequestToAPIRequest(w, r, "")
  174. var responsePayload []byte
  175. if err == nil {
  176. responsePayload, err = connectedAPIRequestHandler(
  177. webServer.config, webServer.lookupGeoIPData(params), params)
  178. }
  179. if err != nil {
  180. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  181. w.WriteHeader(http.StatusNotFound)
  182. return
  183. }
  184. w.WriteHeader(http.StatusOK)
  185. w.Write(responsePayload)
  186. }
  187. func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
  188. params, err := convertHTTPRequestToAPIRequest(w, r, "statusData")
  189. if err == nil {
  190. _, err = statusAPIRequestHandler(
  191. webServer.config, webServer.lookupGeoIPData(params), params)
  192. }
  193. if err != nil {
  194. log.WithContextFields(LogFields{"error": err}).Warning("failed")
  195. w.WriteHeader(http.StatusNotFound)
  196. return
  197. }
  198. w.WriteHeader(http.StatusOK)
  199. }
  200. func (webServer *webServer) clientVerificationHandler(w http.ResponseWriter, r *http.Request) {
  201. params, err := convertHTTPRequestToAPIRequest(w, r, "verificationData")
  202. if err == nil {
  203. _, err = clientVerificationAPIRequestHandler(
  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. }