Add files for swift over UDP.
[swifty.git] / src / libswift_udp / 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-2012 TECHNISCHE UNIVERSITEIT DELFT. 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, timestamp_32
24   HAVE       03, bin_32
25   Confirms successfull delivery of data. Used for
26   congestion control, as well.
27
28   HINT        08, 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 <set>
55 #include <algorithm>
56 #include <string>
57 #include <math.h>
58
59 #include "compat.h"
60 #include <event2/event.h>
61 #include <event2/event_struct.h>
62 #include <event2/buffer.h>
63 #include "bin.h"
64 #include "binmap.h"
65 #include "hashtree.h"
66 #include "avgspeed.h"
67 #include "availability.h"
68
69
70 namespace swift {
71
72 #define SWIFT_MAX_UDP_OVER_ETH_PAYLOAD          (1500-20-8)
73 // Arno: Maximum size of non-DATA messages in a UDP packet we send.
74 #define SWIFT_MAX_NONDATA_DGRAM_SIZE            (SWIFT_MAX_UDP_OVER_ETH_PAYLOAD-SWIFT_DEFAULT_CHUNK_SIZE-1-4)
75 // Arno: Maximum size of a UDP packet we send. Note: depends on CHUNKSIZE 8192
76 #define SWIFT_MAX_SEND_DGRAM_SIZE                       (SWIFT_MAX_NONDATA_DGRAM_SIZE+1+4+8192)
77 // Arno: Maximum size of a UDP packet we are willing to accept. Note: depends on CHUNKSIZE 8192
78 #define SWIFT_MAX_RECV_DGRAM_SIZE                       (SWIFT_MAX_SEND_DGRAM_SIZE*2)
79
80 #define layer2bytes(ln,cs)      (uint64_t)( ((double)cs)*pow(2.0,(double)ln))
81 #define bytes2layer(bn,cs)  (int)log2(  ((double)bn)/((double)cs) )
82
83 // Arno, 2011-12-22: Enable Riccardo's VodPiecePicker
84 #define ENABLE_VOD_PIECEPICKER          1
85
86
87 /** IPv4 address, just a nice wrapping around struct sockaddr_in. */
88     struct Address {
89         struct sockaddr_in  addr;
90         static uint32_t LOCALHOST;
91         void set_port (uint16_t port) {
92             addr.sin_port = htons(port);
93         }
94         void set_port (const char* port_str) {
95             int p;
96             if (sscanf(port_str,"%i",&p))
97                 set_port(p);
98         }
99         void set_ipv4 (uint32_t ipv4) {
100             addr.sin_addr.s_addr = htonl(ipv4);
101         }
102         void set_ipv4 (const char* ipv4_str) ;
103         //{    inet_aton(ipv4_str,&(addr.sin_addr));    }
104         void clear () {
105             memset(&addr,0,sizeof(struct sockaddr_in));
106             addr.sin_family = AF_INET;
107         }
108         Address() {
109             clear();
110         }
111         Address(const char* ip, uint16_t port)  {
112             clear();
113             set_ipv4(ip);
114             set_port(port);
115         }
116         Address(const char* ip_port);
117         Address(uint16_t port) {
118             clear();
119             set_ipv4((uint32_t)INADDR_ANY);
120             set_port(port);
121         }
122         Address(uint32_t ipv4addr, uint16_t port) {
123             clear();
124             set_ipv4(ipv4addr);
125             set_port(port);
126         }
127         Address(const struct sockaddr_in& address) : addr(address) {}
128         uint32_t ipv4 () const { return ntohl(addr.sin_addr.s_addr); }
129         uint16_t port () const { return ntohs(addr.sin_port); }
130         operator sockaddr_in () const {return addr;}
131         bool operator == (const Address& b) const {
132             return addr.sin_family==b.addr.sin_family &&
133                 addr.sin_port==b.addr.sin_port &&
134                 addr.sin_addr.s_addr==b.addr.sin_addr.s_addr;
135         }
136         const char* str () const {
137                 // Arno, 2011-10-04: not thread safe, replace.
138             static char rs[4][32];
139             static int i;
140             i = (i+1) & 3;
141             sprintf(rs[i],"%i.%i.%i.%i:%i",ipv4()>>24,(ipv4()>>16)&0xff,
142                     (ipv4()>>8)&0xff,ipv4()&0xff,port());
143             return rs[i];
144         }
145         const char* ipv4str () const {
146                 // Arno, 2011-10-04: not thread safe, replace.
147             static char rs[4][32];
148             static int i;
149             i = (i+1) & 3;
150             sprintf(rs[i],"%i.%i.%i.%i",ipv4()>>24,(ipv4()>>16)&0xff,
151                     (ipv4()>>8)&0xff,ipv4()&0xff);
152             return rs[i];
153         }
154         bool operator != (const Address& b) const { return !(*this==b); }
155         bool is_private() const {
156                 // TODO IPv6
157                 uint32_t no = ipv4(); uint8_t no0 = no>>24,no1 = (no>>16)&0xff;
158                 if (no0 == 10) return true;
159                 else if (no0 == 172 && no1 >= 16 && no1 <= 31) return true;
160                 else if (no0 == 192 && no1 == 168) return true;
161                 else return false;
162         }
163     };
164
165 // Arno, 2011-10-03: Use libevent callback functions, no on_error?
166 #define sockcb_t                event_callback_fn
167     struct sckrwecb_t {
168         sckrwecb_t (evutil_socket_t s=0, sockcb_t mr=NULL, sockcb_t mw=NULL,
169                     sockcb_t oe=NULL) :
170             sock(s), may_read(mr), may_write(mw), on_error(oe) {}
171         evutil_socket_t sock;
172         sockcb_t   may_read;
173         sockcb_t   may_write;
174         sockcb_t   on_error;
175     };
176
177     struct now_t  {
178         static tint now;
179     };
180
181 #define NOW now_t::now
182
183     /** tintbin is basically a pair<tint,bin64_t> plus some nice operators.
184         Most frequently used in different queues (acknowledgements, requests,
185         etc). */
186     struct tintbin {
187         tint    time;
188         bin_t bin;
189         tintbin(const tintbin& b) : time(b.time), bin(b.bin) {}
190         tintbin() : time(TINT_NEVER), bin(bin_t::NONE) {}
191         tintbin(tint time_, bin_t bin_) : time(time_), bin(bin_) {}
192         tintbin(bin_t bin_) : time(NOW), bin(bin_) {}
193         bool operator < (const tintbin& b) const
194                         { return time > b.time; }
195         bool operator == (const tintbin& b) const
196                         { return time==b.time && bin==b.bin; }
197         bool operator != (const tintbin& b) const
198                         { return !(*this==b); }
199     };
200
201     typedef std::deque<tintbin> tbqueue;
202     typedef std::deque<bin_t> binqueue;
203     typedef Address   Address;
204
205     /** A heap (priority queue) for timestamped bin numbers (tintbins). */
206     class tbheap {
207         tbqueue data_;
208     public:
209         int size () const { return data_.size(); }
210         bool is_empty () const { return data_.empty(); }
211         tintbin         pop() {
212             tintbin ret = data_.front();
213             std::pop_heap(data_.begin(),data_.end());
214             data_.pop_back();
215             return ret;
216         }
217         void            push(const tintbin& tb) {
218             data_.push_back(tb);
219             push_heap(data_.begin(),data_.end());
220         }
221         const tintbin&  peek() const {
222             return data_.front();
223         }
224     };
225
226     /** swift protocol message types; these are used on the wire. */
227     typedef enum {
228         SWIFT_HANDSHAKE = 0,
229         SWIFT_DATA = 1,
230         SWIFT_ACK = 2,
231         SWIFT_HAVE = 3,
232         SWIFT_HASH = 4,
233         SWIFT_PEX_ADD = 5,
234         SWIFT_PEX_REQ = 6,
235         SWIFT_SIGNED_HASH = 7,
236         SWIFT_HINT = 8,
237         SWIFT_MSGTYPE_RCVD = 9,
238         SWIFT_RANDOMIZE = 10, //FRAGRAND
239         SWIFT_VERSION = 11, // Arno, 2011-10-19: TODO to match RFC-rev-03
240         SWIFT_MESSAGE_COUNT = 12
241     } messageid_t;
242
243     typedef enum {
244         DDIR_UPLOAD,
245         DDIR_DOWNLOAD
246     } data_direction_t;
247
248     class PiecePicker;
249     //class CongestionController; // Arno: Currently part of Channel. See ::NextSendTime
250     class PeerSelector;
251     class Channel;
252     typedef void (*ProgressCallback) (int transfer, bin_t bin);
253
254     /** A class representing single file transfer. */
255     class    FileTransfer {
256
257     public:
258
259         /** A constructor. Open/submit/retrieve a file.
260          *  @param file_name    the name of the file
261          *  @param root_hash    the root hash of the file; zero hash if the file
262                  *                          is newly submitted
263                  */
264         FileTransfer(const char *file_name, const Sha1Hash& root_hash=Sha1Hash::ZERO,bool force_check_diskvshash=true,bool check_netwvshash=true,uint32_t chunk_size=SWIFT_DEFAULT_CHUNK_SIZE);
265
266         /**    Close everything. */
267         ~FileTransfer();
268
269
270         /** While we need to feed ACKs to every peer, we try (1) avoid
271             unnecessary duplication and (2) keep minimum state. Thus,
272             we use a rotating queue of bin completion events. */
273         //bin64_t         RevealAck (uint64_t& offset);
274         /** Rotating queue read for channels of this transmission. */
275         // Jori
276         int             RevealChannel (int& i);
277         // Gertjan
278         int             RandomChannel (int own_id);
279
280
281         /** Find transfer by the root hash. */
282         static FileTransfer* Find (const Sha1Hash& hash);
283         /** Find transfer by the file descriptor. */
284         static FileTransfer* file (int fd) {
285             return fd<files.size() ? files[fd] : NULL;
286         }
287
288         /** The binmap for data already retrieved and checked. */
289         binmap_t&           ack_out ()  { return file_.ack_out(); }
290         /** Piece picking strategy used by this transfer. */
291         PiecePicker&    picker () { return *picker_; }
292         /** The number of channels working for this transfer. */
293         int             channel_count () const { return hs_in_.size(); }
294         /** Hash tree checked file; all the hashes and data are kept here. */
295         HashTree&       file() { return file_; }
296         /** File descriptor for the data file. */
297         int             fd () const { return file_.file_descriptor(); }
298         /** Root SHA1 hash of the transfer (and the data file). */
299         const Sha1Hash& root_hash () const { return file_.root_hash(); }
300         /** Ric: the availability in the swarm */
301         Availability&   availability() { return *availability_; }
302
303                 // RATELIMIT
304         /** Arno: Call when n bytes are received. */
305         void                    OnRecvData(int n);
306         /** Arno: Call when n bytes are sent. */
307         void                    OnSendData(int n);
308         /** Arno: Call when no bytes are sent due to rate limiting. */
309         void                    OnSendNoData();
310         /** Arno: Return current speed for the given direction in bytes/s */
311                 double                  GetCurrentSpeed(data_direction_t ddir);
312                 /** Arno: Return maximum speed for the given direction in bytes/s */
313                 double                  GetMaxSpeed(data_direction_t ddir);
314                 /** Arno: Set maximum speed for the given direction in bytes/s */
315                 void                    SetMaxSpeed(data_direction_t ddir, double m);
316                 /** Arno: Return the number of non-seeders current channeled with. */
317                 uint32_t                GetNumLeechers();
318                 /** Arno: Return the number of seeders current channeled with. */
319                 uint32_t                GetNumSeeders();
320                 /** Arno: Return the set of Channels for this transfer. MORESTATS */
321                 std::set<Channel *> GetChannels() { return mychannels_; }
322
323                 /** Arno: set the tracker for this transfer. Reseting it won't kill
324                  * any existing connections.
325                  */
326                 void SetTracker(Address tracker) { tracker_ = tracker; }
327
328                 /** Arno: (Re)Connect to tracker for this transfer, or global Channel::tracker if not set */
329                 void ConnectToTracker();
330
331                 /** Arno: Reconnect to the tracker if no established peers and
332                  * exp backoff allows it.
333                  */
334                 void ReConnectToTrackerIfAllowed(bool hasestablishedpeers);
335
336                 /** Arno: Return the Channel to peer "addr" that is not equal to "notc". */
337                 Channel * FindChannel(const Address &addr, Channel *notc);
338
339                 // SAFECLOSE
340                 static void LibeventCleanCallback(int fd, short event, void *arg);
341     protected:
342
343         HashTree        file_;
344
345         /** Piece picker strategy. */
346         PiecePicker*    picker_;
347
348         /** Channels working for this transfer. */
349         binqueue        hs_in_;                 // Arno, 2011-10-03: Should really be queue of channel ID (=uint32_t)
350
351         /** Messages we are accepting.    */
352         uint64_t        cap_out_;
353
354         tint            init_time_;
355         
356         // Ric: PPPLUG
357         /** Availability in the swarm */
358         Availability*   availability_;
359
360 #define SWFT_MAX_TRANSFER_CB 8
361         ProgressCallback callbacks[SWFT_MAX_TRANSFER_CB];
362         uint8_t         cb_agg[SWFT_MAX_TRANSFER_CB];
363         int             cb_installed;
364
365                 // RATELIMIT
366         std::set<Channel *>     mychannels_; // Arno, 2012-01-31: May be duplicate of hs_in_
367         MovingAverageSpeed      cur_speed_[2];
368         double                          max_speed_[2];
369         int                                     speedzerocount_;
370
371         // SAFECLOSE
372         struct event            evclean_;
373
374         Address                         tracker_; // Tracker for this transfer
375         tint                            tracker_retry_interval_;
376         tint                            tracker_retry_time_;
377
378     public:
379         void            OnDataIn (bin_t pos);
380         // Gertjan fix: return bool
381         bool            OnPexIn (const Address& addr);
382
383         static std::vector<FileTransfer*> files;
384
385
386         friend class Channel;
387         // Ric: maybe not really needed
388         friend class Availability;
389         friend uint64_t  Size (int fdes);
390         friend bool      IsComplete (int fdes);
391         friend uint64_t  Complete (int fdes);
392         friend uint64_t  SeqComplete (int fdes);
393         friend int     Open (const char* filename, const Sha1Hash& hash, Address tracker, bool force_check_diskvshash, bool check_netwvshash, uint32_t chunk_size);
394         friend void    Close (int fd) ;
395         friend void AddProgressCallback (int transfer,ProgressCallback cb,uint8_t agg);
396         friend void RemoveProgressCallback (int transfer,ProgressCallback cb);
397         friend void ExternallyRetrieved (int transfer,bin_t piece);
398     };
399
400
401     /** PiecePicker implements some strategy of choosing (picking) what
402         to request next, given the possible range of choices:
403         data acknowledged by the peer minus data already retrieved.
404         May pick sequentially, do rarest first or in some other way. */
405     class PiecePicker {
406     public:
407         virtual void Randomize (uint64_t twist) = 0;
408         /** The piece picking method itself.
409          *  @param  offered     the data acknowledged by the peer
410          *  @param  max_width   maximum number of packets to ask for
411          *  @param  expires     (not used currently) when to consider request expired
412          *  @return             the bin number to request */
413         virtual bin_t Pick (binmap_t& offered, uint64_t max_width, tint expires) = 0;
414         virtual void LimitRange (bin_t range) = 0;
415         /** updates the playback position for streaming piece picking.
416          *  @param  amount              amount to increment in bin unit size (1KB default) */
417         virtual void updatePlaybackPos (int amount=1) = 0;
418         virtual ~PiecePicker() {}
419     };
420
421
422     class PeerSelector { // Arno: partically unused
423     public:
424         virtual void AddPeer (const Address& addr, const Sha1Hash& root) = 0;
425         virtual Address GetPeer (const Sha1Hash& for_root) = 0;
426     };
427
428
429     /* class DataStorer { // Arno: never implemented
430     public:
431         DataStorer (const Sha1Hash& id, size_t size);
432         virtual size_t    ReadData (bin_t pos,uint8_t** buf) = 0;
433         virtual size_t    WriteData (bin_t pos, uint8_t* buf, size_t len) = 0;
434     }; */
435
436
437     /**    swift channel's "control block"; channels loosely correspond to TCP
438            connections or FTP sessions; one channel is created for one file
439            being transferred between two peers. As we don't need buffers and
440            lots of other TCP stuff, sizeof(Channel+members) must be below 1K.
441            Normally, API users do not deal with this class. */
442     class Channel {
443
444 #define DGRAM_MAX_SOCK_OPEN 128
445         static int sock_count;
446         static sckrwecb_t sock_open[DGRAM_MAX_SOCK_OPEN];
447
448     public:
449         Channel    (FileTransfer* file, int socket=INVALID_SOCKET, Address peer=Address());
450         ~Channel();
451
452         typedef enum {
453             KEEP_ALIVE_CONTROL,
454             PING_PONG_CONTROL,
455             SLOW_START_CONTROL,
456             AIMD_CONTROL,
457             LEDBAT_CONTROL,
458             CLOSE_CONTROL
459         } send_control_t;
460
461         static Address  tracker; // Global tracker for all transfers
462         struct event *evsend_ptr_; // Arno: timer per channel // SAFECLOSE
463         static struct event_base *evbase;
464         static struct event evrecv;
465         static const char* SEND_CONTROL_MODES[];
466
467             static tint epoch, start;
468             static uint64_t global_dgrams_up, global_dgrams_down, global_raw_bytes_up, global_raw_bytes_down, global_bytes_up, global_bytes_down;
469         static void CloseChannelByAddress(const Address &addr);
470
471         // SOCKMGMT
472         // Arno: channel is also a "singleton" class that manages all sockets
473         // for a swift process
474         static void LibeventSendCallback(int fd, short event, void *arg);
475         static void LibeventReceiveCallback(int fd, short event, void *arg);
476         static void RecvDatagram (evutil_socket_t socket); // Called by LibeventReceiveCallback
477             static int RecvFrom(evutil_socket_t sock, Address& addr, struct evbuffer *evb); // Called by RecvDatagram
478             static int SendTo(evutil_socket_t sock, const Address& addr, struct evbuffer *evb); // Called by Channel::Send()
479             static evutil_socket_t Bind(Address address, sckrwecb_t callbacks=sckrwecb_t());
480             static Address BoundAddress(evutil_socket_t sock);
481             static evutil_socket_t default_socket()
482             { return sock_count ? sock_open[0].sock : INVALID_SOCKET; }
483
484             /** close the port */
485             static void CloseSocket(evutil_socket_t sock);
486             static void Shutdown ();
487             /** the current time */
488             static tint Time();
489
490             // Arno: Per instance methods
491         void        Recv (struct evbuffer *evb);
492         void        Send ();  // Called by LibeventSendCallback
493         void        Close ();
494
495         void        OnAck (struct evbuffer *evb);
496         void        OnHave (struct evbuffer *evb);
497         bin_t       OnData (struct evbuffer *evb);
498         void        OnHint (struct evbuffer *evb);
499         void        OnHash (struct evbuffer *evb);
500         void        OnPex (struct evbuffer *evb);
501         void        OnHandshake (struct evbuffer *evb);
502         void        OnRandomize (struct evbuffer *evb); //FRAGRAND
503         void        AddHandshake (struct evbuffer *evb);
504         bin_t       AddData (struct evbuffer *evb);
505         void        AddAck (struct evbuffer *evb);
506         void        AddHave (struct evbuffer *evb);
507         void        AddHint (struct evbuffer *evb);
508         void        AddUncleHashes (struct evbuffer *evb, bin_t pos);
509         void        AddPeakHashes (struct evbuffer *evb);
510         void        AddPex (struct evbuffer *evb);
511         void        OnPexReq(void);
512         void        AddPexReq(struct evbuffer *evb);
513         void        BackOffOnLosses (float ratio=0.5);
514         tint        SwitchSendControl (int control_mode);
515         tint        NextSendTime ();
516         tint        KeepAliveNextSendTime ();
517         tint        PingPongNextSendTime ();
518         tint        CwndRateNextSendTime ();
519         tint        SlowStartNextSendTime ();
520         tint        AimdNextSendTime ();
521         tint        LedbatNextSendTime ();
522         /** Arno: return true if this peer has complete file. May be fuzzy if Peak Hashes not in */
523         bool            IsComplete();
524         /** Arno: return (UDP) port for this channel */
525         uint16_t        GetMyPort();
526         bool            IsDiffSenderOrDuplicate(Address addr, uint32_t chid);
527
528         static int  MAX_REORDERING;
529         static tint TIMEOUT;
530         static tint MIN_DEV;
531         static tint MAX_SEND_INTERVAL;
532         static tint LEDBAT_TARGET;
533         static float LEDBAT_GAIN;
534         static tint LEDBAT_DELAY_BIN;
535         static bool SELF_CONN_OK;
536         static tint MAX_POSSIBLE_RTT;
537         static tint MIN_PEX_REQUEST_INTERVAL;
538         static FILE* debug_file;
539
540         const std::string id_string () const;
541         /** A channel is "established" if had already sent and received packets. */
542         bool        is_established () { return peer_channel_id_ && own_id_mentioned_; }
543         FileTransfer& transfer() { return *transfer_; }
544         HashTree&   file () { return transfer_->file(); }
545         const Address& peer() const { return peer_; }
546         const Address& recv_peer() const { return recv_peer_; }
547         tint ack_timeout () {
548                 tint dev = dev_avg_ < MIN_DEV ? MIN_DEV : dev_avg_;
549                 tint tmo = rtt_avg_ + dev * 4;
550                 return tmo < 30*TINT_SEC ? tmo : 30*TINT_SEC;
551         }
552         uint32_t    id () const { return id_; }
553
554         // MORESTATS
555         uint64_t raw_bytes_up() { return raw_bytes_up_; }
556         uint64_t raw_bytes_down() { return raw_bytes_down_; }
557         uint64_t bytes_up() { return bytes_up_; }
558         uint64_t bytes_down() { return bytes_down_; }
559
560         static int  DecodeID(int scrambled);
561         static int  EncodeID(int unscrambled);
562         static Channel* channel(int i) {
563             return i<channels.size()?channels[i]:NULL;
564         }
565         static void CloseTransfer (FileTransfer* trans);
566
567         // SAFECLOSE
568         void            ClearEvents();
569         void            Schedule4Close() { scheduled4close_ = true; }
570         bool            IsScheduled4Close() { return scheduled4close_; }
571
572
573     protected:
574         /** Channel id: index in the channel array. */
575         uint32_t    id_;
576         /**    Socket address of the peer. */
577         Address     peer_;
578         /**    The UDP socket fd. */
579         evutil_socket_t      socket_;
580         /**    Descriptor of the file in question. */
581         FileTransfer*    transfer_;
582         /**    Peer channel id; zero if we are trying to open a channel. */
583         uint32_t    peer_channel_id_;
584         bool        own_id_mentioned_;
585         /**    Peer's progress, based on acknowledgements. */
586         binmap_t    ack_in_;
587         /**    Last data received; needs to be acked immediately. */
588         tintbin     data_in_;
589         bin_t       data_in_dbl_;
590         /** The history of data sent and still unacknowledged. */
591         tbqueue     data_out_;
592         /** Timeouted data (potentially to be retransmitted). */
593         tbqueue     data_out_tmo_;
594         bin_t       data_out_cap_;
595         /** Index in the history array. */
596         binmap_t    have_out_;
597         /**    Transmit schedule: in most cases filled with the peer's hints */
598         tbqueue     hint_in_;
599         /** Hints sent (to detect and reschedule ignored hints). */
600         tbqueue     hint_out_;
601         uint64_t    hint_out_size_;
602         /** Types of messages the peer accepts. */
603         uint64_t    cap_in_;
604         /** For repeats. */
605         //tint        last_send_time, last_recv_time;
606         /** PEX progress */
607         bool        pex_requested_;
608         tint        last_pex_request_time_;
609         tint        next_pex_request_time_;
610         bool        pex_request_outstanding_;
611         tbqueue     reverse_pex_out_;           // Arno, 2011-10-03: should really be a queue of (tint,channel id(= uint32_t)) pairs.
612         int         useless_pex_count_;
613         /** Smoothed averages for RTT, RTT deviation and data interarrival periods. */
614         tint        rtt_avg_, dev_avg_, dip_avg_;
615         tint        last_send_time_;
616         tint        last_recv_time_;
617         tint        last_data_out_time_;
618         tint        last_data_in_time_;
619         tint        last_loss_time_;
620         tint        next_send_time_;
621         /** Congestion window; TODO: int, bytes. */
622         float       cwnd_;
623         int         cwnd_count1_;
624         /** Data sending interval. */
625         tint        send_interval_;
626         /** The congestion control strategy. */
627         int         send_control_;
628         /** Datagrams (not data) sent since last recv.    */
629         int         sent_since_recv_;
630
631         /** Arno: Fix for KEEP_ALIVE_CONTROL */
632         bool            lastrecvwaskeepalive_;
633         bool            lastsendwaskeepalive_;
634
635         /** Recent acknowlegements for data previously sent.    */
636         int         ack_rcvd_recent_;
637         /** Recent non-acknowlegements (losses) of data previously sent.    */
638         int         ack_not_rcvd_recent_;
639         /** LEDBAT one-way delay machinery */
640         tint        owd_min_bins_[4];
641         int         owd_min_bin_;
642         tint        owd_min_bin_start_;
643         tint        owd_current_[4];
644         int         owd_cur_bin_;
645         /** Stats */
646         int         dgrams_sent_;
647         int         dgrams_rcvd_;
648         // Arno, 2011-11-28: for detailed, per-peer stats. MORESTATS
649         uint64_t raw_bytes_up_, raw_bytes_down_, bytes_up_, bytes_down_;
650
651         // SAFECLOSE
652         bool            scheduled4close_;
653         /** Arno: Socket address of the peer where packets are received from,
654          * when an IANA private address, otherwise 0.
655          * May not be equal to peer_. 2PEERSBEHINDSAMENAT */
656         Address     recv_peer_;
657
658         int         PeerBPS() const {
659             return TINT_SEC / dip_avg_ * 1024;
660         }
661         /** Get a request for one packet from the queue of peer's requests. */
662         bin_t       DequeueHint(bool *retransmitptr);
663         bin_t       ImposeHint();
664         void        TimeoutDataOut ();
665         void        CleanStaleHintOut();
666         void        CleanHintOut(bin_t pos);
667         void        Reschedule();
668         void            UpdateDIP(bin_t pos); // RETRANSMIT
669
670
671         static PeerSelector* peer_selector;
672
673         static tint     last_tick;
674         //static tbheap   send_queue;
675
676         static std::vector<Channel*> channels;
677
678         friend int      Listen (Address addr);
679         friend void     Shutdown (int sock_des);
680         friend void     AddPeer (Address address, const Sha1Hash& root);
681         friend void     SetTracker(const Address& tracker);
682         friend int      Open (const char*, const Sha1Hash&, Address tracker, bool force_check_diskvshash, bool check_netwvshash, uint32_t chunk_size) ; // FIXME
683     };
684
685
686
687     /*************** The top-level API ****************/
688     /** Start listening a port. Returns socket descriptor. */
689     int     Listen (Address addr);
690     /** Stop listening to a port. */
691     void    Shutdown (int sock_des=-1);
692
693     /** Open a file, start a transmission; fill it with content for a given
694         root hash and tracker (optional). If "force_check_diskvshash" is true, the
695         hashtree state will be (re)constructed from the file on disk (if any).
696         If not, open will try to reconstruct the hashtree state from
697         the .mhash and .mbinmap files on disk. .mhash files are created
698         automatically, .mbinmap files must be written by checkpointing the
699         transfer by calling FileTransfer::serialize(). If the reconstruction
700         fails, it will hashcheck anyway. Roothash is optional for new files or
701         files already hashchecked and checkpointed. If "check_netwvshash" is
702         false, no uncle hashes will be sent and no data will be verified against
703         then on receipt. In this mode, checking disk contents against hashes
704         no longer works on restarts, unless checkpoints are used.
705         */
706     int     Open (const char* filename, const Sha1Hash& hash=Sha1Hash::ZERO,Address tracker=Address(), bool force_check_diskvshash=true, bool check_netwvshash=true, uint32_t chunk_size=SWIFT_DEFAULT_CHUNK_SIZE);
707     /** Get the root hash for the transmission. */
708     const Sha1Hash& RootMerkleHash (int file) ;
709     /** Close a file and a transmission. */
710     void    Close (int fd) ;
711     /** Add a possible peer which participares in a given transmission. In the case
712         root hash is zero, the peer might be talked to regarding any transmission
713         (likely, a tracker, cache or an archive). */
714     void    AddPeer (Address address, const Sha1Hash& root=Sha1Hash::ZERO);
715
716     void    SetTracker(const Address& tracker);
717     /** Set the default tracker that is used when Open is not passed a tracker
718         address. */
719
720     /** Returns size of the file in bytes, 0 if unknown. Might be rounded up to a kilobyte
721         before the transmission is complete. */
722     uint64_t  Size (int fdes);
723     /** Returns the amount of retrieved and verified data, in bytes.
724         A 100% complete transmission has Size()==Complete(). */
725     uint64_t  Complete (int fdes);
726     bool      IsComplete (int fdes);
727     /** Returns the number of bytes that are complete sequentially, starting from the
728         beginning, till the first not-yet-retrieved packet. */
729     uint64_t  SeqComplete (int fdes);
730     /***/
731     int       Find (Sha1Hash hash);
732     /** Returns the number of bytes in a chunk for this transmission */
733     uint32_t      ChunkSize(int fdes);
734
735     /** Get the address bound to the socket descriptor returned by Listen() */
736     Address BoundAddress(evutil_socket_t sock);
737
738     void AddProgressCallback (int transfer,ProgressCallback cb,uint8_t agg);
739     void RemoveProgressCallback (int transfer,ProgressCallback cb);
740     void ExternallyRetrieved (int transfer,bin_t piece);
741
742
743     /** Must be called by any client using the library */
744     void LibraryInit(void);
745
746     int evbuffer_add_string(struct evbuffer *evb, std::string str);
747     int evbuffer_add_8(struct evbuffer *evb, uint8_t b);
748     int evbuffer_add_16be(struct evbuffer *evb, uint16_t w);
749     int evbuffer_add_32be(struct evbuffer *evb, uint32_t i);
750     int evbuffer_add_64be(struct evbuffer *evb, uint64_t l);
751     int evbuffer_add_hash(struct evbuffer *evb, const Sha1Hash& hash);
752
753     uint8_t evbuffer_remove_8(struct evbuffer *evb);
754     uint16_t evbuffer_remove_16be(struct evbuffer *evb);
755     uint32_t evbuffer_remove_32be(struct evbuffer *evb);
756     uint64_t evbuffer_remove_64be(struct evbuffer *evb);
757     Sha1Hash evbuffer_remove_hash(struct evbuffer* evb);
758
759     const char* tintstr(tint t=0);
760     std::string sock2str (struct sockaddr_in addr);
761  #define SWIFT_MAX_CONNECTIONS 20
762
763     void nat_test_update(void);
764
765     // Arno: Save transfer's binmap for zero-hashcheck restart
766     void Checkpoint(int fdes);
767
768 } // namespace end
769
770 // #define SWIFT_MUTE
771
772 #ifndef SWIFT_MUTE
773 #define dprintf(...) do { if (Channel::debug_file) fprintf(Channel::debug_file,__VA_ARGS__); } while (0)
774 #define dflush() fflush(Channel::debug_file)
775 #else
776 #define dprintf(...) do {} while(0)
777 #define dflush() do {} while(0)
778 #endif
779 #define eprintf(...) fprintf(stderr,__VA_ARGS__)
780
781 #endif