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