summaryrefslogtreecommitdiff
path: root/src/daq/s5proxy/src/s5proxy/proxy.go
blob: 3f5ec89409a2c7e73d794664640eb96f98e46ab8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
//
// sfive
//
// sfive - spreadspace streaming statistics suite is a generic
// statistic collection tool for streaming server infrastuctures.
// The system collects and stores meta data like number of views
// and throughput from a number of streaming servers and stores
// it in a global data store.
// The data acquisition is designed to be generic and extensible in
// order to support different streaming software.
// sfive also contains tools and applications to filter and visualize
// live and recorded data.
//
//
// Copyright (C) 2014-2017 Christian Pointner <equinox@spreadspace.org>
//                         Markus Grüneis <gimpf@gimpf.org>
//
// This file is part of sfive.
//
// sfive is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// sfive 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 sfive. If not, see <http://www.gnu.org/licenses/>.
//

package main

import (
	"crypto/tls"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
	"time"

	"github.com/soheilhy/cmux"
)

func generateTime(input string) string {
	d, err := time.ParseDuration(input)
	if err != nil {
		s5l.Printf("PROXY: can't parse duration: %v", err)
		return ""
	}

	return time.Now().Add(d).Format(time.RFC1123)
}

type s5proxyResponseWriter struct {
	wrapped   http.ResponseWriter
	conf      *Config
	StatsCh   chan<- *Client
	IP        string
	Port      int
	UserAgent string
}

func (r s5proxyResponseWriter) Header() http.Header {
	return r.wrapped.Header()
}

func (r s5proxyResponseWriter) Write(data []byte) (int, error) {
	sent, err := r.wrapped.Write(data)
	if r.StatsCh != nil {
		stats := &Client{IP: r.IP, Port: uint(r.Port), UserAgent: r.UserAgent, BytesSent: uint(sent)}
		select {
		case r.StatsCh <- stats:
		default:
		}
	}
	return sent, err
}

func (r s5proxyResponseWriter) WriteHeader(status int) {
	for _, h := range r.conf.ResponseHeader {
		switch h.Operation {
		case OpAdd:
			r.wrapped.Header().Add(h.Header, h.Value)
		case OpDel:
			r.wrapped.Header().Del(h.Header)
		case OpSet:
			r.wrapped.Header().Set(h.Header, h.Value)
		case OpTime:
			if ts := generateTime(h.Value); ts != "" {
				r.wrapped.Header().Set(h.Header, ts)
			}
		}
	}
	r.wrapped.WriteHeader(status)
}

func proxyHandler(p *Proxy, w http.ResponseWriter, r *http.Request) {
	pw := s5proxyResponseWriter{wrapped: w, conf: p.conf}
	if p.stats != nil {
		if ip, port, err := net.SplitHostPort(r.RemoteAddr); err != nil {
			s5l.Printf("PROXY: client '%s' error: invalid address/port info: %v, no statistics will be gathered", r.RemoteAddr, err)
		} else {
			pw.IP = ip
			if pw.Port, err = net.LookupPort("tcp", port); err != nil {
				s5l.Printf("PROXY: client '%s' warning: can't parse port or service name: %v", r.RemoteAddr, err)
			}
			pw.UserAgent = r.UserAgent()
			pw.StatsCh = p.stats.GetUpdateChannel(r.URL.String())
		}
	}

	p.proxy.ServeHTTP(pw, r)
}

type Proxy struct {
	conf  *Config
	stats *Stats
	proxy *httputil.ReverseProxy
	mux   *http.ServeMux
	srv   *http.Server
}

func NewProxy(conf *Config, stats *Stats) (p *Proxy, err error) {

	p = &Proxy{conf: conf, stats: stats}

	var remote *url.URL
	remote, err = url.Parse(conf.ConnectAddr)
	if err != nil {
		return
	}
	s5l.Printf("PROXY: forwarding traffic to '%s'", remote.String())

	p.proxy = httputil.NewSingleHostReverseProxy(remote)
	origDir := p.proxy.Director

	p.proxy.Director = func(req *http.Request) {
		origDir(req)
		for _, h := range conf.RequestHeader {
			switch h.Operation {
			case OpAdd:
				req.Header.Add(h.Header, h.Value)
			case OpDel:
				req.Header.Del(h.Header)
			case OpSet:
				req.Header.Set(h.Header, h.Value)
			case OpTime:
				if ts := generateTime(h.Value); ts != "" {
					req.Header.Set(h.Header, ts)
				}
			}
		}
	}

	p.mux = http.NewServeMux()
	p.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		proxyHandler(p, w, r)
	})

	p.srv = &http.Server{
		Handler: p.mux,
	}
	return
}

type httpsRedirectHandler struct {
	code int
}

func (h *httpsRedirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	uri := *r.URL
	uri.Scheme = "https"
	uri.Host = r.Host
	http.Redirect(w, r, uri.String(), h.code)
}

func (p *Proxy) RunHTTP(l net.Listener) error {
	mux := http.NewServeMux()
	mux.Handle("/", &httpsRedirectHandler{http.StatusTemporaryRedirect}) // TODO: make redirect code configurable

	srv := &http.Server{
		Handler: mux,
	}

	return srv.Serve(l)
}

func (p *Proxy) RunHTTPS(l net.Listener) error {
	cert, err := tls.LoadX509KeyPair(p.conf.CertFile, p.conf.KeyFile)
	if err != nil {
		return err
	}

	// TODO: make this configurable
	cfg := &tls.Config{
		Certificates:             []tls.Certificate{cert},
		MinVersion:               tls.VersionTLS10,
		CurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
		PreferServerCipherSuites: true,
		CipherSuites: []uint16{
			tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
			tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
			tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
			tls.TLS_RSA_WITH_AES_256_CBC_SHA,
		},
	}

	tlsL := tls.NewListener(l, cfg)
	return p.srv.Serve(tlsL)
}

func (p *Proxy) Run() error {
	s5l.Printf("PROXY: listening on '%s'", p.conf.ListenAddr)

	l, err := net.Listen("tcp", p.conf.ListenAddr)
	if err != nil {
		return err
	}
	m := cmux.New(l)
	httpL := m.Match(cmux.HTTP1Fast())
	httpsL := m.Match(cmux.Any())

	go p.RunHTTP(httpL)
	go p.RunHTTPS(httpsL)

	if err := m.Serve(); !strings.Contains(err.Error(), "use of closed network connection") {
		return err
	}
	return nil
}