]> Cypherpunks.ru repositories - ucspi.git/blob - conn.go
7076336a2cabb56a671d63189fb88cd26f5d210e
[ucspi.git] / conn.go
1 /*
2 ucspi -- UCSPI-related utilities
3 Copyright (C) 2021-2023 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 ucspi
19
20 import (
21         "errors"
22         "net"
23         "os"
24         "time"
25 )
26
27 type Addr struct {
28         ip   string
29         port string
30 }
31
32 func (addr *Addr) Network() string { return "tcp" }
33
34 func (addr *Addr) String() string { return addr.ip + ":" + addr.port }
35
36 type Conn struct {
37         R *os.File
38         W *os.File
39 }
40
41 func NewConn(r, w *os.File) (*Conn, error) {
42         if r == nil {
43                 return nil, errors.New("no R file descriptor")
44         }
45         if w == nil {
46                 return nil, errors.New("no W file descriptor")
47         }
48         return &Conn{R: r, W: w}, nil
49 }
50
51 func (conn *Conn) Read(b []byte) (int, error) {
52         return conn.R.Read(b)
53 }
54
55 func (conn *Conn) Write(b []byte) (int, error) { return conn.W.Write(b) }
56
57 func (conn *Conn) Close() error {
58         errR := conn.R.Close()
59         errW := conn.W.Close()
60         if errR != nil {
61                 return errR
62         }
63         return errW
64 }
65
66 func (conn *Conn) LocalAddr() net.Addr {
67         return &Addr{ip: os.Getenv("TCPLOCALIP"), port: os.Getenv("TCPLOCALPORT")}
68 }
69
70 func (conn *Conn) RemoteAddr() net.Addr {
71         return &Addr{ip: os.Getenv("TCPREMOTEIP"), port: os.Getenv("TCPREMOTEPORT")}
72 }
73
74 func (conn *Conn) SetDeadline(t time.Time) error {
75         if err := conn.R.SetReadDeadline(t); err != nil {
76                 return err
77         }
78         return conn.W.SetWriteDeadline(t)
79 }
80
81 func (conn *Conn) SetReadDeadline(t time.Time) error {
82         return conn.R.SetReadDeadline(t)
83 }
84
85 func (conn *Conn) SetWriteDeadline(t time.Time) error {
86         return conn.W.SetWriteDeadline(t)
87 }