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