]> Sergey Matveev's repositories - tofuproxy.git/blob - conn.go
WARC
[tofuproxy.git] / conn.go
1 /*
2 tofuproxy -- flexible HTTP/WARC proxy with TLS certificates management
3 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
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, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package tofuproxy
19
20 import (
21         "net"
22         "sync"
23         "time"
24 )
25
26 type SingleConn struct {
27         conn net.Conn
28         ln   *SingleListener
29         once sync.Once
30 }
31
32 func (conn *SingleConn) Read(b []byte) (int, error) { return conn.conn.Read(b) }
33
34 func (conn *SingleConn) Write(b []byte) (int, error) { return conn.conn.Write(b) }
35
36 func (conn *SingleConn) Close() error {
37         conn.once.Do(conn.ln.Unlock)
38         return conn.conn.Close()
39 }
40
41 func (conn *SingleConn) LocalAddr() net.Addr { return conn.conn.LocalAddr() }
42
43 func (conn *SingleConn) RemoteAddr() net.Addr { return conn.conn.RemoteAddr() }
44
45 func (conn *SingleConn) SetDeadline(t time.Time) error { return conn.conn.SetDeadline(t) }
46
47 func (conn *SingleConn) SetReadDeadline(t time.Time) error { return conn.conn.SetReadDeadline(t) }
48
49 func (conn *SingleConn) SetWriteDeadline(t time.Time) error { return conn.conn.SetWriteDeadline(t) }
50
51 type AlreadyAccepted struct{}
52
53 func (err AlreadyAccepted) Error() string { return "already accepted" }
54
55 type SingleListener struct {
56         conn     net.Conn
57         accepted bool
58         sync.Mutex
59 }
60
61 func (ln *SingleListener) Accept() (net.Conn, error) {
62         ln.Lock()
63         if ln.accepted {
64                 return nil, AlreadyAccepted{}
65         }
66         ln.accepted = true
67         return &SingleConn{conn: ln.conn, ln: ln}, nil
68 }
69
70 func (ln *SingleListener) Close() error { return nil }
71
72 func (ln *SingleListener) Addr() net.Addr { return ln.conn.LocalAddr() }