Revert "transmission: update from 2.13 to 2.22"
[tomato.git] / release / src / router / transmission / libtransmission / handshake.c
blobaac9741ae6a51a3adab4f7dd89fdf252c0442767
1 /*
2 * This file Copyright (C) 2007-2010 Mnemosyne LLC
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.
10 * $Id: handshake.c 10912 2010-06-30 16:40:19Z charles $
13 #include <assert.h>
14 #include <errno.h>
15 #include <inttypes.h>
16 #include <limits.h> /* UCHAR_MAX */
17 #include <string.h>
18 #include <stdio.h>
20 #include <event.h>
22 #include "transmission.h"
23 #include "bencode.h"
24 #include "clients.h"
25 #include "crypto.h"
26 #include "handshake.h"
27 #include "peer-io.h"
28 #include "peer-mgr.h"
29 #include "session.h"
30 #include "torrent.h"
31 #include "tr-dht.h"
32 #include "utils.h"
34 /* enable LibTransmission extension protocol */
35 #define ENABLE_LTEP * /
36 /* fast extensions */
37 #define ENABLE_FAST * /
38 /* DHT */
39 #define ENABLE_DHT * /
41 /***
42 ****
43 ***/
45 #define HANDSHAKE_NAME "\023BitTorrent protocol"
47 enum
49 /* BitTorrent Handshake Constants */
50 HANDSHAKE_NAME_LEN = 20,
51 HANDSHAKE_FLAGS_LEN = 8,
52 HANDSHAKE_SIZE = 68,
53 PEER_ID_LEN = 20,
54 INCOMING_HANDSHAKE_LEN = 48,
56 /* Encryption Constants */
57 PadA_MAXLEN = 512,
58 PadB_MAXLEN = 512,
59 PadC_MAXLEN = 512,
60 PadD_MAXLEN = 512,
61 VC_LENGTH = 8,
62 KEY_LEN = 96,
63 CRYPTO_PROVIDE_PLAINTEXT = 1,
64 CRYPTO_PROVIDE_CRYPTO = 2,
66 /* how long to wait before giving up on a handshake */
67 HANDSHAKE_TIMEOUT_SEC = 30
71 #ifdef ENABLE_LTEP
72 #define HANDSHAKE_HAS_LTEP( bits ) ( ( ( bits )[5] & 0x10 ) ? 1 : 0 )
73 #define HANDSHAKE_SET_LTEP( bits ) ( ( bits )[5] |= 0x10 )
74 #else
75 #define HANDSHAKE_HAS_LTEP( bits ) ( 0 )
76 #define HANDSHAKE_SET_LTEP( bits ) ( (void)0 )
77 #endif
79 #ifdef ENABLE_FAST
80 #define HANDSHAKE_HAS_FASTEXT( bits ) ( ( ( bits )[7] & 0x04 ) ? 1 : 0 )
81 #define HANDSHAKE_SET_FASTEXT( bits ) ( ( bits )[7] |= 0x04 )
82 #else
83 #define HANDSHAKE_HAS_FASTEXT( bits ) ( 0 )
84 #define HANDSHAKE_SET_FASTEXT( bits ) ( (void)0 )
85 #endif
87 #ifdef ENABLE_DHT
88 #define HANDSHAKE_HAS_DHT( bits ) ( ( ( bits )[7] & 0x01 ) ? 1 : 0 )
89 #define HANDSHAKE_SET_DHT( bits ) ( ( bits )[7] |= 0x01 )
90 #else
91 #define HANDSHAKE_HAS_DHT( bits ) ( 0 )
92 #define HANDSHAKE_SET_DHT( bits ) ( (void)0 )
93 #endif
95 /* http://www.azureuswiki.com/index.php/Extension_negotiation_protocol
96 these macros are to be used if both extended messaging and the
97 azureus protocol is supported, they indicate which protocol is preferred */
98 #define HANDSHAKE_GET_EXTPREF( reserved ) ( ( reserved )[5] & 0x03 )
99 #define HANDSHAKE_SET_EXTPREF( reserved, val ) ( ( reserved )[5] |= 0x03 &\
100 ( val ) )
102 typedef uint8_t handshake_state_t;
104 struct tr_handshake
106 tr_bool haveReadAnythingFromPeer;
107 tr_bool havePeerID;
108 tr_bool haveSentBitTorrentHandshake;
109 tr_peerIo * io;
110 tr_crypto * crypto;
111 tr_session * session;
112 uint8_t mySecret[KEY_LEN];
113 handshake_state_t state;
114 tr_encryption_mode encryptionMode;
115 uint16_t pad_c_len;
116 uint16_t pad_d_len;
117 uint16_t ia_len;
118 uint32_t crypto_select;
119 uint32_t crypto_provide;
120 uint8_t myReq1[SHA_DIGEST_LENGTH];
121 handshakeDoneCB doneCB;
122 void * doneUserData;
123 struct event timeout_timer;
130 enum
132 /* incoming */
133 AWAITING_HANDSHAKE,
134 AWAITING_PEER_ID,
135 AWAITING_YA,
136 AWAITING_PAD_A,
137 AWAITING_CRYPTO_PROVIDE,
138 AWAITING_PAD_C,
139 AWAITING_IA,
140 AWAITING_PAYLOAD_STREAM,
142 /* outgoing */
143 AWAITING_YB,
144 AWAITING_VC,
145 AWAITING_CRYPTO_SELECT,
146 AWAITING_PAD_D,
153 #define dbgmsg( handshake, ... ) \
154 do { \
155 if( tr_deepLoggingIsActive( ) ) \
156 tr_deepLog( __FILE__, __LINE__, tr_peerIoGetAddrStr( handshake->io ), __VA_ARGS__ ); \
157 } while( 0 )
159 static const char*
160 getStateName( const handshake_state_t state )
162 const char * str = "f00!";
164 switch( state )
166 case AWAITING_HANDSHAKE:
167 str = "awaiting handshake"; break;
169 case AWAITING_PEER_ID:
170 str = "awaiting peer id"; break;
172 case AWAITING_YA:
173 str = "awaiting ya"; break;
175 case AWAITING_PAD_A:
176 str = "awaiting pad a"; break;
178 case AWAITING_CRYPTO_PROVIDE:
179 str = "awaiting crypto_provide"; break;
181 case AWAITING_PAD_C:
182 str = "awaiting pad c"; break;
184 case AWAITING_IA:
185 str = "awaiting ia"; break;
187 case AWAITING_YB:
188 str = "awaiting yb"; break;
190 case AWAITING_VC:
191 str = "awaiting vc"; break;
193 case AWAITING_CRYPTO_SELECT:
194 str = "awaiting crypto select"; break;
196 case AWAITING_PAD_D:
197 str = "awaiting pad d"; break;
199 return str;
202 static void
203 setState( tr_handshake * handshake, handshake_state_t state )
205 dbgmsg( handshake, "setting to state [%s]", getStateName( state ) );
206 handshake->state = state;
209 static void
210 setReadState( tr_handshake * handshake, handshake_state_t state )
212 setState( handshake, state );
215 static void
216 buildHandshakeMessage( tr_handshake * handshake, uint8_t * buf )
218 uint8_t * walk = buf;
219 const uint8_t * torrentHash = tr_cryptoGetTorrentHash( handshake->crypto );
220 const tr_torrent * tor = tr_torrentFindFromHash( handshake->session, torrentHash );
221 const uint8_t * peer_id = tor && tor->peer_id ? tor->peer_id : tr_getPeerId( );
223 memcpy( walk, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN );
224 walk += HANDSHAKE_NAME_LEN;
225 memset( walk, 0, HANDSHAKE_FLAGS_LEN );
226 HANDSHAKE_SET_LTEP( walk );
227 HANDSHAKE_SET_FASTEXT( walk );
229 /* Note that this doesn't depend on whether the torrent is private.
230 * We don't accept DHT peers for a private torrent,
231 * but we participate in the DHT regardless. */
232 if( tr_dhtEnabled( handshake->session ) )
233 HANDSHAKE_SET_DHT( walk );
235 walk += HANDSHAKE_FLAGS_LEN;
236 memcpy( walk, torrentHash, SHA_DIGEST_LENGTH );
237 walk += SHA_DIGEST_LENGTH;
238 memcpy( walk, peer_id, PEER_ID_LEN );
239 walk += PEER_ID_LEN;
241 assert( strlen( ( const char* )peer_id ) == PEER_ID_LEN );
242 assert( walk - buf == HANDSHAKE_SIZE );
245 static int tr_handshakeDone( tr_handshake * handshake,
246 tr_bool isConnected );
248 enum
250 HANDSHAKE_OK,
251 HANDSHAKE_ENCRYPTION_WRONG,
252 HANDSHAKE_BAD_TORRENT,
253 HANDSHAKE_PEER_IS_SELF,
256 static int
257 parseHandshake( tr_handshake * handshake,
258 struct evbuffer * inbuf )
260 uint8_t name[HANDSHAKE_NAME_LEN];
261 uint8_t reserved[HANDSHAKE_FLAGS_LEN];
262 uint8_t hash[SHA_DIGEST_LENGTH];
263 const tr_torrent * tor;
264 const uint8_t * tor_peer_id;
265 uint8_t peer_id[PEER_ID_LEN];
267 dbgmsg( handshake, "payload: need %d, got %zu",
268 (int)HANDSHAKE_SIZE, EVBUFFER_LENGTH( inbuf ) );
270 if( EVBUFFER_LENGTH( inbuf ) < HANDSHAKE_SIZE )
271 return READ_LATER;
273 /* confirm the protocol */
274 tr_peerIoReadBytes( handshake->io, inbuf, name, HANDSHAKE_NAME_LEN );
275 if( memcmp( name, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN ) )
276 return HANDSHAKE_ENCRYPTION_WRONG;
278 /* read the reserved bytes */
279 tr_peerIoReadBytes( handshake->io, inbuf, reserved, HANDSHAKE_FLAGS_LEN );
281 /* torrent hash */
282 tr_peerIoReadBytes( handshake->io, inbuf, hash, sizeof( hash ) );
283 assert( tr_peerIoHasTorrentHash( handshake->io ) );
284 if( !tr_torrentExists( handshake->session, hash )
285 || memcmp( hash, tr_peerIoGetTorrentHash( handshake->io ),
286 SHA_DIGEST_LENGTH ) )
288 dbgmsg( handshake, "peer returned the wrong hash. wtf?" );
289 return HANDSHAKE_BAD_TORRENT;
292 /* peer_id */
293 tr_peerIoReadBytes( handshake->io, inbuf, peer_id, sizeof( peer_id ) );
294 tr_peerIoSetPeersId( handshake->io, peer_id );
296 /* peer id */
297 handshake->havePeerID = TRUE;
298 dbgmsg( handshake, "peer-id is [%*.*s]", PEER_ID_LEN, PEER_ID_LEN, peer_id );
300 tor = tr_torrentFindFromHash( handshake->session, hash );
301 tor_peer_id = tor && tor->peer_id ? tor->peer_id : tr_getPeerId( );
302 if( !memcmp( peer_id, tor_peer_id, PEER_ID_LEN ) )
304 dbgmsg( handshake, "streuth! we've connected to ourselves." );
305 return HANDSHAKE_PEER_IS_SELF;
309 *** Extensions
312 tr_peerIoEnableLTEP( handshake->io, HANDSHAKE_HAS_LTEP( reserved ) );
314 tr_peerIoEnableFEXT( handshake->io, HANDSHAKE_HAS_FASTEXT( reserved ) );
316 tr_peerIoEnableDHT( handshake->io, HANDSHAKE_HAS_DHT( reserved ) );
318 return HANDSHAKE_OK;
321 /***
322 ****
323 **** OUTGOING CONNECTIONS
324 ****
325 ***/
327 /* 1 A->B: Diffie Hellman Ya, PadA */
328 static void
329 sendYa( tr_handshake * handshake )
331 int len;
332 const uint8_t * public_key;
333 char outbuf[ KEY_LEN + PadA_MAXLEN ], *walk=outbuf;
335 /* add our public key (Ya) */
336 public_key = tr_cryptoGetMyPublicKey( handshake->crypto, &len );
337 assert( len == KEY_LEN );
338 assert( public_key );
339 memcpy( walk, public_key, len );
340 walk += len;
342 /* add some bullshit padding */
343 len = tr_cryptoRandInt( PadA_MAXLEN );
344 tr_cryptoRandBuf( walk, len );
345 walk += len;
347 /* send it */
348 setReadState( handshake, AWAITING_YB );
349 tr_peerIoWrite( handshake->io, outbuf, walk - outbuf, FALSE );
352 static uint32_t
353 getCryptoProvide( const tr_handshake * handshake )
355 uint32_t provide = 0;
357 switch( handshake->encryptionMode )
359 case TR_ENCRYPTION_REQUIRED:
360 case TR_ENCRYPTION_PREFERRED:
361 provide |= CRYPTO_PROVIDE_CRYPTO;
362 break;
364 case TR_CLEAR_PREFERRED:
365 provide |= CRYPTO_PROVIDE_CRYPTO | CRYPTO_PROVIDE_PLAINTEXT;
366 break;
369 return provide;
372 static uint32_t
373 getCryptoSelect( const tr_handshake * handshake,
374 uint32_t crypto_provide )
376 uint32_t choices[2];
377 int i, nChoices = 0;
379 switch( handshake->encryptionMode )
381 case TR_ENCRYPTION_REQUIRED:
382 choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
383 break;
385 case TR_ENCRYPTION_PREFERRED:
386 choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
387 choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
388 break;
390 case TR_CLEAR_PREFERRED:
391 choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
392 choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
393 break;
396 for( i = 0; i < nChoices; ++i )
397 if( crypto_provide & choices[i] )
398 return choices[i];
400 return 0;
403 static int
404 readYb( tr_handshake * handshake,
405 struct evbuffer * inbuf )
407 int isEncrypted;
408 const uint8_t * secret;
409 uint8_t yb[KEY_LEN];
410 struct evbuffer * outbuf;
411 size_t needlen = HANDSHAKE_NAME_LEN;
413 if( EVBUFFER_LENGTH( inbuf ) < needlen )
414 return READ_LATER;
416 isEncrypted = memcmp( EVBUFFER_DATA( inbuf ), HANDSHAKE_NAME, HANDSHAKE_NAME_LEN );
417 if( isEncrypted )
419 needlen = KEY_LEN;
420 if( EVBUFFER_LENGTH( inbuf ) < needlen )
421 return READ_LATER;
424 dbgmsg( handshake, "got a %s handshake",
425 ( isEncrypted ? "encrypted" : "plaintext" ) );
427 tr_peerIoSetEncryption( handshake->io, isEncrypted ? PEER_ENCRYPTION_RC4
428 : PEER_ENCRYPTION_NONE );
429 if( !isEncrypted )
431 setState( handshake, AWAITING_HANDSHAKE );
432 return READ_NOW;
435 handshake->haveReadAnythingFromPeer = TRUE;
437 /* compute the secret */
438 evbuffer_remove( inbuf, yb, KEY_LEN );
439 secret = tr_cryptoComputeSecret( handshake->crypto, yb );
440 memcpy( handshake->mySecret, secret, KEY_LEN );
442 /* now send these: HASH('req1', S), HASH('req2', SKEY) xor HASH('req3', S),
443 * ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)), ENCRYPT(IA) */
444 outbuf = evbuffer_new( );
446 /* HASH('req1', S) */
448 uint8_t req1[SHA_DIGEST_LENGTH];
449 tr_sha1( req1, "req1", 4, secret, KEY_LEN, NULL );
450 evbuffer_add( outbuf, req1, SHA_DIGEST_LENGTH );
453 /* HASH('req2', SKEY) xor HASH('req3', S) */
455 int i;
456 uint8_t req2[SHA_DIGEST_LENGTH];
457 uint8_t req3[SHA_DIGEST_LENGTH];
458 uint8_t buf[SHA_DIGEST_LENGTH];
459 tr_sha1( req2, "req2", 4,
460 tr_cryptoGetTorrentHash( handshake->crypto ),
461 SHA_DIGEST_LENGTH, NULL );
462 tr_sha1( req3, "req3", 4, secret, KEY_LEN, NULL );
463 for( i = 0; i < SHA_DIGEST_LENGTH; ++i )
464 buf[i] = req2[i] ^ req3[i];
465 evbuffer_add( outbuf, buf, SHA_DIGEST_LENGTH );
468 /* ENCRYPT(VC, crypto_provide, len(PadC), PadC
469 * PadC is reserved for future extensions to the handshake...
470 * standard practice at this time is for it to be zero-length */
472 uint8_t vc[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
474 tr_peerIoWriteBuf( handshake->io, outbuf, FALSE );
475 tr_cryptoEncryptInit( handshake->crypto );
476 tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_RC4 );
478 tr_peerIoWriteBytes( handshake->io, outbuf, vc, VC_LENGTH );
479 tr_peerIoWriteUint32( handshake->io, outbuf,
480 getCryptoProvide( handshake ) );
481 tr_peerIoWriteUint16( handshake->io, outbuf, 0 );
484 /* ENCRYPT len(IA)), ENCRYPT(IA) */
486 uint8_t msg[HANDSHAKE_SIZE];
487 buildHandshakeMessage( handshake, msg );
489 tr_peerIoWriteUint16( handshake->io, outbuf, sizeof( msg ) );
490 tr_peerIoWriteBytes( handshake->io, outbuf, msg, sizeof( msg ) );
492 handshake->haveSentBitTorrentHandshake = 1;
495 /* send it */
496 tr_cryptoDecryptInit( handshake->crypto );
497 setReadState( handshake, AWAITING_VC );
498 tr_peerIoWriteBuf( handshake->io, outbuf, FALSE );
500 /* cleanup */
501 evbuffer_free( outbuf );
502 return READ_LATER;
505 static int
506 readVC( tr_handshake * handshake,
507 struct evbuffer * inbuf )
509 const uint8_t key[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
510 const int key_len = VC_LENGTH;
511 uint8_t tmp[VC_LENGTH];
513 /* note: this works w/o having to `unwind' the buffer if
514 * we read too much, but it is pretty brute-force.
515 * it would be nice to make this cleaner. */
516 for( ; ; )
518 if( EVBUFFER_LENGTH( inbuf ) < VC_LENGTH )
520 dbgmsg( handshake, "not enough bytes... returning read_more" );
521 return READ_LATER;
524 memcpy( tmp, EVBUFFER_DATA( inbuf ), key_len );
525 tr_cryptoDecryptInit( handshake->crypto );
526 tr_cryptoDecrypt( handshake->crypto, key_len, tmp, tmp );
527 if( !memcmp( tmp, key, key_len ) )
528 break;
530 evbuffer_drain( inbuf, 1 );
533 dbgmsg( handshake, "got it!" );
534 evbuffer_drain( inbuf, key_len );
535 setState( handshake, AWAITING_CRYPTO_SELECT );
536 return READ_NOW;
539 static int
540 readCryptoSelect( tr_handshake * handshake,
541 struct evbuffer * inbuf )
543 uint32_t crypto_select;
544 uint16_t pad_d_len;
545 const size_t needlen = sizeof( uint32_t ) + sizeof( uint16_t );
547 if( EVBUFFER_LENGTH( inbuf ) < needlen )
548 return READ_LATER;
550 tr_peerIoReadUint32( handshake->io, inbuf, &crypto_select );
551 handshake->crypto_select = crypto_select;
552 dbgmsg( handshake, "crypto select is %d", (int)crypto_select );
553 if( !( crypto_select & getCryptoProvide( handshake ) ) )
555 dbgmsg( handshake,
556 "peer selected an encryption option we didn't provide" );
557 return tr_handshakeDone( handshake, FALSE );
560 tr_peerIoReadUint16( handshake->io, inbuf, &pad_d_len );
561 dbgmsg( handshake, "pad_d_len is %d", (int)pad_d_len );
563 if( pad_d_len > 512 )
565 dbgmsg( handshake, "encryption handshake: pad_d_len is too long" );
566 return tr_handshakeDone( handshake, FALSE );
569 handshake->pad_d_len = pad_d_len;
571 setState( handshake, AWAITING_PAD_D );
572 return READ_NOW;
575 static int
576 readPadD( tr_handshake * handshake,
577 struct evbuffer * inbuf )
579 const size_t needlen = handshake->pad_d_len;
580 uint8_t * tmp;
582 dbgmsg( handshake, "pad d: need %zu, got %zu",
583 needlen, EVBUFFER_LENGTH( inbuf ) );
584 if( EVBUFFER_LENGTH( inbuf ) < needlen )
585 return READ_LATER;
587 tmp = tr_new( uint8_t, needlen );
588 tr_peerIoReadBytes( handshake->io, inbuf, tmp, needlen );
589 tr_free( tmp );
591 tr_peerIoSetEncryption( handshake->io, handshake->crypto_select );
593 setState( handshake, AWAITING_HANDSHAKE );
594 return READ_NOW;
597 /***
598 ****
599 **** INCOMING CONNECTIONS
600 ****
601 ***/
603 static int
604 readHandshake( tr_handshake * handshake,
605 struct evbuffer * inbuf )
607 uint8_t pstrlen;
608 uint8_t * pstr;
609 uint8_t reserved[HANDSHAKE_FLAGS_LEN];
610 uint8_t hash[SHA_DIGEST_LENGTH];
612 dbgmsg( handshake, "payload: need %d, got %zu",
613 (int)INCOMING_HANDSHAKE_LEN, EVBUFFER_LENGTH( inbuf ) );
615 if( EVBUFFER_LENGTH( inbuf ) < INCOMING_HANDSHAKE_LEN )
616 return READ_LATER;
618 handshake->haveReadAnythingFromPeer = TRUE;
620 pstrlen = EVBUFFER_DATA( inbuf )[0]; /* peek, don't read. We may be
621 handing inbuf to AWAITING_YA */
623 if( pstrlen == 19 ) /* unencrypted */
625 tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_NONE );
627 if( handshake->encryptionMode == TR_ENCRYPTION_REQUIRED )
629 dbgmsg( handshake,
630 "peer is unencrypted, and we're disallowing that" );
631 return tr_handshakeDone( handshake, FALSE );
634 else /* encrypted or corrupt */
636 tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_RC4 );
638 if( tr_peerIoIsIncoming( handshake->io ) )
640 dbgmsg( handshake,
641 "I think peer is sending us an encrypted handshake..." );
642 setState( handshake, AWAITING_YA );
643 return READ_NOW;
645 tr_cryptoDecrypt( handshake->crypto, 1, &pstrlen, &pstrlen );
647 if( pstrlen != 19 )
649 dbgmsg( handshake,
650 "I think peer has sent us a corrupt handshake..." );
651 return tr_handshakeDone( handshake, FALSE );
655 evbuffer_drain( inbuf, 1 );
657 /* pstr (BitTorrent) */
658 pstr = tr_new( uint8_t, pstrlen + 1 );
659 tr_peerIoReadBytes( handshake->io, inbuf, pstr, pstrlen );
660 pstr[pstrlen] = '\0';
661 if( strcmp( (char*)pstr, "BitTorrent protocol" ) )
663 tr_free( pstr );
664 return tr_handshakeDone( handshake, FALSE );
666 tr_free( pstr );
668 /* reserved bytes */
669 tr_peerIoReadBytes( handshake->io, inbuf, reserved, sizeof( reserved ) );
672 *** Extensions
675 tr_peerIoEnableLTEP( handshake->io, HANDSHAKE_HAS_LTEP( reserved ) );
677 tr_peerIoEnableFEXT( handshake->io, HANDSHAKE_HAS_FASTEXT( reserved ) );
679 tr_peerIoEnableDHT( handshake->io, HANDSHAKE_HAS_DHT( reserved ) );
681 /* torrent hash */
682 tr_peerIoReadBytes( handshake->io, inbuf, hash, sizeof( hash ) );
683 if( tr_peerIoIsIncoming( handshake->io ) )
685 if( !tr_torrentExists( handshake->session, hash ) )
687 dbgmsg( handshake, "peer is trying to connect to us for a torrent we don't have." );
688 return tr_handshakeDone( handshake, FALSE );
690 else
692 assert( !tr_peerIoHasTorrentHash( handshake->io ) );
693 tr_peerIoSetTorrentHash( handshake->io, hash );
696 else /* outgoing */
698 assert( tr_peerIoHasTorrentHash( handshake->io ) );
699 if( memcmp( hash, tr_peerIoGetTorrentHash( handshake->io ),
700 SHA_DIGEST_LENGTH ) )
702 dbgmsg( handshake, "peer returned the wrong hash. wtf?" );
703 return tr_handshakeDone( handshake, FALSE );
708 *** If it's an incoming message, we need to send a response handshake
711 if( !handshake->haveSentBitTorrentHandshake )
713 uint8_t msg[HANDSHAKE_SIZE];
714 buildHandshakeMessage( handshake, msg );
715 tr_peerIoWrite( handshake->io, msg, sizeof( msg ), FALSE );
716 handshake->haveSentBitTorrentHandshake = 1;
719 setReadState( handshake, AWAITING_PEER_ID );
720 return READ_NOW;
723 static int
724 readPeerId( tr_handshake * handshake,
725 struct evbuffer * inbuf )
727 tr_bool peerIsGood;
728 char client[128];
729 tr_torrent * tor;
730 const uint8_t * tor_peer_id;
731 uint8_t peer_id[PEER_ID_LEN];
733 if( EVBUFFER_LENGTH( inbuf ) < PEER_ID_LEN )
734 return READ_LATER;
736 /* peer id */
737 tr_peerIoReadBytes( handshake->io, inbuf, peer_id, PEER_ID_LEN );
738 tr_peerIoSetPeersId( handshake->io, peer_id );
739 handshake->havePeerID = TRUE;
740 tr_clientForId( client, sizeof( client ), peer_id );
741 dbgmsg( handshake, "peer-id is [%s] ... isIncoming is %d", client,
742 tr_peerIoIsIncoming( handshake->io ) );
744 /* if we've somehow connected to ourselves, don't keep the connection */
745 tor = tr_torrentFindFromHash( handshake->session, tr_peerIoGetTorrentHash( handshake->io ) );
746 tor_peer_id = tor && tor->peer_id ? tor->peer_id : tr_getPeerId( );
747 peerIsGood = memcmp( peer_id, tor_peer_id, PEER_ID_LEN ) != 0;
748 dbgmsg( handshake, "isPeerGood == %d", (int)peerIsGood );
749 return tr_handshakeDone( handshake, peerIsGood );
752 static int
753 readYa( tr_handshake * handshake,
754 struct evbuffer * inbuf )
756 uint8_t ya[KEY_LEN];
757 uint8_t * walk, outbuf[KEY_LEN + PadB_MAXLEN];
758 const uint8_t *myKey, *secret;
759 int len;
761 dbgmsg( handshake, "in readYa... need %d, have %zu",
762 (int)KEY_LEN, EVBUFFER_LENGTH( inbuf ) );
763 if( EVBUFFER_LENGTH( inbuf ) < KEY_LEN )
764 return READ_LATER;
766 /* read the incoming peer's public key */
767 evbuffer_remove( inbuf, ya, KEY_LEN );
768 secret = tr_cryptoComputeSecret( handshake->crypto, ya );
769 memcpy( handshake->mySecret, secret, KEY_LEN );
770 tr_sha1( handshake->myReq1, "req1", 4, secret, KEY_LEN, NULL );
772 dbgmsg( handshake, "sending B->A: Diffie Hellman Yb, PadB" );
773 /* send our public key to the peer */
774 walk = outbuf;
775 myKey = tr_cryptoGetMyPublicKey( handshake->crypto, &len );
776 memcpy( walk, myKey, len );
777 walk += len;
778 len = tr_cryptoRandInt( PadB_MAXLEN );
779 tr_cryptoRandBuf( walk, len );
780 walk += len;
782 setReadState( handshake, AWAITING_PAD_A );
783 tr_peerIoWrite( handshake->io, outbuf, walk - outbuf, FALSE );
784 return READ_NOW;
787 static int
788 readPadA( tr_handshake * handshake,
789 struct evbuffer * inbuf )
791 uint8_t * pch;
793 dbgmsg( handshake, "looking to get past pad a... & resync on hash('req',S) ... have %zu bytes",
794 EVBUFFER_LENGTH( inbuf ) );
796 *** Resynchronizing on HASH('req1',S)
799 pch = memchr( EVBUFFER_DATA( inbuf ),
800 handshake->myReq1[0],
801 EVBUFFER_LENGTH( inbuf ) );
802 if( pch == NULL )
804 dbgmsg( handshake, "no luck so far.. draining %zu bytes",
805 EVBUFFER_LENGTH( inbuf ) );
806 evbuffer_drain( inbuf, EVBUFFER_LENGTH( inbuf ) );
807 return READ_LATER;
809 dbgmsg( handshake, "looking for hash('req',S) ... draining %d bytes",
810 (int)( pch - EVBUFFER_DATA( inbuf ) ) );
811 evbuffer_drain( inbuf, pch - EVBUFFER_DATA( inbuf ) );
812 if( EVBUFFER_LENGTH( inbuf ) < SHA_DIGEST_LENGTH )
813 return READ_LATER;
814 if( memcmp( EVBUFFER_DATA( inbuf ), handshake->myReq1,
815 SHA_DIGEST_LENGTH ) )
817 dbgmsg( handshake, "draining one more byte" );
818 evbuffer_drain( inbuf, 1 );
819 return READ_NOW;
822 dbgmsg( handshake,
823 "found it... looking setting to awaiting_crypto_provide" );
824 setState( handshake, AWAITING_CRYPTO_PROVIDE );
825 return READ_NOW;
828 static int
829 readCryptoProvide( tr_handshake * handshake,
830 struct evbuffer * inbuf )
832 /* HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide,
833 len(PadC)) */
835 int i;
836 uint8_t vc_in[VC_LENGTH];
837 uint8_t req2[SHA_DIGEST_LENGTH];
838 uint8_t req3[SHA_DIGEST_LENGTH];
839 uint8_t obfuscatedTorrentHash[SHA_DIGEST_LENGTH];
840 uint16_t padc_len = 0;
841 uint32_t crypto_provide = 0;
842 const size_t needlen = SHA_DIGEST_LENGTH /* HASH('req1',s) */
843 + SHA_DIGEST_LENGTH /* HASH('req2', SKEY) xor
844 HASH('req3', S) */
845 + VC_LENGTH
846 + sizeof( crypto_provide )
847 + sizeof( padc_len );
848 tr_torrent * tor = NULL;
850 if( EVBUFFER_LENGTH( inbuf ) < needlen )
851 return READ_LATER;
853 /* TODO: confirm they sent HASH('req1',S) here? */
854 evbuffer_drain( inbuf, SHA_DIGEST_LENGTH );
856 /* This next piece is HASH('req2', SKEY) xor HASH('req3', S) ...
857 * we can get the first half of that (the obufscatedTorrentHash)
858 * by building the latter and xor'ing it with what the peer sent us */
859 dbgmsg( handshake, "reading obfuscated torrent hash..." );
860 evbuffer_remove( inbuf, req2, SHA_DIGEST_LENGTH );
861 tr_sha1( req3, "req3", 4, handshake->mySecret, KEY_LEN, NULL );
862 for( i = 0; i < SHA_DIGEST_LENGTH; ++i )
863 obfuscatedTorrentHash[i] = req2[i] ^ req3[i];
864 if(( tor = tr_torrentFindFromObfuscatedHash( handshake->session, obfuscatedTorrentHash )))
866 const tr_bool clientIsSeed = tr_torrentIsSeed( tor );
867 const tr_bool peerIsSeed = tr_peerMgrPeerIsSeed( tor, tr_peerIoGetAddress( handshake->io, NULL ) );
868 dbgmsg( handshake, "got INCOMING connection's encrypted handshake for torrent [%s]",
869 tr_torrentName( tor ) );
870 tr_peerIoSetTorrentHash( handshake->io, tor->info.hash );
872 if( clientIsSeed && peerIsSeed )
874 dbgmsg( handshake, "another seed tried to reconnect to us!" );
875 return tr_handshakeDone( handshake, FALSE );
878 else
880 dbgmsg( handshake, "can't find that torrent..." );
881 return tr_handshakeDone( handshake, FALSE );
884 /* next part: ENCRYPT(VC, crypto_provide, len(PadC), */
886 tr_cryptoDecryptInit( handshake->crypto );
888 tr_peerIoReadBytes( handshake->io, inbuf, vc_in, VC_LENGTH );
890 tr_peerIoReadUint32( handshake->io, inbuf, &crypto_provide );
891 handshake->crypto_provide = crypto_provide;
892 dbgmsg( handshake, "crypto_provide is %d", (int)crypto_provide );
894 tr_peerIoReadUint16( handshake->io, inbuf, &padc_len );
895 dbgmsg( handshake, "padc is %d", (int)padc_len );
896 handshake->pad_c_len = padc_len;
897 setState( handshake, AWAITING_PAD_C );
898 return READ_NOW;
901 static int
902 readPadC( tr_handshake * handshake,
903 struct evbuffer * inbuf )
905 uint16_t ia_len;
906 const size_t needlen = handshake->pad_c_len + sizeof( uint16_t );
908 if( EVBUFFER_LENGTH( inbuf ) < needlen )
909 return READ_LATER;
911 evbuffer_drain( inbuf, handshake->pad_c_len );
913 tr_peerIoReadUint16( handshake->io, inbuf, &ia_len );
914 dbgmsg( handshake, "ia_len is %d", (int)ia_len );
915 handshake->ia_len = ia_len;
916 setState( handshake, AWAITING_IA );
917 return READ_NOW;
920 static int
921 readIA( tr_handshake * handshake,
922 struct evbuffer * inbuf )
924 const size_t needlen = handshake->ia_len;
925 struct evbuffer * outbuf;
926 uint32_t crypto_select;
928 dbgmsg( handshake, "reading IA... have %zu, need %zu",
929 EVBUFFER_LENGTH( inbuf ), needlen );
930 if( EVBUFFER_LENGTH( inbuf ) < needlen )
931 return READ_LATER;
934 *** B->A: ENCRYPT(VC, crypto_select, len(padD), padD), ENCRYPT2(Payload Stream)
937 tr_cryptoEncryptInit( handshake->crypto );
938 outbuf = evbuffer_new( );
940 dbgmsg( handshake, "sending vc" );
941 /* send VC */
943 uint8_t vc[VC_LENGTH];
944 memset( vc, 0, VC_LENGTH );
945 tr_peerIoWriteBytes( handshake->io, outbuf, vc, VC_LENGTH );
948 /* send crypto_select */
949 crypto_select = getCryptoSelect( handshake, handshake->crypto_provide );
950 if( crypto_select )
952 dbgmsg( handshake, "selecting crypto mode '%d'", (int)crypto_select );
953 tr_peerIoWriteUint32( handshake->io, outbuf, crypto_select );
955 else
957 dbgmsg( handshake, "peer didn't offer an encryption mode we like." );
958 evbuffer_free( outbuf );
959 return tr_handshakeDone( handshake, FALSE );
962 dbgmsg( handshake, "sending pad d" );
963 /* ENCRYPT(VC, crypto_provide, len(PadD), PadD
964 * PadD is reserved for future extensions to the handshake...
965 * standard practice at this time is for it to be zero-length */
967 const uint16_t len = 0;
968 tr_peerIoWriteUint16( handshake->io, outbuf, len );
971 /* maybe de-encrypt our connection */
972 if( crypto_select == CRYPTO_PROVIDE_PLAINTEXT )
974 tr_peerIoWriteBuf( handshake->io, outbuf, FALSE );
975 tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_NONE );
978 dbgmsg( handshake, "sending handshake" );
979 /* send our handshake */
981 uint8_t msg[HANDSHAKE_SIZE];
982 buildHandshakeMessage( handshake, msg );
984 tr_peerIoWriteBytes( handshake->io, outbuf, msg, sizeof( msg ) );
985 handshake->haveSentBitTorrentHandshake = 1;
988 /* send it out */
989 tr_peerIoWriteBuf( handshake->io, outbuf, FALSE );
990 evbuffer_free( outbuf );
992 /* now await the handshake */
993 setState( handshake, AWAITING_PAYLOAD_STREAM );
994 return READ_NOW;
997 static int
998 readPayloadStream( tr_handshake * handshake,
999 struct evbuffer * inbuf )
1001 int i;
1002 const size_t needlen = HANDSHAKE_SIZE;
1004 dbgmsg( handshake, "reading payload stream... have %zu, need %zu",
1005 EVBUFFER_LENGTH( inbuf ), needlen );
1006 if( EVBUFFER_LENGTH( inbuf ) < needlen )
1007 return READ_LATER;
1009 /* parse the handshake ... */
1010 i = parseHandshake( handshake, inbuf );
1011 dbgmsg( handshake, "parseHandshake returned %d", i );
1012 if( i != HANDSHAKE_OK )
1013 return tr_handshakeDone( handshake, FALSE );
1015 /* we've completed the BT handshake... pass the work on to peer-msgs */
1016 return tr_handshakeDone( handshake, TRUE );
1019 /***
1020 ****
1021 ****
1022 ****
1023 ***/
1025 static ReadState
1026 canRead( struct tr_peerIo * io, void * arg, size_t * piece )
1028 tr_handshake * handshake = arg;
1029 struct evbuffer * inbuf = tr_peerIoGetReadBuffer( io );
1030 ReadState ret;
1031 tr_bool readyForMore = TRUE;
1033 assert( tr_isPeerIo( io ) );
1035 /* no piece data in handshake */
1036 *piece = 0;
1038 dbgmsg( handshake, "handling canRead; state is [%s]",
1039 getStateName( handshake->state ) );
1041 while( readyForMore )
1043 switch( handshake->state )
1045 case AWAITING_HANDSHAKE:
1046 ret = readHandshake ( handshake, inbuf ); break;
1048 case AWAITING_PEER_ID:
1049 ret = readPeerId ( handshake, inbuf ); break;
1051 case AWAITING_YA:
1052 ret = readYa ( handshake, inbuf ); break;
1054 case AWAITING_PAD_A:
1055 ret = readPadA ( handshake, inbuf ); break;
1057 case AWAITING_CRYPTO_PROVIDE:
1058 ret = readCryptoProvide( handshake, inbuf ); break;
1060 case AWAITING_PAD_C:
1061 ret = readPadC ( handshake, inbuf ); break;
1063 case AWAITING_IA:
1064 ret = readIA ( handshake, inbuf ); break;
1066 case AWAITING_PAYLOAD_STREAM:
1067 ret = readPayloadStream( handshake, inbuf ); break;
1069 case AWAITING_YB:
1070 ret = readYb ( handshake, inbuf ); break;
1072 case AWAITING_VC:
1073 ret = readVC ( handshake, inbuf ); break;
1075 case AWAITING_CRYPTO_SELECT:
1076 ret = readCryptoSelect ( handshake, inbuf ); break;
1078 case AWAITING_PAD_D:
1079 ret = readPadD ( handshake, inbuf ); break;
1081 default:
1082 assert( 0 );
1085 if( ret != READ_NOW )
1086 readyForMore = FALSE;
1087 else if( handshake->state == AWAITING_PAD_C )
1088 readyForMore = EVBUFFER_LENGTH( inbuf ) >= handshake->pad_c_len;
1089 else if( handshake->state == AWAITING_PAD_D )
1090 readyForMore = EVBUFFER_LENGTH( inbuf ) >= handshake->pad_d_len;
1091 else if( handshake->state == AWAITING_IA )
1092 readyForMore = EVBUFFER_LENGTH( inbuf ) >= handshake->ia_len;
1095 return ret;
1098 static tr_bool
1099 fireDoneFunc( tr_handshake * handshake, tr_bool isConnected )
1101 const uint8_t * peer_id = isConnected && handshake->havePeerID
1102 ? tr_peerIoGetPeersId( handshake->io )
1103 : NULL;
1104 const tr_bool success = ( *handshake->doneCB )( handshake,
1105 handshake->io,
1106 handshake->haveReadAnythingFromPeer,
1107 isConnected,
1108 peer_id,
1109 handshake->doneUserData );
1111 return success;
1114 static void
1115 tr_handshakeFree( tr_handshake * handshake )
1117 if( handshake->io )
1118 tr_peerIoUnref( handshake->io ); /* balanced by the ref in tr_handshakeNew */
1120 evtimer_del( &handshake->timeout_timer );
1122 tr_free( handshake );
1125 static int
1126 tr_handshakeDone( tr_handshake * handshake,
1127 tr_bool isOK )
1129 tr_bool success;
1131 dbgmsg( handshake, "handshakeDone: %s", isOK ? "connected" : "aborting" );
1132 tr_peerIoSetIOFuncs( handshake->io, NULL, NULL, NULL, NULL );
1134 success = fireDoneFunc( handshake, isOK );
1136 tr_handshakeFree( handshake );
1138 return success ? READ_LATER : READ_ERR;
1141 void
1142 tr_handshakeAbort( tr_handshake * handshake )
1144 if( handshake != NULL )
1145 tr_handshakeDone( handshake, FALSE );
1148 static void
1149 gotError( tr_peerIo * io UNUSED,
1150 short what,
1151 void * vhandshake )
1153 tr_handshake * handshake = vhandshake;
1155 /* if the error happened while we were sending a public key, we might
1156 * have encountered a peer that doesn't do encryption... reconnect and
1157 * try a plaintext handshake */
1158 if( ( ( handshake->state == AWAITING_YB )
1159 || ( handshake->state == AWAITING_VC ) )
1160 && ( handshake->encryptionMode != TR_ENCRYPTION_REQUIRED )
1161 && ( !tr_peerIoReconnect( handshake->io ) ) )
1163 uint8_t msg[HANDSHAKE_SIZE];
1165 dbgmsg( handshake, "handshake failed, trying plaintext..." );
1166 buildHandshakeMessage( handshake, msg );
1167 handshake->haveSentBitTorrentHandshake = 1;
1168 setReadState( handshake, AWAITING_HANDSHAKE );
1169 tr_peerIoWrite( handshake->io, msg, sizeof( msg ), FALSE );
1171 else
1173 dbgmsg( handshake, "libevent got an error what==%d, errno=%d (%s)",
1174 (int)what, errno, tr_strerror( errno ) );
1175 tr_handshakeDone( handshake, FALSE );
1183 static void
1184 handshakeTimeout( int foo UNUSED, short bar UNUSED, void * handshake )
1186 tr_handshakeAbort( handshake );
1189 tr_handshake*
1190 tr_handshakeNew( tr_peerIo * io,
1191 tr_encryption_mode encryptionMode,
1192 handshakeDoneCB doneCB,
1193 void * doneUserData )
1195 tr_handshake * handshake;
1197 handshake = tr_new0( tr_handshake, 1 );
1198 handshake->io = io;
1199 handshake->crypto = tr_peerIoGetCrypto( io );
1200 handshake->encryptionMode = encryptionMode;
1201 handshake->doneCB = doneCB;
1202 handshake->doneUserData = doneUserData;
1203 handshake->session = tr_peerIoGetSession( io );
1205 evtimer_set( &handshake->timeout_timer, handshakeTimeout, handshake );
1206 tr_timerAdd( &handshake->timeout_timer, HANDSHAKE_TIMEOUT_SEC, 0 );
1208 tr_peerIoRef( io ); /* balanced by the unref in tr_handshakeFree */
1209 tr_peerIoSetIOFuncs( handshake->io, canRead, NULL, gotError, handshake );
1210 tr_peerIoSetEncryption( io, PEER_ENCRYPTION_NONE );
1212 if( tr_peerIoIsIncoming( handshake->io ) )
1213 setReadState( handshake, AWAITING_HANDSHAKE );
1214 else if( encryptionMode != TR_CLEAR_PREFERRED )
1215 sendYa( handshake );
1216 else
1218 uint8_t msg[HANDSHAKE_SIZE];
1219 buildHandshakeMessage( handshake, msg );
1221 handshake->haveSentBitTorrentHandshake = 1;
1222 setReadState( handshake, AWAITING_HANDSHAKE );
1223 tr_peerIoWrite( handshake->io, msg, sizeof( msg ), FALSE );
1226 return handshake;
1229 struct tr_peerIo*
1230 tr_handshakeGetIO( tr_handshake * handshake )
1232 assert( handshake );
1233 assert( handshake->io );
1235 return handshake->io;
1238 struct tr_peerIo*
1239 tr_handshakeStealIO( tr_handshake * handshake )
1241 struct tr_peerIo * io;
1243 assert( handshake );
1244 assert( handshake->io );
1246 io = handshake->io;
1247 handshake->io = NULL;
1248 return io;
1251 const tr_address *
1252 tr_handshakeGetAddr( const struct tr_handshake * handshake,
1253 tr_port * port )
1255 assert( handshake );
1256 assert( handshake->io );
1258 return tr_peerIoGetAddress( handshake->io, port );