2317e6153e0eb21873e2d3ff7b10eeab31e0c25c
[swift-upb.git] / sendrecv.cpp
1 /*
2  *  sendrecv.cpp
3  *  most of the swift's state machine
4  *
5  *  Created by Victor Grishchenko on 3/6/09.
6  *  Copyright 2009 Delft University of Technology. All rights reserved.
7  *
8  */
9 #include "swift.h"
10 #include "compat/util.h"
11
12
13 using namespace swift;
14 using namespace std;
15
16 /*
17  TODO  25 Oct 18:55
18  - range: ALL
19  - randomized testing of advanced ops (new testcase)
20  */
21
22 void    Channel::AddPeakHashes (Datagram& dgram) {
23     for(int i=0; i<file().peak_count(); i++) {
24         bin64_t peak = file().peak(i);
25         dgram.Push8(SWIFT_HASH);
26         dgram.Push32((uint32_t)peak);
27         dgram.PushHash(file().peak_hash(i));
28         //DLOG(INFO)<<"#"<<id<<" +pHASH"<<file().peak(i);
29         dprintf("%s #%u +phash %s\n",tintstr(),id_,peak.str());
30     }
31 }
32
33
34 void    Channel::AddUncleHashes (Datagram& dgram, bin64_t pos) {
35     bin64_t peak = file().peak_for(pos);
36     while (pos!=peak && ((NOW&3)==3 || !data_out_cap_.within(pos.parent())) &&
37             ack_in_.get(pos.parent())==binmap_t::EMPTY  ) {
38         bin64_t uncle = pos.sibling();
39         dgram.Push8(SWIFT_HASH);
40         dgram.Push32((uint32_t)uncle);
41         dgram.PushHash( file().hash(uncle) );
42         //DLOG(INFO)<<"#"<<id<<" +uHASH"<<uncle;
43         dprintf("%s #%u +hash %s\n",tintstr(),id_,uncle.str());
44         pos = pos.parent();
45     }
46 }
47
48
49 bin64_t        Channel::DequeueHint () {
50     if (hint_in_.empty() && last_recv_time_>NOW-rtt_avg_-TINT_SEC) {    
51         uint64_t twist = peer_channel_id_;  // got no hints, send something randomly
52         twist &= file().peak(0); // may make it semi-seq here
53         file().ack_out().twist(twist);
54         ack_in_.twist(twist);
55         bin64_t my_pick = 
56             file().ack_out().find_filtered(ack_in_,bin64_t::ALL,binmap_t::FILLED);
57         while (my_pick.width()>max(1,(int)cwnd_))
58             my_pick = my_pick.left();
59         file().ack_out().twist(0);
60         ack_in_.twist(0);
61         if (my_pick!=bin64_t::NONE) {
62             my_pick = my_pick.twisted(twist);
63             hint_in_.push_back(my_pick);
64             dprintf("%s #%u *hint %s\n",tintstr(),id_,my_pick.str());
65         }
66     }
67     bin64_t send = bin64_t::NONE;
68     while (!hint_in_.empty() && send==bin64_t::NONE) {
69         bin64_t hint = hint_in_.front().bin;
70         tint time = hint_in_.front().time;
71         hint_in_.pop_front();
72         while (!hint.is_base()) { // FIXME optimize; possible attack
73             hint_in_.push_front(tintbin(time,hint.right()));
74             hint = hint.left();
75         }
76         //if (time < NOW-TINT_SEC*3/2 )
77         //    continue;  bad idea
78         if (ack_in_.get(hint)!=binmap_t::FILLED) 
79             send = hint;
80     }
81     uint64_t mass = 0;
82     for(int i=0; i<hint_in_.size(); i++)
83         mass += hint_in_[i].bin.width();
84     dprintf("%s #%u dequeued %s [%lli]\n",tintstr(),id_,send.str(),mass);
85     return send;
86 }
87
88
89 void    Channel::AddHandshake (Datagram& dgram) {
90     if (!peer_channel_id_) { // initiating
91         dgram.Push8(SWIFT_HASH);
92         dgram.Push32(bin64_t::ALL32);
93         dgram.PushHash(file().root_hash());
94         dprintf("%s #%u +hash ALL %s\n",
95                 tintstr(),id_,file().root_hash().hex().c_str());
96     }
97     dgram.Push8(SWIFT_HANDSHAKE);
98     int encoded = EncodeID(id_);
99     dgram.Push32(encoded);
100     dprintf("%s #%u +hs %x\n",tintstr(),id_,encoded);
101     ack_out_.clear();
102     AddAck(dgram);
103 }
104
105
106 void    Channel::Send () {
107     Datagram dgram(socket_,peer());
108     dgram.Push32(peer_channel_id_);
109     bin64_t data = bin64_t::NONE;
110     if ( is_established() ) {
111         // FIXME: seeder check
112         AddAck(dgram);
113         if (!file().is_complete())
114             AddHint(dgram);
115         AddPex(dgram);
116         CleanDataOut();
117         data = AddData(dgram);
118     } else {
119         AddHandshake(dgram);
120         AddAck(dgram);
121     }
122     dprintf("%s #%u sent %ib %s:%x\n",
123             tintstr(),id_,dgram.size(),peer().str(),peer_channel_id_);
124     if (dgram.size()==4) {// only the channel id; bare keep-alive
125         data = bin64_t::ALL;
126         //dprintf("%s #%u considering keepalive %i %f %s\n",
127         //        tintstr(),id_,(int)data_out_.size(),cwnd_,SEND_CONTROL_MODES[send_control_]);
128         //if (data_out_.size()<cwnd_ && send_control_!=KEEP_ALIVE_CONTROL) {
129             //if ( cwnd_ < 1 )
130             //    SwitchSendControl(KEEP_ALIVE_CONTROL);
131             //else
132             //    cwnd_ = cwnd_/2.0;
133         //}
134         //if (data_out_.empty() && send_control_!=KEEP_ALIVE_CONTROL)
135         //     SwitchSendControl(KEEP_ALIVE_CONTROL);// we did our best
136         //if (NOW<last_send_time_+MAX_SEND_INTERVAL) // no need for keepalive
137         //    return; // don't send empty dgram
138     }
139     if (dgram.Send()==-1)
140         print_error("can't send datagram");
141     last_send_time_ = NOW;
142     sent_since_recv_++;
143     dgrams_sent_++;
144 }
145
146
147 void    Channel::AddHint (Datagram& dgram) {
148
149     tint plan_for = max(TINT_SEC,rtt_avg_*4);
150     
151     tint timed_out = NOW - plan_for*2;
152     while ( !hint_out_.empty() && hint_out_.front().time < timed_out ) {
153         hint_out_size_ -= hint_out_.front().bin.width();
154         hint_out_.pop_front();
155     }
156     
157     /*int peer_cwnd = (int)(rtt_avg_ / dip_avg_);
158     if (!peer_cwnd)
159         peer_cwnd = 1;*/
160     int plan_pck = std::max ( (tint)1, plan_for / dip_avg_ );
161     
162     if ( hint_out_size_ < plan_pck ) {
163             
164         int diff = plan_pck - hint_out_size_; // TODO: aggregate
165         bin64_t hint = transfer().picker().Pick(ack_in_,diff,NOW+plan_for*2);
166         
167         if (hint!=bin64_t::NONE) {
168             dgram.Push8(SWIFT_HINT);
169             dgram.Push32(hint);
170             dprintf("%s #%u +hint %s [%lli]\n",tintstr(),id_,hint.str(),hint_out_size_);
171             hint_out_.push_back(hint);
172             hint_out_size_ += hint.width();
173         } else
174             dprintf("%s #%u Xhint\n",tintstr(),id_);
175         
176     }
177 }
178
179
180 bin64_t        Channel::AddData (Datagram& dgram) {
181     
182     if (!file().size()) // know nothing
183         return bin64_t::NONE;
184     
185     bin64_t tosend = bin64_t::NONE;
186     tint luft = send_interval_>>4; // may wake up a bit earlier
187     if (data_out_.size()<cwnd_ &&
188             last_data_out_time_+send_interval_<=NOW+luft) {
189         tosend = DequeueHint();
190         if (tosend==bin64_t::NONE) {
191             dprintf("%s #%u sendctrl no idea what to send\n",tintstr(),id_);
192             if (send_control_!=KEEP_ALIVE_CONTROL)
193                 SwitchSendControl(KEEP_ALIVE_CONTROL);
194         }
195     } else
196         dprintf("%s #%u sendctrl wait cwnd %f data_out %i next %s\n",
197                 tintstr(),id_,cwnd_,data_out_.size(),tintstr(last_data_out_time_+NOW-send_interval_));
198     
199     if (tosend==bin64_t::NONE)// && (last_data_out_time_>NOW-TINT_SEC || data_out_.empty())) 
200         return bin64_t::NONE; // once in a while, empty data is sent just to check rtt FIXED
201     
202     if (ack_in_.is_empty() && file().size())
203         AddPeakHashes(dgram);
204     AddUncleHashes(dgram,tosend);
205     if (!ack_in_.is_empty()) // TODO: cwnd_>1
206         data_out_cap_ = tosend;
207
208     if (dgram.size()>254) {
209         dgram.Send(); // kind of fragmentation
210         dgram.Push32(peer_channel_id_);
211     }
212     
213     dgram.Push8(SWIFT_DATA);
214     dgram.Push32(tosend.to32());
215     
216     uint8_t buf[1024];
217     size_t r = pread(file().file_descriptor(),buf,1024,tosend.base_offset()<<10); 
218     // TODO: corrupted data, retries, caching
219     if (r<0) {
220         print_error("error on reading");
221         return bin64_t::NONE;
222     }
223     assert(dgram.space()>=r+4+1);
224     dgram.Push(buf,r);
225     
226     last_data_out_time_ = NOW;
227     data_out_.push_back(tosend);
228     dprintf("%s #%u +data %s\n",tintstr(),id_,tosend.str());
229     
230     return tosend;
231 }
232
233
234 void    Channel::AddTs (Datagram& dgram) {
235     dgram.Push8(SWIFT_TS);
236     dgram.Push64(data_in_.time);
237     dprintf("%s #%u +ts %s\n",tintstr(),id_,tintstr(data_in_.time));
238 }
239
240
241 void    Channel::AddAck (Datagram& dgram) {
242     if (data_in_dbl_!=bin64_t::NONE) { // TODO: do redundancy better
243         dgram.Push8(SWIFT_ACK);
244         dgram.Push32(data_in_dbl_.to32());
245         data_in_dbl_=bin64_t::NONE;
246     }
247     if (data_in_.time!=TINT_NEVER) { // TODO: ACK NONE for corrupted data
248         AddTs(dgram);
249         bin64_t pos = data_in_.bin; // be precise file().ack_out().cover(data_in_.bin);
250         dgram.Push8(SWIFT_ACK);
251         dgram.Push32(pos.to32());
252         //dgram.Push64(data_in_.time);
253         ack_out_.set(pos);
254         dprintf("%s #%u +ack %s %s\n",tintstr(),id_,pos.str(),tintstr(data_in_.time));
255         data_in_ = tintbin(TINT_NEVER,bin64_t::NONE);
256         if (pos.layer()>2)
257             data_in_dbl_ = pos;
258     }
259     for(int count=0; count<4; count++) {
260         bin64_t ack = file().ack_out().find_filtered(ack_out_, bin64_t::ALL, binmap_t::FILLED);
261         if (ack==bin64_t::NONE)
262             break;
263         ack = file().ack_out().cover(ack);
264         ack_out_.set(ack);
265         dgram.Push8(SWIFT_ACK);
266         dgram.Push32(ack.to32());
267         dprintf("%s #%u +ack %s\n",tintstr(),id_,ack.str());
268     }
269 }
270
271
272 void    Channel::Recv (Datagram& dgram) {
273     dprintf("%s #%u recvd %i\n",tintstr(),id_,dgram.size()+4);
274     peer_send_time_ = 0; // has scope of 1 datagram
275     dgrams_rcvd_++;
276     if (last_send_time_ && rtt_avg_==TINT_SEC && dev_avg_==0) {
277         rtt_avg_ = NOW - last_send_time_;
278         dev_avg_ = rtt_avg_;
279         dip_avg_ = rtt_avg_;
280         dprintf("%s #%u sendctrl rtt init %lli\n",tintstr(),id_,rtt_avg_);
281     }
282     bin64_t data = dgram.size() ? bin64_t::NONE : bin64_t::ALL;
283     while (dgram.size()) {
284         uint8_t type = dgram.Pull8();
285         switch (type) {
286             case SWIFT_HANDSHAKE: OnHandshake(dgram); break;
287             case SWIFT_DATA:      data=OnData(dgram); break;
288             case SWIFT_TS:        OnTs(dgram); break;
289             case SWIFT_ACK:       OnAck(dgram); break;
290             case SWIFT_HASH:      OnHash(dgram); break;
291             case SWIFT_HINT:      OnHint(dgram); break;
292             case SWIFT_PEX_ADD:   OnPex(dgram); break;
293             default:
294                 eprintf("%s #%u ?msg id unknown %i\n",tintstr(),id_,(int)type);
295                 return;
296         }
297     }
298     last_recv_time_ = NOW;
299     sent_since_recv_ = 0;
300 }
301
302
303 void    Channel::OnHash (Datagram& dgram) {
304     bin64_t pos = dgram.Pull32();
305     Sha1Hash hash = dgram.PullHash();
306     file().OfferHash(pos,hash);
307     //DLOG(INFO)<<"#"<<id<<" .HASH"<<(int)pos;
308     dprintf("%s #%u -hash %s\n",tintstr(),id_,pos.str());
309 }
310
311
312 void    Channel::CleanHintOut (bin64_t pos) {
313     int hi = 0;
314     while (hi<hint_out_.size() && !pos.within(hint_out_[hi].bin))
315         hi++;
316     if (hi==hint_out_.size())
317         return; // something not hinted or hinted in far past
318     while (hi--) { // removing likely snubbed hints
319         hint_out_size_ -= hint_out_.front().bin.width();
320         hint_out_.pop_front();
321     }
322     while (hint_out_.front().bin!=pos) {
323         tintbin f = hint_out_.front();
324         f.bin = f.bin.towards(pos);
325         hint_out_.front().bin = f.bin.sibling();
326         hint_out_.push_front(f);
327     }
328     hint_out_.pop_front();
329     hint_out_size_--;
330 }
331
332
333 bin64_t Channel::OnData (Datagram& dgram) {
334     bin64_t pos = dgram.Pull32();
335     uint8_t *data;
336     int length = dgram.Pull(&data,1024);
337     bool ok = (pos==bin64_t::NONE) || file().OfferData(pos, (char*)data, length) ;
338     dprintf("%s #%u %cdata %s\n",tintstr(),id_,ok?'-':'!',pos.str());
339     data_in_ = tintbin(NOW,bin64_t::NONE);
340     if (!ok) 
341         return bin64_t::NONE;
342     data_in_.bin = pos;
343     if (pos!=bin64_t::NONE) {
344         if (last_data_in_time_) {
345             tint dip = NOW - last_data_in_time_;
346             dip_avg_ = ( dip_avg_*3 + dip ) >> 2;
347         }
348         last_data_in_time_ = NOW;
349     }
350     CleanHintOut(pos);    
351     return pos;
352 }
353
354
355 void    Channel::CleanDataOut (bin64_t ackd_pos) { // TODO: isn't it too long?
356     
357     int max_ack_off = 0;
358     
359     if (ackd_pos!=bin64_t::NONE) {
360         for (int i=0; i<data_out_.size(); i++) {
361             if (data_out_[i]!=tintbin() && data_out_[i].bin.within(ackd_pos)) {
362                 if (peer_send_time_)
363                     for(tbqueue::iterator j=data_out_tmo_.begin(); j!=data_out_tmo_.end(); j++)
364                         if (j->bin==data_out_[i].bin)
365                             peer_send_time_=0; // possibly retransmit
366                 if (peer_send_time_) { // well, it is sorta ACK ACK
367                     tint rtt = NOW-data_out_[i].time;
368                     rtt_avg_ = (rtt_avg_*7 + rtt) >> 3;
369                     dev_avg_ = ( dev_avg_*3 + abs(rtt-rtt_avg_) ) >> 2;
370                     assert(data_out_[i].time!=TINT_NEVER);
371                     tint owd = peer_send_time_ - data_out_[i].time;
372                     owd_cur_bin_ = (owd_cur_bin_+1) & 3;
373                     owd_current_[owd_cur_bin_] = owd;
374                     if ( owd_min_bin_start_+TINT_SEC*30 < NOW ) {
375                         owd_min_bin_start_ = NOW;
376                         owd_min_bin_ = (owd_min_bin_+1) & 3;
377                         owd_min_bins_[owd_min_bin_] = TINT_NEVER;
378                     }
379                     if (owd_min_bins_[owd_min_bin_]>owd)
380                         owd_min_bins_[owd_min_bin_] = owd;
381                     peer_send_time_ = 0;
382                 }
383                 dprintf("%s #%u sendctrl rtt %lli dev %lli based on %s\n",
384                         tintstr(),id_,rtt_avg_,dev_avg_,data_out_[i].bin.str());
385                 bin64_t pos = data_out_[i].bin;
386                 ack_rcvd_recent_++;
387                 data_out_[i]=tintbin();
388                 max_ack_off = i;
389                 if (ackd_pos==pos)
390                     break;
391             }
392         }
393         while (!data_out_.empty() && data_out_.front().bin==bin64_t::NONE) {
394             data_out_.pop_front();
395             max_ack_off--;
396         }
397         static const int MAX_REORDERING = 2;  // the triple-ACK principle
398         if (max_ack_off>MAX_REORDERING) {
399             while (max_ack_off && (data_out_.front().bin==bin64_t::NONE
400                                    || ack_in_.is_filled(data_out_.front().bin)) ) {
401                 data_out_.pop_front();
402                 max_ack_off--;
403             }
404             while (max_ack_off>MAX_REORDERING) {
405                 ack_not_rcvd_recent_++;
406                 data_out_tmo_.push_back(data_out_.front().bin);
407                 dprintf("%s #%u Rdata %s\n",tintstr(),id_,data_out_.front().bin.str());
408                 data_out_.pop_front();
409                 max_ack_off--;
410                 data_out_cap_ = bin64_t::ALL;
411             }
412         }
413         peer_send_time_ = 0;
414     }
415     tint timeout = NOW - rtt_avg_ - 4*std::max(dev_avg_,TINT_MSEC*50);
416     while (!data_out_.empty() && data_out_.front().time<timeout) {
417         if (data_out_.front().bin!=bin64_t::NONE && ack_in_.is_empty(data_out_.front().bin)) {
418             ack_not_rcvd_recent_++;
419             data_out_cap_ = bin64_t::ALL;
420             data_out_tmo_.push_back(data_out_.front().bin);
421             dprintf("%s #%u Tdata %s\n",tintstr(),id_,data_out_.front().bin.str());
422         }
423         data_out_.pop_front();
424     }
425     while (!data_out_.empty() && data_out_.front().bin==bin64_t::NONE)
426         data_out_.pop_front();
427     assert(data_out_.empty() || data_out_.front().time!=TINT_NEVER);
428     while (!data_out_tmo_.empty() && data_out_tmo_.front().time<NOW-MAX_POSSIBLE_RTT)
429         data_out_tmo_.pop_front();
430
431 }
432
433
434 void    Channel::OnAck (Datagram& dgram) {
435     bin64_t ackd_pos = dgram.Pull32();
436     if (ackd_pos==bin64_t::NONE)
437         return; // likely, brocken packet / insufficient hashes
438     if (file().size() && ackd_pos.base_offset()>=file().packet_size()) {
439         eprintf("invalid ack: %s\n",ackd_pos.str());
440         return;
441     }
442     dprintf("%s #%u -ack %s\n",tintstr(),id_,ackd_pos.str());
443     ack_in_.set(ackd_pos);
444     CleanDataOut(ackd_pos); // FIXME do AFTER all ACKs
445 }
446
447
448 void Channel::OnTs (Datagram& dgram) {
449     peer_send_time_ = dgram.Pull64();
450     dprintf("%s #%u -ts %lli\n",tintstr(),id_,peer_send_time_);
451 }
452
453
454 void    Channel::OnHint (Datagram& dgram) {
455     bin64_t hint = dgram.Pull32();
456     hint_in_.push_back(hint);
457     //ack_in_.set(hint,binmap_t::EMPTY);
458     //RequeueSend(cc_->OnHintRecvd(hint));
459     dprintf("%s #%u -hint %s\n",tintstr(),id_,hint.str());
460 }
461
462
463 void Channel::OnHandshake (Datagram& dgram) {
464     peer_channel_id_ = dgram.Pull32();
465     dprintf("%s #%u -hs %x\n",tintstr(),id_,peer_channel_id_);
466     // self-connection check
467     if (!SELF_CONN_OK) {
468         uint32_t try_id = DecodeID(peer_channel_id_);
469         if (channel(try_id) && !channel(try_id)->peer_channel_id_) {
470             peer_channel_id_ = 0;
471             Close();
472             return; // this is a self-connection
473         }
474     }
475     // FUTURE: channel forking
476 }
477
478
479 void Channel::OnPex (Datagram& dgram) {
480     uint32_t ipv4 = dgram.Pull32();
481     uint16_t port = dgram.Pull16();
482     Address addr(ipv4,port);
483     dprintf("%s #%u -pex %s\n",tintstr(),id_,addr.str());
484     transfer().OnPexIn(addr);
485 }
486
487
488 void    Channel::AddPex (Datagram& dgram) {
489     int chid = transfer().RevealChannel(pex_out_);
490     if (chid==-1 || chid==id_)
491         return;
492     Address a = channels[chid]->peer();
493     dgram.Push8(SWIFT_PEX_ADD);
494     dgram.Push32(a.ipv4());
495     dgram.Push16(a.port());
496     dprintf("%s #%u +pex %s\n",tintstr(),id_,a.str());
497 }
498
499
500 Channel*    Channel::RecvDatagram (int socket) {
501     Datagram data(socket);
502     data.Recv();
503     const Address& addr = data.address();
504 #define return_log(...) { printf(__VA_ARGS__); return NULL; }
505     if (data.size()<4) 
506         return_log("datagram shorter than 4 bytes %s\n",addr.str());
507     uint32_t mych = data.Pull32();
508     Sha1Hash hash;
509     Channel* channel = NULL;
510     if (!mych) { // handshake initiated
511         if (data.size()<1+4+1+4+Sha1Hash::SIZE) 
512             return_log ("%s #0 incorrect size %i initial handshake packet %s\n",
513                         tintstr(),data.size(),addr.str());
514         uint8_t hashid = data.Pull8();
515         if (hashid!=SWIFT_HASH) 
516             return_log ("%s #0 no hash in the initial handshake %s\n",
517                         tintstr(),addr.str());
518         bin64_t pos = data.Pull32();
519         if (pos!=bin64_t::ALL) 
520             return_log ("%s #0 that is not the root hash %s\n",tintstr(),addr.str());
521         hash = data.PullHash();
522         FileTransfer* file = FileTransfer::Find(hash);
523         if (!file) 
524             return_log ("%s #0 hash %s unknown, no such file %s\n",tintstr(),hash.hex().c_str(),addr.str());
525         dprintf("%s #0 -hash ALL %s\n",tintstr(),hash.hex().c_str());
526         for(binqueue::iterator i=file->hs_in_.begin(); i!=file->hs_in_.end(); i++)
527             if (channels[*i] && channels[*i]->peer_==data.address() && 
528                 channels[*i]->last_recv_time_>NOW-TINT_SEC*2)
529                 return_log("%s #0 have a channel already to %s\n",tintstr(),addr.str());
530         channel = new Channel(file, socket, data.address());
531     } else {
532         mych = DecodeID(mych);
533         if (mych>=channels.size()) 
534             return_log("%s invalid channel #%u, %s\n",tintstr(),mych,addr.str());
535         channel = channels[mych];
536         if (!channel) 
537             return_log ("%s #%u is already closed\n",tintstr(),mych,addr.str());
538         if (channel->peer() != addr) 
539             return_log ("%s #%u invalid peer address %s!=%s\n",
540                         tintstr(),mych,channel->peer().str(),addr.str());
541         channel->own_id_mentioned_ = true;
542     }
543     //dprintf("recvd %i bytes for %i\n",data.size(),channel->id);
544     channel->Recv(data);
545     return channel;
546 }
547
548
549 void    Channel::Loop (tint howlong) {  
550     
551     tint limit = Datagram::Time() + howlong;
552     
553     do {
554
555         tint send_time(TINT_NEVER);
556         Channel* sender(NULL);
557         while (!sender && !send_queue.is_empty()) { // dequeue
558             tintbin next = send_queue.pop();
559             sender = channel((int)next.bin);
560             send_time = next.time;
561             if (sender && sender->next_send_time_!=send_time &&
562                      sender->next_send_time_!=TINT_NEVER )
563                 sender = NULL; // it was a stale entry
564         }
565         
566         if ( sender!=NULL && send_time<=NOW ) { // it's time
567             
568             dprintf("%s #%u sch_send %s\n",tintstr(),sender->id(),
569                     tintstr(send_time));
570             sender->Send();
571             sender->Reschedule();
572             
573         } else {  // it's too early, wait
574             
575             tint towait = min(limit,send_time) - NOW;
576             dprintf("%s #0 waiting %lliusec\n",tintstr(),towait);
577             int rd = Datagram::Wait(socket_count,sockets,towait);
578             if (rd!=INVALID_SOCKET) { // in meantime, received something
579                 Channel* receiver = RecvDatagram(rd);
580                 if (receiver) // receiver's state may have changed
581                     receiver->Reschedule();
582             }
583             if (sender)  // get back to that later
584                 send_queue.push(tintbin(send_time,sender->id()));
585             
586         }
587         
588     } while (NOW<limit);
589             
590 }
591
592  
593 void Channel::Close () {
594     this->SwitchSendControl(CLOSE_CONTROL);
595 }
596
597
598 void Channel::Reschedule () {
599     next_send_time_ = NextSendTime();
600     if (next_send_time_!=TINT_NEVER) {
601         assert(next_send_time_<NOW+TINT_MIN);
602         send_queue.push(tintbin(next_send_time_,id_));
603         dprintf("%s #%u requeue for %s\n",tintstr(),id_,tintstr(next_send_time_));
604     } else {
605         dprintf("%s #%u closed\n",tintstr(),id_);
606         delete this;
607     }
608 }