webServer.go 7.0 KB

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