-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
304 lines (239 loc) · 6.12 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
package main
import (
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"io"
"log"
"sync"
"time"
"github.com/anthdm/foreverstore/p2p"
)
type FileServerOpts struct {
ID string
EncKey []byte
StorageRoot string
PathTransformFunc PathTransformFunc
Transport p2p.Transport
BootstrapNodes []string
}
type FileServer struct {
FileServerOpts
peerLock sync.Mutex
peers map[string]p2p.Peer
store *Store
quitch chan struct{}
}
func NewFileServer(opts FileServerOpts) *FileServer {
storeOpts := StoreOpts{
Root: opts.StorageRoot,
PathTransformFunc: opts.PathTransformFunc,
}
if len(opts.ID) == 0 {
opts.ID = generateID()
}
return &FileServer{
FileServerOpts: opts,
store: NewStore(storeOpts),
quitch: make(chan struct{}),
peers: make(map[string]p2p.Peer),
}
}
func (s *FileServer) broadcast(msg *Message) error {
buf := new(bytes.Buffer)
if err := gob.NewEncoder(buf).Encode(msg); err != nil {
return err
}
for _, peer := range s.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 (s *FileServer) Get(key string) (io.Reader, error) {
if s.store.Has(s.ID, key) {
fmt.Printf("[%s] serving file (%s) from local disk\n", s.Transport.Addr(), key)
_, r, err := s.store.Read(s.ID, key)
return r, err
}
fmt.Printf("[%s] dont have file (%s) locally, fetching from network...\n", s.Transport.Addr(), key)
msg := Message{
Payload: MessageGetFile{
ID: s.ID,
Key: hashKey(key),
},
}
if err := s.broadcast(&msg); err != nil {
return nil, err
}
time.Sleep(time.Millisecond * 500)
for _, peer := range s.peers {
// First read the file size so we can limit the amount of bytes that we read
// from the connection, so it will not keep hanging.
var fileSize int64
binary.Read(peer, binary.LittleEndian, &fileSize)
n, err := s.store.WriteDecrypt(s.EncKey, s.ID, key, io.LimitReader(peer, fileSize))
if err != nil {
return nil, err
}
fmt.Printf("[%s] received (%d) bytes over the network from (%s)", s.Transport.Addr(), n, peer.RemoteAddr())
peer.CloseStream()
}
_, r, err := s.store.Read(s.ID, key)
return r, err
}
func (s *FileServer) Store(key string, r io.Reader) error {
var (
fileBuffer = new(bytes.Buffer)
tee = io.TeeReader(r, fileBuffer)
)
size, err := s.store.Write(s.ID, key, tee)
if err != nil {
return err
}
msg := Message{
Payload: MessageStoreFile{
ID: s.ID,
Key: hashKey(key),
Size: size + 16,
},
}
if err := s.broadcast(&msg); err != nil {
return err
}
time.Sleep(time.Millisecond * 5)
peers := []io.Writer{}
for _, peer := range s.peers {
peers = append(peers, peer)
}
mw := io.MultiWriter(peers...)
mw.Write([]byte{p2p.IncomingStream})
n, err := copyEncrypt(s.EncKey, fileBuffer, mw)
if err != nil {
return err
}
fmt.Printf("[%s] received and written (%d) bytes to disk\n", s.Transport.Addr(), n)
return nil
}
func (s *FileServer) Stop() {
close(s.quitch)
}
func (s *FileServer) OnPeer(p p2p.Peer) error {
s.peerLock.Lock()
defer s.peerLock.Unlock()
s.peers[p.RemoteAddr().String()] = p
log.Printf("connected with remote %s", p.RemoteAddr())
return nil
}
func (s *FileServer) loop() {
defer func() {
log.Println("file server stopped due to error or user quit action")
s.Transport.Close()
}()
for {
select {
case rpc := <-s.Transport.Consume():
var msg Message
if err := gob.NewDecoder(bytes.NewReader(rpc.Payload)).Decode(&msg); err != nil {
log.Println("decoding error: ", err)
}
if err := s.handleMessage(rpc.From, &msg); err != nil {
log.Println("handle message error: ", err)
}
case <-s.quitch:
return
}
}
}
func (s *FileServer) handleMessage(from string, msg *Message) error {
switch v := msg.Payload.(type) {
case MessageStoreFile:
return s.handleMessageStoreFile(from, v)
case MessageGetFile:
return s.handleMessageGetFile(from, v)
}
return nil
}
func (s *FileServer) handleMessageGetFile(from string, msg MessageGetFile) error {
if !s.store.Has(msg.ID, msg.Key) {
return fmt.Errorf("[%s] need to serve file (%s) but it does not exist on disk", s.Transport.Addr(), msg.Key)
}
fmt.Printf("[%s] serving file (%s) over the network\n", s.Transport.Addr(), msg.Key)
fileSize, r, err := s.store.Read(msg.ID, msg.Key)
if err != nil {
return err
}
if rc, ok := r.(io.ReadCloser); ok {
fmt.Println("closing readCloser")
defer rc.Close()
}
peer, ok := s.peers[from]
if !ok {
return fmt.Errorf("peer %s not in map", from)
}
// First send the "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", s.Transport.Addr(), n, from)
return nil
}
func (s *FileServer) handleMessageStoreFile(from string, msg MessageStoreFile) error {
peer, ok := s.peers[from]
if !ok {
return fmt.Errorf("peer (%s) could not be found in the peer list", from)
}
n, err := s.store.Write(msg.ID, msg.Key, io.LimitReader(peer, msg.Size))
if err != nil {
return err
}
fmt.Printf("[%s] written %d bytes to disk\n", s.Transport.Addr(), n)
peer.CloseStream()
return nil
}
func (s *FileServer) bootstrapNetwork() error {
for _, addr := range s.BootstrapNodes {
if len(addr) == 0 {
continue
}
go func(addr string) {
fmt.Printf("[%s] attemping to connect with remote %s\n", s.Transport.Addr(), addr)
if err := s.Transport.Dial(addr); err != nil {
log.Println("dial error: ", err)
}
}(addr)
}
return nil
}
func (s *FileServer) Start() error {
fmt.Printf("[%s] starting fileserver...\n", s.Transport.Addr())
if err := s.Transport.ListenAndAccept(); err != nil {
return err
}
s.bootstrapNetwork()
s.loop()
return nil
}
func init() {
gob.Register(MessageStoreFile{})
gob.Register(MessageGetFile{})
}