scons build fixup
[swift-upb.git] / swift.h
1 /*
2  *  swift.h
3  *  the main header file for libswift, normally you should only read this one
4  *
5  *  Created by Victor Grishchenko on 3/6/09.
6  *  Copyright 2009 Delft University of Technology. All rights reserved.
7  *
8  */
9 /*
10
11 The swift protocol
12
13 Messages
14
15  HANDSHAKE    00, channelid
16  Communicates the channel id of the sender. The
17  initial handshake packet also has the root hash
18  (a HASH message).
19
20  DATA        01, bin_32, buffer
21  1K of data.
22
23  ACK        02, bin_32
24  ACKTS      08, bin_32, timestamp_32
25  Confirms successfull delivery of data. Used for
26  congestion control, as well.
27
28  HINT        03, bin_32
29  Practical value of "hints" is to avoid overlap, mostly.
30  Hints might be lost in the network or ignored.
31  Peer might send out data without a hint.
32  Hint which was not responded (by DATA) in some RTTs
33  is considered to be ignored.
34  As peers cant pick randomly kilobyte here and there,
35  they send out "long hints" for non-base bins.
36
37  HASH        04, bin_32, sha1hash
38  SHA1 hash tree hashes for data verification. The
39  connection to a fresh peer starts with bootstrapping
40  him with peak hashes. Later, before sending out
41  any data, a peer sends the necessary uncle hashes.
42
43  PEX+/PEX-    05/06, ipv4 addr, port
44  Peer exchange messages; reports all connected and
45  disconected peers. Might has special meaning (as
46  in the case with swarm supervisors).
47
48 */
49 #ifndef SWIFT_H
50 #define SWIFT_H
51
52 #include <deque>
53 #include <vector>
54 #include <algorithm>
55 #include <string>
56 #include "bin64.h"
57 #include "bins.h"
58 #include "datagram.h"
59 #include "hashtree.h"
60
61 namespace swift {
62
63     #define NOW Datagram::now
64     
65     /** tintbin is basically a pair<tint,bin64_t> plus some nice operators.
66         Most frequently used in different queues (acknowledgements, requests, 
67         etc). */
68     struct tintbin {
69         tint    time;
70         bin64_t bin;
71         tintbin(const tintbin& b) : time(b.time), bin(b.bin) {}
72         tintbin() : time(TINT_NEVER), bin(bin64_t::NONE) {}
73         tintbin(tint time_, bin64_t bin_) : time(time_), bin(bin_) {}
74         tintbin(bin64_t bin_) : time(NOW), bin(bin_) {}
75         bool operator < (const tintbin& b) const 
76             { return time > b.time; }
77         bool operator == (const tintbin& b) const
78             { return time==b.time && bin==b.bin; }
79         bool operator != (const tintbin& b) const
80             { return !(*this==b); }
81     };
82
83     typedef std::deque<tintbin> tbqueue;
84     typedef std::deque<bin64_t> binqueue;
85     typedef Address   Address;
86
87     /** A heap (priority queue) for timestamped bin numbers (tintbins). */
88     class tbheap {
89         tbqueue data_;
90     public:
91         int size () const { return data_.size(); }
92         bool is_empty () const { return data_.empty(); }
93         tintbin         pop() {
94             tintbin ret = data_.front();
95             std::pop_heap(data_.begin(),data_.end());
96             data_.pop_back();
97             return ret;
98         }
99         void            push(const tintbin& tb) {
100             data_.push_back(tb);
101             push_heap(data_.begin(),data_.end());
102         }
103         const tintbin&  peek() const {
104             return data_.front();
105         }
106     };
107
108     /** swift protocol message types; these are used on the wire. */
109     typedef enum {
110         SWIFT_HANDSHAKE = 0,
111         SWIFT_DATA = 1,
112         SWIFT_ACK = 2,
113         SWIFT_TS = 8,
114         SWIFT_HINT = 3,
115         SWIFT_HASH = 4,
116         SWIFT_PEX_ADD = 5,
117         SWIFT_PEX_RM = 6,
118         SWIFT_SIGNED_HASH = 7,
119         SWIFT_MSGTYPE_SENT = 8,
120         SWIFT_MSGTYPE_RCVD = 9,
121         SWIFT_MESSAGE_COUNT = 10
122     } messageid_t;
123
124     class PiecePicker;
125     class CongestionController;
126     class PeerSelector;
127
128
129     /** A class representing single file transfer. */
130     class    FileTransfer {
131
132     public:
133
134         /** A constructor. Open/submit/retrieve a file. 
135          *  @param file_name    the name of the file 
136          *  @param root_hash    the root hash of the file; zero hash if the file
137                                 is newly submitted */
138         FileTransfer(const char *file_name, const Sha1Hash& root_hash=Sha1Hash::ZERO);
139
140         /**    Close everything. */
141         ~FileTransfer();
142
143
144         /** While we need to feed ACKs to every peer, we try (1) avoid
145             unnecessary duplication and (2) keep minimum state. Thus,
146             we use a rotating queue of bin completion events. */
147         //bin64_t         RevealAck (uint64_t& offset);
148         /** Rotating queue read for channels of this transmission. */
149         int             RevealChannel (int& i);
150
151         /** Find transfer by the root hash. */
152         static FileTransfer* Find (const Sha1Hash& hash);
153         /** Find transfer by the file descriptor. */
154         static FileTransfer* file (int fd) {
155             return fd<files.size() ? files[fd] : NULL;
156         }
157
158         /** The binmap for data already retrieved and checked. */
159         binmap_t&           ack_out ()  { return file_.ack_out(); }
160         /** Piece picking strategy used by this transfer. */
161         PiecePicker&    picker () { return *picker_; }
162         /** The number of channels working for this transfer. */
163         int             channel_count () const { return hs_in_.size(); }
164         /** Hash tree checked file; all the hashes and data are kept here. */
165         HashTree&       file() { return file_; }
166         /** File descriptor for the data file. */
167         int             fd () const { return file_.file_descriptor(); }
168         /** Root SHA1 hash of the transfer (and the data file). */
169         const Sha1Hash& root_hash () const { return file_.root_hash(); }
170
171     private:
172
173         static std::vector<FileTransfer*> files;
174
175         HashTree        file_;
176
177         /** Piece picker strategy. */
178         PiecePicker*    picker_;
179
180         /** Channels working for this transfer. */
181         binqueue        hs_in_;
182         int             hs_in_offset_;
183         std::deque<Address> pex_in_;
184
185         /** Messages we are accepting.    */
186         uint64_t        cap_out_;
187         
188         tint            init_time_;
189
190     public:
191         void            OnDataIn (bin64_t pos);
192         void            OnPexIn (const Address& addr);
193
194         friend class Channel;
195         friend uint64_t  Size (int fdes);
196         friend bool      IsComplete (int fdes);
197         friend uint64_t  Complete (int fdes);
198         friend uint64_t  SeqComplete (int fdes);
199         friend int     Open (const char* filename, const Sha1Hash& hash) ;
200         friend void    Close (int fd) ;
201     };
202
203
204     /** PiecePicker implements some strategy of choosing (picking) what
205         to request next, given the possible range of choices:
206         data acknowledged by the peer minus data already retrieved.
207         May pick sequentially, do rarest first or in some other way. */
208     class PiecePicker {
209     public:
210         virtual void Randomize (uint64_t twist) = 0;
211         /** The piece picking method itself.
212          *  @param  offered     the daata acknowledged by the peer 
213          *  @param  max_width   maximum number of packets to ask for
214          *  @param  expires     (not used currently) when to consider request expired
215          *  @return             the bin number to request */
216         virtual bin64_t Pick (binmap_t& offered, uint64_t max_width, tint expires) = 0;
217         virtual ~PiecePicker() {}
218     };
219
220
221     class PeerSelector {
222     public:
223         virtual void AddPeer (const Address& addr, const Sha1Hash& root) = 0;
224         virtual Address GetPeer (const Sha1Hash& for_root) = 0;
225     };
226
227
228     class DataStorer {
229     public:
230         DataStorer (const Sha1Hash& id, size_t size);
231         virtual size_t    ReadData (bin64_t pos,uint8_t** buf) = 0;
232         virtual size_t    WriteData (bin64_t pos, uint8_t* buf, size_t len) = 0;
233     };
234
235
236     /**    swift channel's "control block"; channels loosely correspond to TCP
237         connections or FTP sessions; one channel is created for one file
238         being transferred between two peers. As we don't need buffers and
239         lots of other TCP stuff, sizeof(Channel+members) must be below 1K.
240         Normally, API users do not deal with this class. */
241     class Channel {  
242     public:
243         Channel    (FileTransfer* file, int socket=-1, Address peer=Address());
244         ~Channel();
245         
246         typedef enum {
247             KEEP_ALIVE_CONTROL,
248             PING_PONG_CONTROL,
249             SLOW_START_CONTROL,
250             AIMD_CONTROL,
251             LEDBAT_CONTROL,
252             CLOSE_CONTROL
253         } send_control_t;
254         
255         static const char* SEND_CONTROL_MODES[];
256
257         static Channel*
258                     RecvDatagram (int socket);
259         static void Loop (tint till);
260
261         void        Recv (Datagram& dgram);
262         void        Send ();
263         void        Close ();
264
265         void        OnAck (Datagram& dgram);
266         void        OnTs (Datagram& dgram);
267         bin64_t     OnData (Datagram& dgram);
268         void        OnHint (Datagram& dgram);
269         void        OnHash (Datagram& dgram);
270         void        OnPex (Datagram& dgram);
271         void        OnHandshake (Datagram& dgram);
272         void        AddHandshake (Datagram& dgram);
273         bin64_t     AddData (Datagram& dgram);
274         void        AddAck (Datagram& dgram);
275         void        AddTs (Datagram& dgram);
276         void        AddHint (Datagram& dgram);
277         void        AddUncleHashes (Datagram& dgram, bin64_t pos);
278         void        AddPeakHashes (Datagram& dgram);
279         void        AddPex (Datagram& dgram);
280
281         void        BackOffOnLosses (float ratio=0.5);
282         tint        SwitchSendControl (int control_mode);
283         tint        NextSendTime ();
284         tint        KeepAliveNextSendTime ();
285         tint        PingPongNextSendTime ();
286         tint        CwndRateNextSendTime ();
287         tint        SlowStartNextSendTime ();
288         tint        AimdNextSendTime ();
289         tint        LedbatNextSendTime ();
290         
291         static int  MAX_REORDERING;
292         static tint TIMEOUT;
293         static tint MIN_DEV;
294         static tint MAX_SEND_INTERVAL;
295         static tint LEDBAT_TARGET;
296         static float LEDBAT_GAIN;
297         static tint LEDBAT_DELAY_BIN;
298         static bool SELF_CONN_OK;
299         static tint MAX_POSSIBLE_RTT;
300         static FILE* debug_file;
301         
302         const std::string id_string () const;
303         /** A channel is "established" if had already sent and received packets. */
304         bool        is_established () { return peer_channel_id_ && own_id_mentioned_; }
305         FileTransfer& transfer() { return *transfer_; }
306         HashTree&   file () { return transfer_->file(); }
307         const Address& peer() const { return peer_; }
308         tint ack_timeout () {
309                         tint dev = dev_avg_ < MIN_DEV ? MIN_DEV : dev_avg_;
310                         tint tmo = rtt_avg_ + dev * 4;
311                         return tmo < 30*TINT_SEC ? tmo : 30*TINT_SEC; 
312         }
313         uint32_t    id () const { return id_; }
314         
315         static int  DecodeID(int scrambled);
316         static int  EncodeID(int unscrambled);
317         static Channel* channel(int i) {
318             return i<channels.size()?channels[i]:NULL;
319         }
320         static void CloseTransfer (FileTransfer* trans);
321         static SOCKET default_socket() { return sockets[0]; }
322
323     protected:
324         /** Channel id: index in the channel array. */
325         uint32_t    id_;
326         /**    Socket address of the peer. */
327         Address     peer_;
328         /**    The UDP socket fd. */
329         SOCKET      socket_;
330         /**    Descriptor of the file in question. */
331         FileTransfer*    transfer_;
332         /**    Peer channel id; zero if we are trying to open a channel. */
333         uint32_t    peer_channel_id_;
334         bool        own_id_mentioned_;
335         /**    Peer's progress, based on acknowledgements. */
336         binmap_t        ack_in_;
337         /**    Last data received; needs to be acked immediately. */
338         tintbin     data_in_;
339         bin64_t     data_in_dbl_;
340         /** The history of data sent and still unacknowledged. */
341         tbqueue     data_out_;
342         /** Timeouted data (potentially to be retransmitted). */
343         tbqueue     data_out_tmo_;
344         bin64_t     data_out_cap_;
345         /** Index in the history array. */
346         binmap_t        ack_out_;
347         /**    Transmit schedule: in most cases filled with the peer's hints */
348         tbqueue     hint_in_;
349         /** Hints sent (to detect and reschedule ignored hints). */
350         tbqueue     hint_out_;
351         uint64_t    hint_out_size_;
352         /** Types of messages the peer accepts. */
353         uint64_t    cap_in_;
354         /** For repeats. */
355         //tint        last_send_time, last_recv_time;
356         /** PEX progress */
357         int         pex_out_;
358         /** Smoothed averages for RTT, RTT deviation and data interarrival periods. */
359         tint        rtt_avg_, dev_avg_, dip_avg_;
360         tint        last_send_time_;
361         tint        last_recv_time_;
362         tint        last_data_out_time_;
363         tint        last_data_in_time_;
364         tint        last_loss_time_;
365         tint        next_send_time_;
366         tint        peer_send_time_;
367         /** Congestion window; TODO: int, bytes. */
368         float       cwnd_;
369         /** Data sending interval. */
370         tint        send_interval_;
371         /** The congestion control strategy. */
372         int         send_control_;
373         /** Datagrams (not data) sent since last recv.    */
374         int         sent_since_recv_;
375         /** Recent acknowlegements for data previously sent.    */
376         int         ack_rcvd_recent_;
377         /** Recent non-acknowlegements (losses) of data previously sent.    */
378         int         ack_not_rcvd_recent_;
379         /** LEDBAT one-way delay machinery */
380         tint        owd_min_bins_[4];
381         int         owd_min_bin_;
382         tint        owd_min_bin_start_;
383         tint        owd_current_[4];
384         int         owd_cur_bin_;
385         /** Stats */
386         int         dgrams_sent_;
387         int         dgrams_rcvd_;
388
389         int         PeerBPS() const {
390             return TINT_SEC / dip_avg_ * 1024;
391         }
392         /** Get a request for one packet from the queue of peer's requests. */
393         bin64_t     DequeueHint();
394         void        CleanDataOut (bin64_t acks_pos=bin64_t::NONE);
395         void        CleanStaleHintOut();
396         void        CleanHintOut(bin64_t pos);
397         void        Reschedule();
398
399         static PeerSelector* peer_selector;
400
401         static SOCKET   sockets[8];
402         static int      socket_count;
403         static tint     last_tick;
404         static tbheap   send_queue;        
405
406         static Address  tracker;
407         static std::vector<Channel*> channels;
408
409         friend int      Listen (Address addr);
410         friend void     Shutdown (int sock_des);
411         friend void     AddPeer (Address address, const Sha1Hash& root);
412         friend void     SetTracker(const Address& tracker);
413         friend int      Open (const char*, const Sha1Hash&) ; // FIXME
414
415     };
416
417
418
419     /*************** The top-level API ****************/
420     /** Start listening a port. Returns socket descriptor. */
421     int     Listen (Address addr);
422     /** Run send/receive loop for the specified amount of time. */
423     void    Loop (tint till);
424     /** Stop listening to a port. */
425     void    Shutdown (int sock_des=-1);
426
427     /** Open a file, start a transmission; fill it with content for a given root hash;
428         in case the hash is omitted, the file is a fresh submit. */
429     int     Open (const char* filename, const Sha1Hash& hash=Sha1Hash::ZERO) ;
430     /** Get the root hash for the transmission. */
431     const Sha1Hash& RootMerkleHash (int file) ;
432     /** Close a file and a transmission. */
433     void    Close (int fd) ;
434     /** Add a possible peer which participares in a given transmission. In the case
435         root hash is zero, the peer might be talked to regarding any transmission
436         (likely, a tracker, cache or an archive). */
437     void    AddPeer (Address address, const Sha1Hash& root=Sha1Hash::ZERO);
438
439     void    SetTracker(const Address& tracker);
440
441     /** Returns size of the file in bytes, 0 if unknown. Might be rounded up to a kilobyte
442         before the transmission is complete. */
443     uint64_t  Size (int fdes);
444     /** Returns the amount of retrieved and verified data, in bytes.
445         A 100% complete transmission has Size()==Complete(). */
446     uint64_t  Complete (int fdes);
447     bool      IsComplete (int fdes);
448     /** Returns the number of bytes that are complete sequentially, starting from the
449         beginning, till the first not-yet-retrieved packet. */
450     uint64_t  SeqComplete (int fdes);
451
452
453     //uint32_t Width (const tbinvec& v);
454
455
456     /** Must be called by any client using the library */
457     void LibraryInit(void);
458
459
460 } // namespace end
461
462 #ifndef SWIFT_MUTE
463 #define dprintf(...) { if (Channel::debug_file) fprintf(Channel::debug_file,__VA_ARGS__); }
464 #else
465 #define dprintf(...) {}
466 #endif
467 #define eprintf(...) fprintf(stderr,__VA_ARGS__)
468
469 #endif