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