aboutsummaryrefslogtreecommitdiff
path: root/src/gnunet/transport/channel.go
blob: 1632aab01d81a9efa2ec1e6b717f6bb5be816523 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// This file is part of gnunet-go, a GNUnet-implementation in Golang.
// Copyright (C) 2019, 2020 Bernd Fix  >Y<
//
// gnunet-go is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// gnunet-go is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later

package transport

import (
	"encoding/hex"
	"errors"
	"fmt"
	"path"
	"strings"

	"gnunet/message"
	"gnunet/util"

	"github.com/bfix/gospel/concurrent"
	"github.com/bfix/gospel/data"
	"github.com/bfix/gospel/logger"
)

// Error codes
var (
	ErrChannelNotImplemented = fmt.Errorf("protocol not implemented")
	ErrChannelNotOpened      = fmt.Errorf("channel not opened")
	ErrChannelInterrupted    = fmt.Errorf("channel interrupted")
)

////////////////////////////////////////////////////////////////////////
// CHANNEL

// Channel is an abstraction for exchanging arbitrary data over various
// transport protocols and mechanisms. They are created by clients via
// 'NewChannel()' or by services run via 'NewChannelServer()'.
// A string specifies the end-point of the channel:
//     "unix+/tmp/test.sock" -- for UDS channels
//     "tcp+1.2.3.4:5"       -- for TCP channels
//     "udp+1.2.3.4:5"       -- for UDP channels
type Channel interface {
	Open(spec string) error                           // open channel (for read/write)
	Close() error                                     // close open channel
	IsOpen() bool                                     // check if channel is open
	Read([]byte, *concurrent.Signaller) (int, error)  // read from channel
	Write([]byte, *concurrent.Signaller) (int, error) // write to channel
}

// ChannelFactory instantiates specific Channel imülementations.
type ChannelFactory func() Channel

// Known channel implementations.
var channelImpl = map[string]ChannelFactory{
	"unix": NewSocketChannel,
	"tcp":  NewTCPChannel,
	"udp":  NewUDPChannel,
}

// NewChannel creates a new channel to the specified endpoint.
// Called by a client to connect to a service.
func NewChannel(spec string) (Channel, error) {
	parts := strings.Split(spec, "+")
	if fac, ok := channelImpl[parts[0]]; ok {
		inst := fac()
		err := inst.Open(spec)
		return inst, err
	}
	return nil, ErrChannelNotImplemented
}

////////////////////////////////////////////////////////////////////////
// CHANNEL SERVER

// ChannelServer creates a listener for the specified endpoint.
// The specification string has the same format as for Channel with slightly
// different semantics (for TCP, and ICMP the address specifies is a mask
// for client addresses accepted for a channel request).
type ChannelServer interface {
	Open(spec string, hdlr chan<- Channel) error
	Close() error
}

// ChannelServerFactory instantiates specific ChannelServer imülementations.
type ChannelServerFactory func() ChannelServer

// Known channel server implementations.
var channelServerImpl = map[string]ChannelServerFactory{
	"unix": NewSocketChannelServer,
	"tcp":  NewTCPChannelServer,
	"udp":  NewUDPChannelServer,
}

// NewChannelServer creates a new channel server instance
func NewChannelServer(spec string, hdlr chan<- Channel) (cs ChannelServer, err error) {
	parts := strings.Split(spec, "+")

	if fac, ok := channelServerImpl[parts[0]]; ok {
		// check if the basedir for the spec exists...
		if err = util.EnforceDirExists(path.Dir(parts[1])); err != nil {
			return
		}
		// instantiate server implementation
		cs = fac()
		// create the domain socket and listen to it.
		err = cs.Open(spec, hdlr)
		return
	}
	return nil, ErrChannelNotImplemented
}

////////////////////////////////////////////////////////////////////////
// MESSAGE CHANNEL

// MsgChannel s a wrapper around a generic channel for GNUnet message exchange.
type MsgChannel struct {
	ch  Channel
	buf []byte
}

// NewMsgChannel wraps a plain Channel for GNUnet message exchange.
func NewMsgChannel(ch Channel) *MsgChannel {
	return &MsgChannel{
		ch:  ch,
		buf: make([]byte, 65536),
	}
}

// Close a MsgChannel by closing the wrapped plain Channel.
func (c *MsgChannel) Close() error {
	return c.ch.Close()
}

// Send a GNUnet message over a channel.
func (c *MsgChannel) Send(msg message.Message, sig *concurrent.Signaller) error {
	// convert message to binary data
	data, err := data.Marshal(msg)
	if err != nil {
		return err
	}
	logger.Printf(logger.DBG, "==> %v\n", msg)
	logger.Printf(logger.DBG, "    [%s]\n", hex.EncodeToString(data))

	// check message header size and packet size
	mh, err := message.GetMsgHeader(data)
	if err != nil {
		return err
	}
	if len(data) != int(mh.MsgSize) {
		return errors.New("send: message size mismatch")
	}

	// send packet
	n, err := c.ch.Write(data, sig)
	if err != nil {
		return err
	}
	if n != len(data) {
		return errors.New("incomplete send")
	}
	return nil
}

// Receive GNUnet messages over a plain Channel.
func (c *MsgChannel) Receive(sig *concurrent.Signaller) (message.Message, error) {
	// get bytes from channel
	get := func(pos, count int) error {
		n, err := c.ch.Read(c.buf[pos:pos+count], sig)
		if err != nil {
			return err
		}
		if n != count {
			return errors.New("not enough bytes on network")
		}
		return nil
	}

	if err := get(0, 4); err != nil {
		return nil, err
	}
	mh, err := message.GetMsgHeader(c.buf[:4])
	if err != nil {
		return nil, err
	}

	if err := get(4, int(mh.MsgSize)-4); err != nil {
		return nil, err
	}
	msg, err := message.NewEmptyMessage(mh.MsgType)
	if err != nil {
		return nil, err
	}
	if msg == nil {
		return nil, fmt.Errorf("message{%d} is nil", mh.MsgType)
	}
	if err = data.Unmarshal(msg, c.buf[:mh.MsgSize]); err != nil {
		return nil, err
	}
	logger.Printf(logger.DBG, "<== %v\n", msg)
	logger.Printf(logger.DBG, "    [%s]\n", hex.EncodeToString(c.buf[:mh.MsgSize]))
	return msg, nil
}