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