]> Sergey Matveev's repositories - tofuproxy.git/blob - conn.go
Unify copyright comment format
[tofuproxy.git] / conn.go
1 // tofuproxy -- flexible HTTP/HTTPS proxy, TLS terminator, X.509 TOFU
2 //              manager, WARC/geminispace browser
3 // Copyright (C) 2021-2024 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 package tofuproxy
18
19 import (
20         "net"
21         "sync"
22         "time"
23 )
24
25 type SingleConn struct {
26         conn net.Conn
27         ln   *SingleListener
28         once sync.Once
29 }
30
31 func (conn *SingleConn) Read(b []byte) (int, error) { return conn.conn.Read(b) }
32
33 func (conn *SingleConn) Write(b []byte) (int, error) { return conn.conn.Write(b) }
34
35 func (conn *SingleConn) Close() error {
36         conn.once.Do(conn.ln.Unlock)
37         return conn.conn.Close()
38 }
39
40 func (conn *SingleConn) LocalAddr() net.Addr { return conn.conn.LocalAddr() }
41
42 func (conn *SingleConn) RemoteAddr() net.Addr { return conn.conn.RemoteAddr() }
43
44 func (conn *SingleConn) SetDeadline(t time.Time) error { return conn.conn.SetDeadline(t) }
45
46 func (conn *SingleConn) SetReadDeadline(t time.Time) error { return conn.conn.SetReadDeadline(t) }
47
48 func (conn *SingleConn) SetWriteDeadline(t time.Time) error { return conn.conn.SetWriteDeadline(t) }
49
50 type AlreadyAccepted struct{}
51
52 func (err AlreadyAccepted) Error() string { return "already accepted" }
53
54 type SingleListener struct {
55         conn     net.Conn
56         accepted bool
57         sync.Mutex
58 }
59
60 func (ln *SingleListener) Accept() (net.Conn, error) {
61         ln.Lock()
62         if ln.accepted {
63                 return nil, AlreadyAccepted{}
64         }
65         ln.accepted = true
66         return &SingleConn{conn: ln.conn, ln: ln}, nil
67 }
68
69 func (ln *SingleListener) Close() error { return nil }
70
71 func (ln *SingleListener) Addr() net.Addr { return ln.conn.LocalAddr() }