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