]> Sergey Matveev's repositories - tofuproxy.git/blob - conn.go
Download link for 0.5.0 release
[tofuproxy.git] / conn.go
1 /*
2 tofuproxy -- flexible HTTP/HTTPS proxy, TLS terminator, X.509 TOFU
3              manager, WARC/geminispace browser
4 Copyright (C) 2021-2023 Sergey Matveev <stargrave@stargrave.org>
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, version 3 of the License.
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 tofuproxy
20
21 import (
22         "net"
23         "sync"
24         "time"
25 )
26
27 type SingleConn struct {
28         conn net.Conn
29         ln   *SingleListener
30         once sync.Once
31 }
32
33 func (conn *SingleConn) Read(b []byte) (int, error) { return conn.conn.Read(b) }
34
35 func (conn *SingleConn) Write(b []byte) (int, error) { return conn.conn.Write(b) }
36
37 func (conn *SingleConn) Close() error {
38         conn.once.Do(conn.ln.Unlock)
39         return conn.conn.Close()
40 }
41
42 func (conn *SingleConn) LocalAddr() net.Addr { return conn.conn.LocalAddr() }
43
44 func (conn *SingleConn) RemoteAddr() net.Addr { return conn.conn.RemoteAddr() }
45
46 func (conn *SingleConn) SetDeadline(t time.Time) error { return conn.conn.SetDeadline(t) }
47
48 func (conn *SingleConn) SetReadDeadline(t time.Time) error { return conn.conn.SetReadDeadline(t) }
49
50 func (conn *SingleConn) SetWriteDeadline(t time.Time) error { return conn.conn.SetWriteDeadline(t) }
51
52 type AlreadyAccepted struct{}
53
54 func (err AlreadyAccepted) Error() string { return "already accepted" }
55
56 type SingleListener struct {
57         conn     net.Conn
58         accepted bool
59         sync.Mutex
60 }
61
62 func (ln *SingleListener) Accept() (net.Conn, error) {
63         ln.Lock()
64         if ln.accepted {
65                 return nil, AlreadyAccepted{}
66         }
67         ln.accepted = true
68         return &SingleConn{conn: ln.conn, ln: ln}, nil
69 }
70
71 func (ln *SingleListener) Close() error { return nil }
72
73 func (ln *SingleListener) Addr() net.Addr { return ln.conn.LocalAddr() }