-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
313 lines (244 loc) · 6.73 KB
/
server.go
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package main
import (
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"io"
"log"
"sync"
"time"
"github.com/SuperSection/FileStorage/p2p"
)
type FileServerOptions struct {
ID string
EncKey []byte
StorageRoot string
PathTransformFunc PathTransformFunc
Transport p2p.Transport
BootstrapNodes []string
}
type FileServer struct {
FileServerOptions
peerLock sync.Mutex
peers map[string]p2p.Peer
storage *Storage
quitch chan struct{}
}
func NewFileServer(opts FileServerOptions) *FileServer {
storageOpts := StorageOptions{
Root: opts.StorageRoot,
PathTransformFunc: opts.PathTransformFunc,
}
if len(opts.ID) == 0 {
opts.ID = generateID()
}
return &FileServer{
FileServerOptions: opts,
storage: NewStorage(storageOpts),
quitch: make(chan struct{}),
peers: make(map[string]p2p.Peer),
}
}
func (server *FileServer) broadcast(msg *Message) error {
/* encode the message */
buf := new(bytes.Buffer)
if err := gob.NewEncoder(buf).Encode(msg); err != nil {
return err
}
/* send the message to all peers in the network */
for _, peer := range server.peers {
peer.Send([]byte{p2p.IncomingMessage})
if err := peer.Send(buf.Bytes()); err != nil {
return err
}
}
return nil
}
type Message struct {
Payload any
}
type MessageStoreFile struct {
ID string
Key string
Size int64
}
type MessageGetFile struct {
ID string
Key string
}
func (server *FileServer) Get(key string) (io.Reader, error) {
if server.storage.Has(server.ID, key) {
fmt.Printf("[%s] serving file (%s) from local disk\n", server.Transport.ListenAddr(), key)
_, r, err := server.storage.Read(server.ID, key)
return r, err
}
fmt.Printf("[%s] don't have file (%s) locally, fetching from network...\n", server.Transport.ListenAddr(), key)
msg := Message{
Payload: MessageGetFile{
ID: server.ID,
Key: hashKey(key),
},
}
if err := server.broadcast(&msg); err != nil {
return nil, err
}
time.Sleep(time.Millisecond * 500)
for _, peer := range server.peers {
/* first read the file size so we can limit the amount of bytes
that we need from the connection so it will not keep hanging */
var fileSize int64
binary.Read(peer, binary.LittleEndian, &fileSize)
n, err := server.storage.writeDecrypt(server.EncKey, server.ID, key, io.LimitReader(peer, fileSize))
if err != nil {
return nil, err
}
fmt.Printf("[%s] received (%d) bytes over the network from (%s): ", server.Transport.ListenAddr(), n, peer.RemoteAddr())
peer.CloseStream()
}
_, r, err := server.storage.Read(server.ID, key)
return r, err
}
func (server *FileServer) Remove() {}
func (server *FileServer) Store(key string, r io.Reader) error {
// 1. Store this file to disk
// 2. Broadcast this file to all known peers in the network
var (
fileBuffer = new(bytes.Buffer)
tee = io.TeeReader(r, fileBuffer)
)
size, err := server.storage.Write(server.ID, key, tee)
if err != nil {
return nil
}
msg := Message{
Payload: MessageStoreFile{
ID: server.ID,
Key: hashKey(key),
Size: size + 16,
},
}
if err = server.broadcast(&msg); err != nil {
return err
}
time.Sleep(time.Millisecond * 5)
peers := []io.Writer{}
for _, peer := range server.peers {
peers = append(peers, peer)
}
mw := io.MultiWriter(peers...)
mw.Write([]byte{p2p.IncomingStream})
n, err := copyEncrypt(server.EncKey, fileBuffer, mw)
if err != nil {
return err
}
fmt.Printf("[%s] received and written (%d) bytes to disk\n", server.Transport.ListenAddr(), n)
return nil
}
func (server *FileServer) Stop() {
close(server.quitch)
}
func (server *FileServer) OnPeer(p p2p.Peer) error {
server.peerLock.Lock()
defer server.peerLock.Unlock()
server.peers[p.RemoteAddr().String()] = p
log.Printf("connected with remote %s", p.RemoteAddr())
return nil
}
func (server *FileServer) loop() {
defer func() {
log.Println("file server stopped due to error user quit action")
server.Transport.Close()
}()
for {
select {
case rpc := <-server.Transport.Consume():
var msg Message
if err := gob.NewDecoder(bytes.NewReader(rpc.Payload)).Decode(&msg); err != nil {
log.Println("decoding error: ", err)
}
if err := server.handleMessage(rpc.From, &msg); err != nil {
log.Println("handle message error: ", err)
}
case <-server.quitch:
return
}
}
}
func (server *FileServer) handleMessage(from string, msg *Message) error {
switch v := msg.Payload.(type) {
case MessageStoreFile:
return server.handleMessageStoreFile(from, v)
case MessageGetFile:
return server.handleMessageGetFile(from, v)
}
return nil
}
func (server *FileServer) handleMessageGetFile(from string, msg MessageGetFile) error {
if !server.storage.Has(msg.ID, msg.Key) {
return fmt.Errorf("[%s] need to serve file (%s) but it doesn't exist on disk", server.Transport.ListenAddr(), msg.Key)
}
fmt.Printf("[%s] serving file (%s) over the network\n", server.Transport.ListenAddr(), msg.Key)
fileSize, r, err := server.storage.Read(msg.ID, msg.Key)
if err != nil {
return err
}
if re, ok := r.(io.ReadCloser); ok {
fmt.Println("closing readCloser")
defer re.Close()
}
peer, ok := server.peers[from]
if !ok {
return fmt.Errorf("peer %s not in map", from)
}
/* first send "incomingstream" byte to the peer and
then we can send the file size as an int64 */
peer.Send([]byte{p2p.IncomingStream})
binary.Write(peer, binary.LittleEndian, fileSize)
n, err := io.Copy(peer, r)
if err != nil {
return err
}
fmt.Printf("[%s] written (%d) bytes over the network to %s\n", server.Transport.ListenAddr(), n, from)
return nil
}
func (server *FileServer) handleMessageStoreFile(from string, msg MessageStoreFile) error {
peer, ok := server.peers[from]
if !ok {
return fmt.Errorf("peer (%s) could not be found in the peer list", from)
}
n, err := server.storage.Write(msg.ID, msg.Key, io.LimitReader(peer, msg.Size))
if err != nil {
return err
}
fmt.Printf("[%s] written %d bytes to disk\n", server.Transport.ListenAddr(), n)
peer.CloseStream()
return nil
}
func (server *FileServer) bootstrapNetwork() error {
for _, addr := range server.BootstrapNodes {
if len(addr) == 0 {
continue
}
go func(addr string) {
fmt.Printf("[%s] attempting to connect with remote %s\n", server.Transport.ListenAddr(), addr)
if err := server.Transport.Dial(addr); err != nil {
log.Println("dial error: ", err)
}
}(addr)
}
return nil
}
func (server *FileServer) Start() error {
fmt.Printf("[%s] starting fileserver...\n", server.Transport.ListenAddr())
if err := server.Transport.ListenAndAccept(); err != nil {
return err
}
server.bootstrapNetwork()
server.loop()
return nil
}
func init() {
gob.Register(MessageStoreFile{})
gob.Register(MessageGetFile{})
}