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