source: trunk/libtransmission/peer-io.c @ 10694

Last change on this file since 10694 was 10694, checked in by charles, 13 years ago

(trunk libT) define MAX_BLOCK_SIZE once instead of in a handful of places

  • Property svn:keywords set to Date Rev Author Id
File size: 25.0 KB
Line 
1/*
2 * This file Copyright (C) 2007-2010 Mnemosyne LLC
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: peer-io.c 10694 2010-05-26 15:23:21Z charles $
11 */
12
13#include <assert.h>
14#include <errno.h>
15#include <limits.h> /* INT_MAX */
16#include <string.h>
17#include <stdio.h>
18#include <unistd.h>
19
20#ifdef WIN32
21 #include <winsock2.h>
22#else
23 #include <arpa/inet.h> /* inet_ntoa */
24#endif
25
26#include <event.h>
27
28#include "transmission.h"
29#include "session.h"
30#include "bandwidth.h"
31#include "crypto.h"
32#include "list.h"
33#include "net.h"
34#include "peer-common.h" /* MAX_BLOCK_SIZE */
35#include "peer-io.h"
36#include "trevent.h" /* tr_runInEventThread() */
37#include "utils.h"
38
39#define MAGIC_NUMBER 206745
40
41static size_t
42guessPacketOverhead( size_t d )
43{
44    /**
45     * http://sd.wareonearth.com/~phil/net/overhead/
46     *
47     * TCP over Ethernet:
48     * Assuming no header compression (e.g. not PPP)
49     * Add 20 IPv4 header or 40 IPv6 header (no options)
50     * Add 20 TCP header
51     * Add 12 bytes optional TCP timestamps
52     * Max TCP Payload data rates over ethernet are thus:
53     *  (1500-40)/(38+1500) = 94.9285 %  IPv4, minimal headers
54     *  (1500-52)/(38+1500) = 94.1482 %  IPv4, TCP timestamps
55     *  (1500-52)/(42+1500) = 93.9040 %  802.1q, IPv4, TCP timestamps
56     *  (1500-60)/(38+1500) = 93.6281 %  IPv6, minimal headers
57     *  (1500-72)/(38+1500) = 92.8479 %  IPv6, TCP timestamps
58     *  (1500-72)/(42+1500) = 92.6070 %  802.1q, IPv6, ICP timestamps
59     */
60    const double assumed_payload_data_rate = 94.0;
61
62    return (size_t)( d * ( 100.0 / assumed_payload_data_rate ) - d );
63}
64
65/**
66***
67**/
68
69#define dbgmsg( io, ... ) \
70    do { \
71        if( tr_deepLoggingIsActive( ) ) \
72            tr_deepLog( __FILE__, __LINE__, tr_peerIoGetAddrStr( io ), __VA_ARGS__ ); \
73    } while( 0 )
74
75struct tr_datatype
76{
77    tr_bool  isPieceData;
78    size_t   length;
79};
80
81/***
82****
83***/
84
85static void
86didWriteWrapper( tr_peerIo * io, size_t bytes_transferred )
87{
88     while( bytes_transferred && tr_isPeerIo( io ) )
89     {
90        struct tr_datatype * next = io->outbuf_datatypes->data;
91
92        const size_t payload = MIN( next->length, bytes_transferred );
93        const size_t overhead = guessPacketOverhead( payload );
94
95        tr_bandwidthUsed( &io->bandwidth, TR_UP, payload, next->isPieceData );
96
97        if( overhead > 0 )
98            tr_bandwidthUsed( &io->bandwidth, TR_UP, overhead, FALSE );
99
100        if( io->didWrite )
101            io->didWrite( io, payload, next->isPieceData, io->userData );
102
103        if( tr_isPeerIo( io ) )
104        {
105            bytes_transferred -= payload;
106            next->length -= payload;
107            if( !next->length ) {
108                tr_list_pop_front( &io->outbuf_datatypes );
109                tr_free( next );
110            }
111        }
112    }
113}
114
115static void
116canReadWrapper( tr_peerIo * io )
117{
118    tr_bool err = 0;
119    tr_bool done = 0;
120    tr_session * session;
121
122    dbgmsg( io, "canRead" );
123
124    assert( tr_isPeerIo( io ) );
125    assert( tr_isSession( io->session ) );
126    tr_peerIoRef( io );
127
128    session = io->session;
129
130    /* try to consume the input buffer */
131    if( io->canRead )
132    {
133        tr_sessionLock( session );
134
135        while( !done && !err )
136        {
137            size_t piece = 0;
138            const size_t oldLen = EVBUFFER_LENGTH( io->inbuf );
139            const int ret = io->canRead( io, io->userData, &piece );
140
141            const size_t used = oldLen - EVBUFFER_LENGTH( io->inbuf );
142
143            assert( tr_isPeerIo( io ) );
144
145            if( piece )
146                tr_bandwidthUsed( &io->bandwidth, TR_DOWN, piece, TRUE );
147
148            if( used != piece )
149                tr_bandwidthUsed( &io->bandwidth, TR_DOWN, used - piece, FALSE );
150
151            switch( ret )
152            {
153                case READ_NOW:
154                    if( EVBUFFER_LENGTH( io->inbuf ) )
155                        continue;
156                    done = 1;
157                    break;
158
159                case READ_LATER:
160                    done = 1;
161                    break;
162
163                case READ_ERR:
164                    err = 1;
165                    break;
166            }
167
168            assert( tr_isPeerIo( io ) );
169        }
170
171        tr_sessionUnlock( session );
172    }
173
174    /* keep the iobuf's excess capacity from growing too large */
175    if( EVBUFFER_LENGTH( io->inbuf ) == 0 ) {
176        evbuffer_free( io->inbuf );
177        io->inbuf = evbuffer_new( );
178    }
179
180    assert( tr_isPeerIo( io ) );
181    tr_peerIoUnref( io );
182}
183
184tr_bool
185tr_isPeerIo( const tr_peerIo * io )
186{
187    return ( io != NULL )
188        && ( io->magicNumber == MAGIC_NUMBER )
189        && ( io->refCount >= 0 )
190        && ( tr_isBandwidth( &io->bandwidth ) )
191        && ( tr_isAddress( &io->addr ) );
192}
193
194static void
195event_read_cb( int fd, short event UNUSED, void * vio )
196{
197    int res;
198    int e;
199    tr_peerIo * io = vio;
200
201    /* Limit the input buffer to 256K, so it doesn't grow too large */
202    size_t howmuch;
203    const tr_direction dir = TR_DOWN;
204    const size_t max = 256 * 1024;
205    size_t curlen;
206
207    assert( tr_isPeerIo( io ) );
208
209    io->hasFinishedConnecting = TRUE;
210    io->pendingEvents &= ~EV_READ;
211
212    curlen = EVBUFFER_LENGTH( io->inbuf );
213    howmuch = curlen >= max ? 0 : max - curlen;
214    howmuch = tr_bandwidthClamp( &io->bandwidth, TR_DOWN, howmuch );
215
216    dbgmsg( io, "libevent says this peer is ready to read" );
217
218    /* if we don't have any bandwidth left, stop reading */
219    if( howmuch < 1 ) {
220        tr_peerIoSetEnabled( io, dir, FALSE );
221        return;
222    }
223
224    errno = 0;
225    res = evbuffer_read( io->inbuf, fd, howmuch );
226    e = errno;
227
228    if( res > 0 )
229    {
230        tr_peerIoSetEnabled( io, dir, TRUE );
231
232        /* Invoke the user callback - must always be called last */
233        canReadWrapper( io );
234    }
235    else
236    {
237        short what = EVBUFFER_READ;
238
239        if( res == 0 ) /* EOF */
240            what |= EVBUFFER_EOF;
241        else if( res == -1 ) {
242            if( e == EAGAIN || e == EINTR ) {
243                tr_peerIoSetEnabled( io, dir, TRUE );
244                return;
245            }
246            what |= EVBUFFER_ERROR;
247        }
248
249        dbgmsg( io, "event_read_cb got an error. res is %d, what is %hd, errno is %d (%s)", res, what, e, strerror( e ) );
250
251        if( io->gotError != NULL )
252            io->gotError( io, what, io->userData );
253    }
254}
255
256static int
257tr_evbuffer_write( tr_peerIo * io, int fd, size_t howmuch )
258{
259    int e;
260    int n;
261    struct evbuffer * buffer = io->outbuf;
262
263    howmuch = MIN( EVBUFFER_LENGTH( buffer ), howmuch );
264
265    errno = 0;
266#ifdef WIN32
267    n = (int) send(fd, buffer->buffer, howmuch,  0 );
268#else
269    n = (int) write(fd, buffer->buffer, howmuch );
270#endif
271    e = errno;
272    dbgmsg( io, "wrote %d to peer (%s)", n, (n==-1?strerror(e):"") );
273
274    if( n > 0 )
275        evbuffer_drain( buffer, n );
276
277    /* keep the iobuf's excess capacity from growing too large */
278    if( EVBUFFER_LENGTH( io->outbuf ) == 0 ) {
279        evbuffer_free( io->outbuf );
280        io->outbuf = evbuffer_new( );
281    }
282
283    return n;
284}
285
286static void
287event_write_cb( int fd, short event UNUSED, void * vio )
288{
289    int res = 0;
290    int e;
291    short what = EVBUFFER_WRITE;
292    tr_peerIo * io = vio;
293    size_t howmuch;
294    const tr_direction dir = TR_UP;
295
296    assert( tr_isPeerIo( io ) );
297
298    io->hasFinishedConnecting = TRUE;
299    io->pendingEvents &= ~EV_WRITE;
300
301    dbgmsg( io, "libevent says this peer is ready to write" );
302
303    /* Write as much as possible, since the socket is non-blocking, write() will
304     * return if it can't write any more data without blocking */
305    howmuch = tr_bandwidthClamp( &io->bandwidth, dir, EVBUFFER_LENGTH( io->outbuf ) );
306
307    /* if we don't have any bandwidth left, stop writing */
308    if( howmuch < 1 ) {
309        tr_peerIoSetEnabled( io, dir, FALSE );
310        return;
311    }
312
313    errno = 0;
314    res = tr_evbuffer_write( io, fd, howmuch );
315    e = errno;
316
317    if (res == -1) {
318#ifndef WIN32
319/*todo. evbuffer uses WriteFile when WIN32 is set. WIN32 system calls do not
320 *  *set errno. thus this error checking is not portable*/
321        if (e == EAGAIN || e == EINTR || e == EINPROGRESS)
322            goto reschedule;
323        /* error case */
324        what |= EVBUFFER_ERROR;
325
326#else
327        goto reschedule;
328#endif
329
330    } else if (res == 0) {
331        /* eof case */
332        what |= EVBUFFER_EOF;
333    }
334    if (res <= 0)
335        goto error;
336
337    if( EVBUFFER_LENGTH( io->outbuf ) )
338        tr_peerIoSetEnabled( io, dir, TRUE );
339
340    didWriteWrapper( io, res );
341    return;
342
343 reschedule:
344    if( EVBUFFER_LENGTH( io->outbuf ) )
345        tr_peerIoSetEnabled( io, dir, TRUE );
346    return;
347
348 error:
349
350    dbgmsg( io, "event_write_cb got an error. res is %d, what is %hd, errno is %d (%s)", res, what, e, strerror( e ) );
351
352    if( io->gotError != NULL )
353        io->gotError( io, what, io->userData );
354}
355
356/**
357***
358**/
359
360static void
361maybeSetCongestionAlgorithm( int socket, const char * algorithm )
362{
363    if( algorithm && *algorithm )
364    {
365        const int rc = tr_netSetCongestionControl( socket, algorithm );
366
367        if( rc < 0 )
368            tr_ninf( "Net", "Can't set congestion control algorithm '%s': %s",
369                     algorithm, tr_strerror( errno ));
370    }
371}
372
373static tr_peerIo*
374tr_peerIoNew( tr_session       * session,
375              tr_bandwidth     * parent,
376              const tr_address * addr,
377              tr_port            port,
378              const uint8_t    * torrentHash,
379              tr_bool            isIncoming,
380              tr_bool            isSeed,
381              int                socket )
382{
383    tr_peerIo * io;
384
385    assert( session != NULL );
386    assert( session->events != NULL );
387    assert( tr_isBool( isIncoming ) );
388    assert( tr_isBool( isSeed ) );
389    assert( tr_amInEventThread( session ) );
390
391    if( socket >= 0 ) {
392        tr_netSetTOS( socket, session->peerSocketTOS );
393        maybeSetCongestionAlgorithm( socket, session->peer_congestion_algorithm );
394    }
395   
396    io = tr_new0( tr_peerIo, 1 );
397    io->magicNumber = MAGIC_NUMBER;
398    io->refCount = 1;
399    io->crypto = tr_cryptoNew( torrentHash, isIncoming );
400    io->session = session;
401    io->addr = *addr;
402    io->isSeed = isSeed;
403    io->port = port;
404    io->socket = socket;
405    io->isIncoming = isIncoming != 0;
406    io->hasFinishedConnecting = FALSE;
407    io->timeCreated = tr_time( );
408    io->inbuf = evbuffer_new( );
409    io->outbuf = evbuffer_new( );
410    tr_bandwidthConstruct( &io->bandwidth, session, parent );
411    tr_bandwidthSetPeer( &io->bandwidth, io );
412    dbgmsg( io, "bandwidth is %p; its parent is %p", &io->bandwidth, parent );
413
414    event_set( &io->event_read, io->socket, EV_READ, event_read_cb, io );
415    event_set( &io->event_write, io->socket, EV_WRITE, event_write_cb, io );
416
417    return io;
418}
419
420tr_peerIo*
421tr_peerIoNewIncoming( tr_session        * session,
422                      tr_bandwidth      * parent,
423                      const tr_address  * addr,
424                      tr_port             port,
425                      int                 fd )
426{
427    assert( session );
428    assert( tr_isAddress( addr ) );
429    assert( fd >= 0 );
430
431    return tr_peerIoNew( session, parent, addr, port, NULL, TRUE, FALSE, fd );
432}
433
434tr_peerIo*
435tr_peerIoNewOutgoing( tr_session        * session,
436                      tr_bandwidth      * parent,
437                      const tr_address  * addr,
438                      tr_port             port,
439                      const uint8_t     * torrentHash,
440                      tr_bool             isSeed )
441{
442    int fd;
443
444    assert( session );
445    assert( tr_isAddress( addr ) );
446    assert( torrentHash );
447
448    fd = tr_netOpenPeerSocket( session, addr, port, isSeed );
449    dbgmsg( NULL, "tr_netOpenPeerSocket returned fd %d", fd );
450
451    return fd < 0 ? NULL
452                  : tr_peerIoNew( session, parent, addr, port, torrentHash, FALSE, isSeed, fd );
453}
454
455/***
456****
457***/
458
459static void
460event_enable( tr_peerIo * io, short event )
461{
462    assert( tr_amInEventThread( io->session ) );
463    assert( io->session != NULL );
464    assert( io->session->events != NULL );
465    assert( event_initialized( &io->event_read ) );
466    assert( event_initialized( &io->event_write ) );
467
468    if( io->socket < 0 )
469        return;
470
471    if( ( event & EV_READ ) && ! ( io->pendingEvents & EV_READ ) )
472    {
473        dbgmsg( io, "enabling libevent ready-to-read polling" );
474        event_add( &io->event_read, NULL );
475        io->pendingEvents |= EV_READ;
476    }
477
478    if( ( event & EV_WRITE ) && ! ( io->pendingEvents & EV_WRITE ) )
479    {
480        dbgmsg( io, "enabling libevent ready-to-write polling" );
481        event_add( &io->event_write, NULL );
482        io->pendingEvents |= EV_WRITE;
483    }
484}
485
486static void
487event_disable( struct tr_peerIo * io, short event )
488{
489    assert( tr_amInEventThread( io->session ) );
490    assert( io->session != NULL );
491    assert( io->session->events != NULL );
492    assert( event_initialized( &io->event_read ) );
493    assert( event_initialized( &io->event_write ) );
494
495    if( ( event & EV_READ ) && ( io->pendingEvents & EV_READ ) )
496    {
497        dbgmsg( io, "disabling libevent ready-to-read polling" );
498        event_del( &io->event_read );
499        io->pendingEvents &= ~EV_READ;
500    }
501
502    if( ( event & EV_WRITE ) && ( io->pendingEvents & EV_WRITE ) )
503    {
504        dbgmsg( io, "disabling libevent ready-to-write polling" );
505        event_del( &io->event_write );
506        io->pendingEvents &= ~EV_WRITE;
507    }
508}
509
510void
511tr_peerIoSetEnabled( tr_peerIo    * io,
512                     tr_direction   dir,
513                     tr_bool        isEnabled )
514{
515    const short event = dir == TR_UP ? EV_WRITE : EV_READ;
516
517    assert( tr_isPeerIo( io ) );
518    assert( tr_isDirection( dir ) );
519    assert( tr_amInEventThread( io->session ) );
520    assert( io->session->events != NULL );
521
522    if( isEnabled )
523        event_enable( io, event );
524    else
525        event_disable( io, event );
526}
527
528/***
529****
530***/
531
532static void
533io_dtor( void * vio )
534{
535    tr_peerIo * io = vio;
536
537    assert( tr_isPeerIo( io ) );
538    assert( tr_amInEventThread( io->session ) );
539    assert( io->session->events != NULL );
540
541    dbgmsg( io, "in tr_peerIo destructor" );
542    event_disable( io, EV_READ | EV_WRITE );
543    tr_bandwidthDestruct( &io->bandwidth );
544    evbuffer_free( io->outbuf );
545    evbuffer_free( io->inbuf );
546    tr_netClose( io->session, io->socket );
547    tr_cryptoFree( io->crypto );
548    tr_list_free( &io->outbuf_datatypes, tr_free );
549
550    memset( io, ~0, sizeof( tr_peerIo ) );
551    tr_free( io );
552}
553
554static void
555tr_peerIoFree( tr_peerIo * io )
556{
557    if( io )
558    {
559        dbgmsg( io, "in tr_peerIoFree" );
560        io->canRead = NULL;
561        io->didWrite = NULL;
562        io->gotError = NULL;
563        tr_runInEventThread( io->session, io_dtor, io );
564    }
565}
566
567void
568tr_peerIoRefImpl( const char * file, int line, tr_peerIo * io )
569{
570    assert( tr_isPeerIo( io ) );
571
572    dbgmsg( io, "%s:%d is incrementing the IO's refcount from %d to %d",
573                file, line, io->refCount, io->refCount+1 );
574
575    ++io->refCount;
576}
577
578void
579tr_peerIoUnrefImpl( const char * file, int line, tr_peerIo * io )
580{
581    assert( tr_isPeerIo( io ) );
582
583    dbgmsg( io, "%s:%d is decrementing the IO's refcount from %d to %d",
584                file, line, io->refCount, io->refCount-1 );
585
586    if( !--io->refCount )
587        tr_peerIoFree( io );
588}
589
590const tr_address*
591tr_peerIoGetAddress( const tr_peerIo * io, tr_port   * port )
592{
593    assert( tr_isPeerIo( io ) );
594
595    if( port )
596        *port = io->port;
597
598    return &io->addr;
599}
600
601const char*
602tr_peerIoAddrStr( const tr_address * addr, tr_port port )
603{
604    static char buf[512];
605
606    if( addr->type == TR_AF_INET )
607        tr_snprintf( buf, sizeof( buf ), "%s:%u", tr_ntop_non_ts( addr ), ntohs( port ) );
608    else
609        tr_snprintf( buf, sizeof( buf ), "[%s]:%u", tr_ntop_non_ts( addr ), ntohs( port ) );
610    return buf;
611}
612
613void
614tr_peerIoSetIOFuncs( tr_peerIo        * io,
615                     tr_can_read_cb     readcb,
616                     tr_did_write_cb    writecb,
617                     tr_net_error_cb    errcb,
618                     void             * userData )
619{
620    io->canRead = readcb;
621    io->didWrite = writecb;
622    io->gotError = errcb;
623    io->userData = userData;
624}
625
626void
627tr_peerIoClear( tr_peerIo * io )
628{
629    tr_peerIoSetIOFuncs( io, NULL, NULL, NULL, NULL );
630    tr_peerIoSetEnabled( io, TR_UP, FALSE );
631    tr_peerIoSetEnabled( io, TR_DOWN, FALSE );
632}
633
634int
635tr_peerIoReconnect( tr_peerIo * io )
636{
637    int pendingEvents;
638    tr_session * session;
639
640    assert( tr_isPeerIo( io ) );
641    assert( !tr_peerIoIsIncoming( io ) );
642
643    session = tr_peerIoGetSession( io );
644
645    pendingEvents = io->pendingEvents;
646    event_disable( io, EV_READ | EV_WRITE );
647
648    if( io->socket >= 0 )
649        tr_netClose( session, io->socket );
650
651    io->socket = tr_netOpenPeerSocket( session, &io->addr, io->port, io->isSeed );
652    event_set( &io->event_read, io->socket, EV_READ, event_read_cb, io );
653    event_set( &io->event_write, io->socket, EV_WRITE, event_write_cb, io );
654
655    if( io->socket >= 0 )
656    {
657        event_enable( io, pendingEvents );
658        tr_netSetTOS( io->socket, session->peerSocketTOS );
659        maybeSetCongestionAlgorithm( io->socket, session->peer_congestion_algorithm );
660        return 0;
661    }
662
663    return -1;
664}
665
666/**
667***
668**/
669
670void
671tr_peerIoSetTorrentHash( tr_peerIo *     io,
672                         const uint8_t * hash )
673{
674    assert( tr_isPeerIo( io ) );
675
676    tr_cryptoSetTorrentHash( io->crypto, hash );
677}
678
679const uint8_t*
680tr_peerIoGetTorrentHash( tr_peerIo * io )
681{
682    assert( tr_isPeerIo( io ) );
683    assert( io->crypto );
684
685    return tr_cryptoGetTorrentHash( io->crypto );
686}
687
688int
689tr_peerIoHasTorrentHash( const tr_peerIo * io )
690{
691    assert( tr_isPeerIo( io ) );
692    assert( io->crypto );
693
694    return tr_cryptoHasTorrentHash( io->crypto );
695}
696
697/**
698***
699**/
700
701void
702tr_peerIoSetPeersId( tr_peerIo *     io,
703                     const uint8_t * peer_id )
704{
705    assert( tr_isPeerIo( io ) );
706
707    if( ( io->peerIdIsSet = peer_id != NULL ) )
708        memcpy( io->peerId, peer_id, 20 );
709    else
710        memset( io->peerId, 0, 20 );
711}
712
713/**
714***
715**/
716
717static size_t
718getDesiredOutputBufferSize( const tr_peerIo * io, uint64_t now )
719{
720    /* this is all kind of arbitrary, but what seems to work well is
721     * being large enough to hold the next 20 seconds' worth of input,
722     * or a few blocks, whichever is bigger.
723     * It's okay to tweak this as needed */
724    const double currentSpeed = tr_bandwidthGetPieceSpeed( &io->bandwidth, now, TR_UP );
725    const double period = 15; /* arbitrary */
726    const double numBlocks = 3.5; /* the 3 is arbitrary; the .5 is to leave room for messages */
727    return MAX( MAX_BLOCK_SIZE*numBlocks, currentSpeed*1024*period );
728}
729
730size_t
731tr_peerIoGetWriteBufferSpace( const tr_peerIo * io, uint64_t now )
732{
733    const size_t desiredLen = getDesiredOutputBufferSize( io, now );
734    const size_t currentLen = EVBUFFER_LENGTH( io->outbuf );
735    size_t freeSpace = 0;
736
737    if( desiredLen > currentLen )
738        freeSpace = desiredLen - currentLen;
739
740    return freeSpace;
741}
742
743/**
744***
745**/
746
747void
748tr_peerIoSetEncryption( tr_peerIo * io,
749                        int         encryptionMode )
750{
751    assert( tr_isPeerIo( io ) );
752    assert( encryptionMode == PEER_ENCRYPTION_NONE
753         || encryptionMode == PEER_ENCRYPTION_RC4 );
754
755    io->encryptionMode = encryptionMode;
756}
757
758/**
759***
760**/
761
762void
763tr_peerIoWrite( tr_peerIo   * io,
764                const void  * bytes,
765                size_t        byteCount,
766                tr_bool       isPieceData )
767{
768    /* FIXME(libevent2): this implementation snould be moved to tr_peerIoWriteBuf.   This function should be implemented as evbuffer_new() + evbuffer_add_reference() + a call to tr_peerIoWriteBuf() + evbuffer_free() */
769    struct tr_datatype * datatype;
770
771    assert( tr_amInEventThread( io->session ) );
772    dbgmsg( io, "adding %zu bytes into io->output", byteCount );
773
774    datatype = tr_new( struct tr_datatype, 1 );
775    datatype->isPieceData = isPieceData != 0;
776    datatype->length = byteCount;
777    tr_list_append( &io->outbuf_datatypes, datatype );
778
779    switch( io->encryptionMode )
780    {
781        case PEER_ENCRYPTION_RC4:
782        {
783            /* FIXME(libevent2): use evbuffer_reserve_space() and evbuffer_commit_space() instead of tmp */
784            void * tmp = tr_sessionGetBuffer( io->session );
785            const size_t tmplen = SESSION_BUFFER_SIZE;
786            const uint8_t * walk = bytes;
787            evbuffer_expand( io->outbuf, byteCount );
788            while( byteCount > 0 )
789            {
790                const size_t thisPass = MIN( byteCount, tmplen );
791                tr_cryptoEncrypt( io->crypto, thisPass, walk, tmp );
792                evbuffer_add( io->outbuf, tmp, thisPass );
793                walk += thisPass;
794                byteCount -= thisPass;
795            }
796            tr_sessionReleaseBuffer( io->session );
797            break;
798        }
799
800        case PEER_ENCRYPTION_NONE:
801            evbuffer_add( io->outbuf, bytes, byteCount );
802            break;
803
804        default:
805            assert( 0 );
806            break;
807    }
808}
809
810void
811tr_peerIoWriteBuf( tr_peerIo         * io,
812                   struct evbuffer   * buf,
813                   tr_bool             isPieceData )
814{
815    /* FIXME(libevent2): loop through calls to evbuffer_get_contiguous_space() + evbuffer_drain() */
816    const size_t n = EVBUFFER_LENGTH( buf );
817    tr_peerIoWrite( io, EVBUFFER_DATA( buf ), n, isPieceData );
818    evbuffer_drain( buf, n );
819}
820
821/***
822****
823***/
824
825void
826tr_peerIoReadBytes( tr_peerIo       * io,
827                    struct evbuffer * inbuf,
828                    void            * bytes,
829                    size_t            byteCount )
830{
831    assert( tr_isPeerIo( io ) );
832    /* FIXME(libevent2): use evbuffer_get_length() */
833    assert( EVBUFFER_LENGTH( inbuf ) >= byteCount );
834
835    switch( io->encryptionMode )
836    {
837        case PEER_ENCRYPTION_NONE:
838            evbuffer_remove( inbuf, bytes, byteCount );
839            break;
840
841        case PEER_ENCRYPTION_RC4:
842            /* FIXME(libevent2): loop through calls to evbuffer_get_contiguous_space() + evbuffer_drain() */
843            tr_cryptoDecrypt( io->crypto, byteCount, EVBUFFER_DATA(inbuf), bytes );
844            evbuffer_drain(inbuf, byteCount );
845            break;
846
847        default:
848            assert( 0 );
849    }
850}
851
852void
853tr_peerIoDrain( tr_peerIo       * io,
854                struct evbuffer * inbuf,
855                size_t            byteCount )
856{
857    void * buf = tr_sessionGetBuffer( io->session );
858    const size_t buflen = SESSION_BUFFER_SIZE;
859
860    while( byteCount > 0 )
861    {
862        const size_t thisPass = MIN( byteCount, buflen );
863        tr_peerIoReadBytes( io, inbuf, buf, thisPass );
864        byteCount -= thisPass;
865    }
866
867    tr_sessionReleaseBuffer( io->session );
868}
869
870/***
871****
872***/
873
874static int
875tr_peerIoTryRead( tr_peerIo * io, size_t howmuch )
876{
877    int res = 0;
878
879    if(( howmuch = tr_bandwidthClamp( &io->bandwidth, TR_DOWN, howmuch )))
880    {
881        int e;
882        errno = 0;
883        res = evbuffer_read( io->inbuf, io->socket, howmuch );
884        e = errno;
885
886        dbgmsg( io, "read %d from peer (%s)", res, (res==-1?strerror(e):"") );
887
888        if( EVBUFFER_LENGTH( io->inbuf ) )
889            canReadWrapper( io );
890
891        if( ( res <= 0 ) && ( io->gotError ) && ( e != EAGAIN ) && ( e != EINTR ) && ( e != EINPROGRESS ) )
892        {
893            short what = EVBUFFER_READ | EVBUFFER_ERROR;
894            if( res == 0 )
895                what |= EVBUFFER_EOF;
896            dbgmsg( io, "tr_peerIoTryRead got an error. res is %d, what is %hd, errno is %d (%s)", res, what, e, strerror( e ) );
897            io->gotError( io, what, io->userData );
898        }
899    }
900
901    return res;
902}
903
904static int
905tr_peerIoTryWrite( tr_peerIo * io, size_t howmuch )
906{
907    int n = 0;
908
909    if(( howmuch = tr_bandwidthClamp( &io->bandwidth, TR_UP, howmuch )))
910    {
911        int e;
912        errno = 0;
913        n = tr_evbuffer_write( io, io->socket, howmuch );
914        e = errno;
915
916        if( n > 0 )
917            didWriteWrapper( io, n );
918
919        if( ( n < 0 ) && ( io->gotError ) && ( e != EPIPE ) && ( e != EAGAIN ) && ( e != EINTR ) && ( e != EINPROGRESS ) )
920        {
921            const short what = EVBUFFER_WRITE | EVBUFFER_ERROR;
922            dbgmsg( io, "tr_peerIoTryWrite got an error. res is %d, what is %hd, errno is %d (%s)", n, what, e, strerror( e ) );
923
924            if( io->gotError != NULL )
925                io->gotError( io, what, io->userData );
926        }
927    }
928
929    return n;
930}
931
932int
933tr_peerIoFlush( tr_peerIo  * io, tr_direction dir, size_t limit )
934{
935    int bytesUsed = 0;
936
937    assert( tr_isPeerIo( io ) );
938    assert( tr_isDirection( dir ) );
939
940    if( io->hasFinishedConnecting )
941    {
942        if( dir == TR_DOWN )
943            bytesUsed = tr_peerIoTryRead( io, limit );
944        else
945            bytesUsed = tr_peerIoTryWrite( io, limit );
946    }
947
948    dbgmsg( io, "flushing peer-io, hasFinishedConnecting %d, direction %d, limit %zu, bytesUsed %d", (int)io->hasFinishedConnecting, (int)dir, limit, bytesUsed );
949    return bytesUsed;
950}
951
952int
953tr_peerIoFlushOutgoingProtocolMsgs( tr_peerIo * io )
954{
955    size_t byteCount = 0;
956    tr_list * it;
957
958    /* count up how many bytes are used by non-piece-data messages
959       at the front of our outbound queue */
960    for( it=io->outbuf_datatypes; it!=NULL; it=it->next )
961    {
962        struct tr_datatype * d = it->data;
963
964        if( d->isPieceData )
965            break;
966
967        byteCount += d->length;
968    }
969
970    return tr_peerIoFlush( io, TR_UP, byteCount );
971}
Note: See TracBrowser for help on using the repository browser.