| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242 |
- /*
- * Copyright (c) 2016, Psiphon Inc.
- * All rights reserved.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- */
- package server
- import (
- "crypto/subtle"
- "crypto/tls"
- "encoding/json"
- "fmt"
- "io/ioutil"
- golanglog "log"
- "net"
- "net/http"
- "sync"
- log "github.com/Psiphon-Inc/logrus"
- "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
- )
- type webServer struct {
- serveMux *http.ServeMux
- config *Config
- }
- func RunWebServer(config *Config, shutdownBroadcast <-chan struct{}) error {
- webServer := &webServer{
- config: config,
- }
- serveMux := http.NewServeMux()
- serveMux.HandleFunc("/handshake", webServer.handshakeHandler)
- serveMux.HandleFunc("/connected", webServer.connectedHandler)
- serveMux.HandleFunc("/status", webServer.statusHandler)
- certificate, err := tls.X509KeyPair(
- []byte(config.WebServerCertificate),
- []byte(config.WebServerPrivateKey))
- if err != nil {
- return psiphon.ContextError(err)
- }
- tlsConfig := &tls.Config{
- Certificates: []tls.Certificate{certificate},
- }
- // TODO: inherit global log config?
- logWriter := log.StandardLogger().Writer()
- defer logWriter.Close()
- server := &psiphon.HTTPSServer{
- http.Server{
- Handler: serveMux,
- TLSConfig: tlsConfig,
- ReadTimeout: WEB_SERVER_READ_TIMEOUT,
- WriteTimeout: WEB_SERVER_WRITE_TIMEOUT,
- ErrorLog: golanglog.New(logWriter, "", 0),
- },
- }
- listener, err := net.Listen(
- "tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, config.WebServerPort))
- if err != nil {
- return psiphon.ContextError(err)
- }
- log.Info("RunWebServer: starting server")
- err = nil
- errors := make(chan error)
- waitGroup := new(sync.WaitGroup)
- waitGroup.Add(1)
- go func() {
- defer waitGroup.Done()
- // Note: will be interrupted by listener.Close()
- err := server.ServeTLS(listener)
- // Can't check for the exact error that Close() will cause in Accept(),
- // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
- // explicit stop signal to stop gracefully.
- select {
- case <-shutdownBroadcast:
- default:
- if err != nil {
- select {
- case errors <- psiphon.ContextError(err):
- default:
- }
- }
- }
- log.Info("RunWebServer: server stopped")
- }()
- select {
- case <-shutdownBroadcast:
- case err = <-errors:
- }
- listener.Close()
- waitGroup.Wait()
- log.Info("RunWebServer: exiting")
- return err
- }
- func (webServer *webServer) checkWebServerSecret(r *http.Request) bool {
- return subtle.ConstantTimeCompare(
- []byte(r.URL.Query().Get("server_secret")),
- []byte(webServer.config.WebServerSecret)) == 1
- }
- func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Request) {
- if !webServer.checkWebServerSecret(r) {
- // TODO: log more details?
- log.Warning("handshakeHandler: checkWebServerSecret failed")
- // TODO: psi_web returns NotFound in this case
- w.WriteHeader(http.StatusForbidden)
- return
- }
- // TODO: validate; proper log
- log.Info("handshake: %+v", r.URL.Query())
- // TODO: necessary, in case client sends bogus request body?
- _, err := ioutil.ReadAll(r.Body)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- // TODO: backwards compatibility cases (only sending the new JSON format response line)
- // TODO: share struct definition with psiphon/serverApi.go?
- // TODO: populate more response data
- var handshakeConfig struct {
- Homepages []string `json:"homepages"`
- UpgradeClientVersion string `json:"upgrade_client_version"`
- PageViewRegexes []map[string]string `json:"page_view_regexes"`
- HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
- EncodedServerList []string `json:"encoded_server_list"`
- ClientRegion string `json:"client_region"`
- ServerTimestamp string `json:"server_timestamp"`
- }
- handshakeConfig.ServerTimestamp = psiphon.GetCurrentTimestamp()
- jsonPayload, err := json.Marshal(handshakeConfig)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- responseBody := append([]byte("Config: "), jsonPayload...)
- w.WriteHeader(http.StatusOK)
- w.Write(responseBody)
- }
- func (webServer *webServer) connectedHandler(w http.ResponseWriter, r *http.Request) {
- if !webServer.checkWebServerSecret(r) {
- // TODO: log more details?
- log.Warning("handshakeHandler: checkWebServerSecret failed")
- // TODO: psi_web does NotFound in this case
- w.WriteHeader(http.StatusForbidden)
- return
- }
- // TODO: validate; proper log
- log.Info("connected: %+v", r.URL.Query())
- // TODO: necessary, in case client sends bogus request body?
- _, err := ioutil.ReadAll(r.Body)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- var connectedResponse struct {
- ConnectedTimestamp string `json:"connected_timestamp"`
- }
- connectedResponse.ConnectedTimestamp =
- psiphon.TruncateTimestampToHour(psiphon.GetCurrentTimestamp())
- responseBody, err := json.Marshal(connectedResponse)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- w.WriteHeader(http.StatusOK)
- w.Write(responseBody)
- }
- func (webServer *webServer) statusHandler(w http.ResponseWriter, r *http.Request) {
- if !webServer.checkWebServerSecret(r) {
- // TODO: log more details?
- log.Warning("handshakeHandler: checkWebServerSecret failed")
- // TODO: psi_web does NotFound in this case
- w.WriteHeader(http.StatusForbidden)
- return
- }
- // TODO: validate; proper log
- log.Info("status: %+v", r.URL.Query())
- // TODO: use json.NewDecoder(r.Body)? But will that handle bogus extra data in request body?
- requestBody, err := ioutil.ReadAll(r.Body)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- // TODO: parse payload; validate; proper logs
- log.Info("status payload: %s", string(requestBody))
- w.WriteHeader(http.StatusOK)
- }
|