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