Changeset 13702


Ignore:
Timestamp:
Dec 27, 2012, 10:03:58 PM (8 years ago)
Author:
jordan
Message:

(trunk, libT) copyediting: apply the new indentation style to handshake.c. I hate making changes to this file; even changing the whitespace probably breaks all the peer connections.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/libtransmission/handshake.c

    r13670 r13702  
    4444enum
    4545{
    46     /* BitTorrent Handshake Constants */
    47     HANDSHAKE_NAME_LEN             = 20,
    48     HANDSHAKE_FLAGS_LEN            = 8,
    49     HANDSHAKE_SIZE                 = 68,
    50     INCOMING_HANDSHAKE_LEN         = 48,
    51 
    52     /* Encryption Constants */
    53     PadA_MAXLEN                    = 512,
    54     PadB_MAXLEN                    = 512,
    55     PadC_MAXLEN                    = 512,
    56     PadD_MAXLEN                    = 512,
    57     VC_LENGTH                      = 8,
    58     CRYPTO_PROVIDE_PLAINTEXT       = 1,
    59     CRYPTO_PROVIDE_CRYPTO          = 2,
    60 
    61     /* how long to wait before giving up on a handshake */
    62     HANDSHAKE_TIMEOUT_SEC          = 30
     46  /* BitTorrent Handshake Constants */
     47  HANDSHAKE_NAME_LEN             = 20,
     48  HANDSHAKE_FLAGS_LEN            = 8,
     49  HANDSHAKE_SIZE                 = 68,
     50  INCOMING_HANDSHAKE_LEN         = 48,
     51
     52  /* Encryption Constants */
     53  PadA_MAXLEN                    = 512,
     54  PadB_MAXLEN                    = 512,
     55  PadC_MAXLEN                    = 512,
     56  PadD_MAXLEN                    = 512,
     57  VC_LENGTH                      = 8,
     58  CRYPTO_PROVIDE_PLAINTEXT       = 1,
     59  CRYPTO_PROVIDE_CRYPTO          = 2,
     60
     61  /* how long to wait before giving up on a handshake */
     62  HANDSHAKE_TIMEOUT_SEC          = 30
    6363};
    6464
     
    9898struct tr_handshake
    9999{
    100     bool                  haveReadAnythingFromPeer;
    101     bool                  havePeerID;
    102     bool                  haveSentBitTorrentHandshake;
    103     tr_peerIo *           io;
    104     tr_crypto *           crypto;
    105     tr_session *          session;
    106     uint8_t               mySecret[KEY_LEN];
    107     handshake_state_t     state;
    108     tr_encryption_mode    encryptionMode;
    109     uint16_t              pad_c_len;
    110     uint16_t              pad_d_len;
    111     uint16_t              ia_len;
    112     uint32_t              crypto_select;
    113     uint32_t              crypto_provide;
    114     uint8_t               myReq1[SHA_DIGEST_LENGTH];
    115     handshakeDoneCB       doneCB;
    116     void *                doneUserData;
    117     struct event        * timeout_timer;
     100  bool                  haveReadAnythingFromPeer;
     101  bool                  havePeerID;
     102  bool                  haveSentBitTorrentHandshake;
     103  tr_peerIo *           io;
     104  tr_crypto *           crypto;
     105  tr_session *          session;
     106  uint8_t               mySecret[KEY_LEN];
     107  handshake_state_t     state;
     108  tr_encryption_mode    encryptionMode;
     109  uint16_t              pad_c_len;
     110  uint16_t              pad_d_len;
     111  uint16_t              ia_len;
     112  uint32_t              crypto_select;
     113  uint32_t              crypto_provide;
     114  uint8_t               myReq1[SHA_DIGEST_LENGTH];
     115  handshakeDoneCB       doneCB;
     116  void *                doneUserData;
     117  struct event        * timeout_timer;
    118118};
    119119
     
    124124enum
    125125{
    126     /* incoming */
    127     AWAITING_HANDSHAKE,
    128     AWAITING_PEER_ID,
    129     AWAITING_YA,
    130     AWAITING_PAD_A,
    131     AWAITING_CRYPTO_PROVIDE,
    132     AWAITING_PAD_C,
    133     AWAITING_IA,
    134     AWAITING_PAYLOAD_STREAM,
    135 
    136     /* outgoing */
    137     AWAITING_YB,
    138     AWAITING_VC,
    139     AWAITING_CRYPTO_SELECT,
    140     AWAITING_PAD_D,
     126  /* incoming */
     127  AWAITING_HANDSHAKE,
     128  AWAITING_PEER_ID,
     129  AWAITING_YA,
     130  AWAITING_PAD_A,
     131  AWAITING_CRYPTO_PROVIDE,
     132  AWAITING_PAD_C,
     133  AWAITING_IA,
     134  AWAITING_PAYLOAD_STREAM,
     135
     136  /* outgoing */
     137  AWAITING_YB,
     138  AWAITING_VC,
     139  AWAITING_CRYPTO_SELECT,
     140  AWAITING_PAD_D,
     141
     142  N_STATES
    141143};
    142144
     
    146148
    147149#define dbgmsg(handshake, ...) \
    148     do { \
    149         if (tr_deepLoggingIsActive ()) \
    150             tr_deepLog (__FILE__, __LINE__, tr_peerIoGetAddrStr (handshake->io), __VA_ARGS__); \
    151     } while (0)
     150  do { \
     151    if (tr_deepLoggingIsActive ()) \
     152      tr_deepLog (__FILE__, __LINE__, tr_peerIoGetAddrStr (handshake->io), __VA_ARGS__); \
     153  } while (0)
    152154
    153155static const char*
    154156getStateName (const handshake_state_t state)
    155157{
    156     const char * str = "f00!";
    157 
    158     switch (state)
    159     {
    160         case AWAITING_HANDSHAKE:
    161             str = "awaiting handshake"; break;
    162 
    163         case AWAITING_PEER_ID:
    164             str = "awaiting peer id"; break;
    165 
    166         case AWAITING_YA:
    167             str = "awaiting ya"; break;
    168 
    169         case AWAITING_PAD_A:
    170             str = "awaiting pad a"; break;
    171 
    172         case AWAITING_CRYPTO_PROVIDE:
    173             str = "awaiting crypto_provide"; break;
    174 
    175         case AWAITING_PAD_C:
    176             str = "awaiting pad c"; break;
    177 
    178         case AWAITING_IA:
    179             str = "awaiting ia"; break;
    180 
    181         case AWAITING_YB:
    182             str = "awaiting yb"; break;
    183 
    184         case AWAITING_VC:
    185             str = "awaiting vc"; break;
    186 
    187         case AWAITING_CRYPTO_SELECT:
    188             str = "awaiting crypto select"; break;
    189 
    190         case AWAITING_PAD_D:
    191             str = "awaiting pad d"; break;
    192     }
    193     return str;
     158  static const char * const state_strings[N_STATES] =
     159    {
     160      /* AWAITING_HANDSHAKE      */ "awaiting handshake",
     161      /* AWAITING_PEER_ID        */ "awaiting peer id",
     162      /* AWAITING_YA             */ "awaiting ya",
     163      /* AWAITING_PAD_A          */ "awaiting pad a",
     164      /* AWAITING_CRYPTO_PROVIDE */ "awaiting crypto_provide",
     165      /* AWAITING_PAD_C          */ "awaiting pad c",
     166      /* AWAITING_IA             */ "awaiting ia",
     167      /* AWAITING_PAYLOAD_STREAM */ "awaiting payload stream",
     168      /* AWAITING_YB             */ "awaiting yb",
     169      /* AWAITING_VC             */ "awaiting vc",
     170      /* AWAITING_CRYPTO_SELECT  */ "awaiting crypto select",
     171      /* AWAITING_PAD_D          */ "awaiting pad d"
     172  };
     173
     174  return state<N_STATES ? state_strings[state] : "unknown state";
    194175}
    195176
     
    197178setState (tr_handshake * handshake, handshake_state_t state)
    198179{
    199     dbgmsg (handshake, "setting to state [%s]", getStateName (state));
    200     handshake->state = state;
     180  dbgmsg (handshake, "setting to state [%s]", getStateName (state));
     181  handshake->state = state;
    201182}
    202183
     
    204185setReadState (tr_handshake * handshake, handshake_state_t state)
    205186{
    206     setState (handshake, state);
     187  setState (handshake, state);
    207188}
    208189
     
    210191buildHandshakeMessage (tr_handshake * handshake, uint8_t * buf)
    211192{
    212     uint8_t          * walk = buf;
    213     const uint8_t    * torrentHash = tr_cryptoGetTorrentHash (handshake->crypto);
    214     const tr_torrent * tor = tr_torrentFindFromHash (handshake->session, torrentHash);
    215     const uint8_t    * peer_id = tor && *tor->peer_id ? tor->peer_id : tr_getPeerId (handshake->session);
    216 
    217     memcpy (walk, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN);
    218     walk += HANDSHAKE_NAME_LEN;
    219     memset (walk, 0, HANDSHAKE_FLAGS_LEN);
    220     HANDSHAKE_SET_LTEP (walk);
    221     HANDSHAKE_SET_FASTEXT (walk);
    222 
    223     /* Note that this doesn't depend on whether the torrent is private.
    224      * We don't accept DHT peers for a private torrent,
    225      * but we participate in the DHT regardless. */
    226     if (tr_dhtEnabled (handshake->session))
    227         HANDSHAKE_SET_DHT (walk);
    228 
    229     walk += HANDSHAKE_FLAGS_LEN;
    230     memcpy (walk, torrentHash, SHA_DIGEST_LENGTH);
    231     walk += SHA_DIGEST_LENGTH;
    232     memcpy (walk, peer_id, PEER_ID_LEN);
    233     walk += PEER_ID_LEN;
    234 
    235     assert (walk - buf == HANDSHAKE_SIZE);
     193  uint8_t * walk = buf;
     194  const uint8_t * torrentHash = tr_cryptoGetTorrentHash (handshake->crypto);
     195  const tr_torrent * tor = tr_torrentFindFromHash (handshake->session, torrentHash);
     196  const uint8_t * peer_id = tor && *tor->peer_id ? tor->peer_id : tr_getPeerId (handshake->session);
     197
     198  memcpy (walk, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN);
     199  walk += HANDSHAKE_NAME_LEN;
     200  memset (walk, 0, HANDSHAKE_FLAGS_LEN);
     201  HANDSHAKE_SET_LTEP (walk);
     202  HANDSHAKE_SET_FASTEXT (walk);
     203
     204  /* Note that this doesn't depend on whether the torrent is private.
     205   * We don't accept DHT peers for a private torrent,
     206   * but we participate in the DHT regardless. */
     207  if (tr_dhtEnabled (handshake->session))
     208    HANDSHAKE_SET_DHT (walk);
     209
     210  walk += HANDSHAKE_FLAGS_LEN;
     211  memcpy (walk, torrentHash, SHA_DIGEST_LENGTH);
     212  walk += SHA_DIGEST_LENGTH;
     213  memcpy (walk, peer_id, PEER_ID_LEN);
     214  walk += PEER_ID_LEN;
     215
     216  assert (walk - buf == HANDSHAKE_SIZE);
    236217}
    237218
     
    241222enum
    242223{
    243     HANDSHAKE_OK,
    244     HANDSHAKE_ENCRYPTION_WRONG,
    245     HANDSHAKE_BAD_TORRENT,
    246     HANDSHAKE_PEER_IS_SELF,
     224  HANDSHAKE_OK,
     225  HANDSHAKE_ENCRYPTION_WRONG,
     226  HANDSHAKE_BAD_TORRENT,
     227  HANDSHAKE_PEER_IS_SELF,
    247228};
    248229
     
    251232                struct evbuffer * inbuf)
    252233{
    253     uint8_t name[HANDSHAKE_NAME_LEN];
    254     uint8_t reserved[HANDSHAKE_FLAGS_LEN];
    255     uint8_t hash[SHA_DIGEST_LENGTH];
    256     const tr_torrent * tor;
    257     const uint8_t * tor_peer_id;
    258     uint8_t peer_id[PEER_ID_LEN];
    259 
    260     dbgmsg (handshake, "payload: need %d, got %zu",
    261             HANDSHAKE_SIZE, evbuffer_get_length (inbuf));
    262 
    263     if (evbuffer_get_length (inbuf) < HANDSHAKE_SIZE)
    264         return READ_LATER;
    265 
    266     /* confirm the protocol */
    267     tr_peerIoReadBytes (handshake->io, inbuf, name, HANDSHAKE_NAME_LEN);
    268     if (memcmp (name, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN))
    269         return HANDSHAKE_ENCRYPTION_WRONG;
    270 
    271     /* read the reserved bytes */
    272     tr_peerIoReadBytes (handshake->io, inbuf, reserved, HANDSHAKE_FLAGS_LEN);
    273 
    274     /* torrent hash */
    275     tr_peerIoReadBytes (handshake->io, inbuf, hash, sizeof (hash));
    276     assert (tr_peerIoHasTorrentHash (handshake->io));
    277     if (!tr_torrentExists (handshake->session, hash)
    278       || memcmp (hash, tr_peerIoGetTorrentHash (handshake->io),
    279                  SHA_DIGEST_LENGTH))
    280     {
    281         dbgmsg (handshake, "peer returned the wrong hash. wtf?");
    282         return HANDSHAKE_BAD_TORRENT;
    283     }
    284 
    285     /* peer_id */
    286     tr_peerIoReadBytes (handshake->io, inbuf, peer_id, sizeof (peer_id));
    287     tr_peerIoSetPeersId (handshake->io, peer_id);
    288 
    289     /* peer id */
    290     handshake->havePeerID = true;
    291     dbgmsg (handshake, "peer-id is [%*.*s]", PEER_ID_LEN, PEER_ID_LEN, peer_id);
    292 
    293     tor = tr_torrentFindFromHash (handshake->session, hash);
    294     tor_peer_id = tor ? tor->peer_id : tr_getPeerId (handshake->session);
    295     if (!memcmp (peer_id, tor_peer_id, PEER_ID_LEN))
    296     {
    297         dbgmsg (handshake, "streuth!  we've connected to ourselves.");
    298         return HANDSHAKE_PEER_IS_SELF;
    299     }
    300 
    301     /**
    302     *** Extensions
    303     **/
    304 
    305     tr_peerIoEnableLTEP (handshake->io, HANDSHAKE_HAS_LTEP (reserved));
    306 
    307     tr_peerIoEnableFEXT (handshake->io, HANDSHAKE_HAS_FASTEXT (reserved));
    308 
    309     tr_peerIoEnableDHT (handshake->io, HANDSHAKE_HAS_DHT (reserved));
    310 
    311     return HANDSHAKE_OK;
     234  uint8_t name[HANDSHAKE_NAME_LEN];
     235  uint8_t reserved[HANDSHAKE_FLAGS_LEN];
     236  uint8_t hash[SHA_DIGEST_LENGTH];
     237  const tr_torrent * tor;
     238  const uint8_t * tor_peer_id;
     239  uint8_t peer_id[PEER_ID_LEN];
     240
     241  dbgmsg (handshake, "payload: need %d, got %zu",
     242          HANDSHAKE_SIZE, evbuffer_get_length (inbuf));
     243
     244  if (evbuffer_get_length (inbuf) < HANDSHAKE_SIZE)
     245    return READ_LATER;
     246
     247  /* confirm the protocol */
     248  tr_peerIoReadBytes (handshake->io, inbuf, name, HANDSHAKE_NAME_LEN);
     249  if (memcmp (name, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN))
     250    return HANDSHAKE_ENCRYPTION_WRONG;
     251
     252  /* read the reserved bytes */
     253  tr_peerIoReadBytes (handshake->io, inbuf, reserved, HANDSHAKE_FLAGS_LEN);
     254
     255  /* torrent hash */
     256  tr_peerIoReadBytes (handshake->io, inbuf, hash, sizeof (hash));
     257  assert (tr_peerIoHasTorrentHash (handshake->io));
     258  if (!tr_torrentExists (handshake->session, hash)
     259      || memcmp (hash, tr_peerIoGetTorrentHash (handshake->io), SHA_DIGEST_LENGTH))
     260    {
     261      dbgmsg (handshake, "peer returned the wrong hash. wtf?");
     262      return HANDSHAKE_BAD_TORRENT;
     263    }
     264
     265  /* peer_id */
     266  tr_peerIoReadBytes (handshake->io, inbuf, peer_id, sizeof (peer_id));
     267  tr_peerIoSetPeersId (handshake->io, peer_id);
     268
     269  /* peer id */
     270  handshake->havePeerID = true;
     271  dbgmsg (handshake, "peer-id is [%*.*s]", PEER_ID_LEN, PEER_ID_LEN, peer_id);
     272
     273  tor = tr_torrentFindFromHash (handshake->session, hash);
     274  tor_peer_id = tor ? tor->peer_id : tr_getPeerId (handshake->session);
     275  if (!memcmp (peer_id, tor_peer_id, PEER_ID_LEN))
     276    {
     277      dbgmsg (handshake, "streuth!  we've connected to ourselves.");
     278      return HANDSHAKE_PEER_IS_SELF;
     279    }
     280
     281  /**
     282  *** Extensions
     283  **/
     284
     285  tr_peerIoEnableDHT  (handshake->io, HANDSHAKE_HAS_DHT    (reserved));
     286  tr_peerIoEnableLTEP (handshake->io, HANDSHAKE_HAS_LTEP    (reserved));
     287  tr_peerIoEnableFEXT (handshake->io, HANDSHAKE_HAS_FASTEXT (reserved));
     288
     289  return HANDSHAKE_OK;
    312290}
    313291
     
    322300sendYa (tr_handshake * handshake)
    323301{
    324     int               len;
    325     const uint8_t *   public_key;
    326     char              outbuf[ KEY_LEN + PadA_MAXLEN ], *walk=outbuf;
    327 
    328     /* add our public key (Ya) */
    329     public_key = tr_cryptoGetMyPublicKey (handshake->crypto, &len);
    330     assert (len == KEY_LEN);
    331     assert (public_key);
    332     memcpy (walk, public_key, len);
    333     walk += len;
    334 
    335     /* add some bullshit padding */
    336     len = tr_cryptoRandInt (PadA_MAXLEN);
    337     tr_cryptoRandBuf (walk, len);
    338     walk += len;
    339 
    340     /* send it */
    341     setReadState (handshake, AWAITING_YB);
    342     tr_peerIoWriteBytes (handshake->io, outbuf, walk - outbuf, false);
     302  int len;
     303  const uint8_t * public_key;
     304  char outbuf[ KEY_LEN + PadA_MAXLEN ];
     305  char *walk = outbuf;
     306
     307  /* add our public key (Ya) */
     308  public_key = tr_cryptoGetMyPublicKey (handshake->crypto, &len);
     309  assert (len == KEY_LEN);
     310  assert (public_key);
     311  memcpy (walk, public_key, len);
     312  walk += len;
     313
     314  /* add some bullshit padding */
     315  len = tr_cryptoRandInt (PadA_MAXLEN);
     316  tr_cryptoRandBuf (walk, len);
     317  walk += len;
     318
     319  /* send it */
     320  setReadState (handshake, AWAITING_YB);
     321  tr_peerIoWriteBytes (handshake->io, outbuf, walk - outbuf, false);
    343322}
    344323
     
    346325getCryptoProvide (const tr_handshake * handshake)
    347326{
    348     uint32_t provide = 0;
    349 
    350     switch (handshake->encryptionMode)
    351     {
    352         case TR_ENCRYPTION_REQUIRED:
    353         case TR_ENCRYPTION_PREFERRED:
    354             provide |= CRYPTO_PROVIDE_CRYPTO;
    355             break;
    356 
    357         case TR_CLEAR_PREFERRED:
    358             provide |= CRYPTO_PROVIDE_CRYPTO | CRYPTO_PROVIDE_PLAINTEXT;
    359             break;
    360     }
    361 
    362     return provide;
     327  uint32_t provide = 0;
     328
     329  switch (handshake->encryptionMode)
     330    {
     331      case TR_ENCRYPTION_REQUIRED:
     332      case TR_ENCRYPTION_PREFERRED:
     333        provide |= CRYPTO_PROVIDE_CRYPTO;
     334        break;
     335
     336      case TR_CLEAR_PREFERRED:
     337        provide |= CRYPTO_PROVIDE_CRYPTO | CRYPTO_PROVIDE_PLAINTEXT;
     338        break;
     339    }
     340
     341  return provide;
    363342}
    364343
     
    367346                 uint32_t             crypto_provide)
    368347{
    369     uint32_t choices[2];
    370     int      i, nChoices = 0;
    371 
    372     switch (handshake->encryptionMode)
    373     {
    374         case TR_ENCRYPTION_REQUIRED:
    375             choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
    376             break;
    377 
    378         case TR_ENCRYPTION_PREFERRED:
    379             choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
    380             choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
    381             break;
    382 
    383         case TR_CLEAR_PREFERRED:
    384             choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
    385             choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
    386             break;
    387     }
    388 
    389     for (i = 0; i < nChoices; ++i)
    390         if (crypto_provide & choices[i])
    391             return choices[i];
    392 
    393     return 0;
     348  uint32_t choices[2];
     349  int i;
     350  int nChoices = 0;
     351
     352  switch (handshake->encryptionMode)
     353    {
     354      case TR_ENCRYPTION_REQUIRED:
     355        choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
     356        break;
     357
     358      case TR_ENCRYPTION_PREFERRED:
     359        choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
     360        choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
     361        break;
     362
     363      case TR_CLEAR_PREFERRED:
     364        choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
     365        choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
     366        break;
     367    }
     368
     369  for (i=0; i<nChoices; ++i)
     370    if (crypto_provide & choices[i])
     371      return choices[i];
     372
     373  return 0;
    394374}
    395375
     
    397377readYb (tr_handshake * handshake, struct evbuffer * inbuf)
    398378{
    399     int               isEncrypted;
    400     const uint8_t *   secret;
    401     uint8_t           yb[KEY_LEN];
    402     struct evbuffer * outbuf;
    403     size_t            needlen = HANDSHAKE_NAME_LEN;
    404 
    405     if (evbuffer_get_length (inbuf) < needlen)
     379  int isEncrypted;
     380  const uint8_t * secret;
     381  uint8_t yb[KEY_LEN];
     382  struct evbuffer * outbuf;
     383  size_t needlen = HANDSHAKE_NAME_LEN;
     384
     385  if (evbuffer_get_length (inbuf) < needlen)
     386    return READ_LATER;
     387
     388  isEncrypted = memcmp (evbuffer_pullup (inbuf, HANDSHAKE_NAME_LEN), HANDSHAKE_NAME, HANDSHAKE_NAME_LEN);
     389  if (isEncrypted)
     390    {
     391      needlen = KEY_LEN;
     392
     393      if (evbuffer_get_length (inbuf) < needlen)
    406394        return READ_LATER;
    407 
    408     isEncrypted = memcmp (evbuffer_pullup (inbuf, HANDSHAKE_NAME_LEN), HANDSHAKE_NAME, HANDSHAKE_NAME_LEN);
    409     if (isEncrypted)
    410     {
    411         needlen = KEY_LEN;
    412         if (evbuffer_get_length (inbuf) < needlen)
    413             return READ_LATER;
    414     }
    415 
    416     dbgmsg (handshake, "got a %s handshake",
    417          (isEncrypted ? "encrypted" : "plaintext"));
    418 
    419     tr_peerIoSetEncryption (handshake->io, isEncrypted ? PEER_ENCRYPTION_RC4
    420                                                        : PEER_ENCRYPTION_NONE);
    421     if (!isEncrypted)
    422     {
    423         setState (handshake, AWAITING_HANDSHAKE);
    424         return READ_NOW;
    425     }
    426 
    427     handshake->haveReadAnythingFromPeer = true;
    428 
    429     /* compute the secret */
    430     evbuffer_remove (inbuf, yb, KEY_LEN);
    431     secret = tr_cryptoComputeSecret (handshake->crypto, yb);
    432     memcpy (handshake->mySecret, secret, KEY_LEN);
    433 
    434     /* now send these: HASH ('req1', S), HASH ('req2', SKEY) xor HASH ('req3', S),
    435      * ENCRYPT (VC, crypto_provide, len (PadC), PadC, len (IA)), ENCRYPT (IA) */
    436     outbuf = evbuffer_new ();
    437 
    438     /* HASH ('req1', S) */
    439     {
    440         uint8_t req1[SHA_DIGEST_LENGTH];
    441         tr_sha1 (req1, "req1", 4, secret, KEY_LEN, NULL);
    442         evbuffer_add (outbuf, req1, SHA_DIGEST_LENGTH);
    443     }
    444 
    445     /* HASH ('req2', SKEY) xor HASH ('req3', S) */
    446     {
    447         int     i;
    448         uint8_t req2[SHA_DIGEST_LENGTH];
    449         uint8_t req3[SHA_DIGEST_LENGTH];
    450         uint8_t buf[SHA_DIGEST_LENGTH];
    451         tr_sha1 (req2, "req2", 4,
    452                  tr_cryptoGetTorrentHash (handshake->crypto),
    453                  SHA_DIGEST_LENGTH, NULL);
    454         tr_sha1 (req3, "req3", 4, secret, KEY_LEN, NULL);
    455         for (i = 0; i < SHA_DIGEST_LENGTH; ++i)
    456             buf[i] = req2[i] ^ req3[i];
    457         evbuffer_add (outbuf, buf, SHA_DIGEST_LENGTH);
    458     }
    459 
    460     /* ENCRYPT (VC, crypto_provide, len (PadC), PadC
    461      * PadC is reserved for future extensions to the handshake...
    462      * standard practice at this time is for it to be zero-length */
    463     {
    464         uint8_t vc[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
    465 
    466         tr_peerIoWriteBuf (handshake->io, outbuf, false);
    467         tr_cryptoEncryptInit (handshake->crypto);
    468         tr_peerIoSetEncryption (handshake->io, PEER_ENCRYPTION_RC4);
    469 
    470         evbuffer_add      (outbuf, vc, VC_LENGTH);
    471         evbuffer_add_uint32 (outbuf, getCryptoProvide (handshake));
    472         evbuffer_add_uint16 (outbuf, 0);
    473     }
    474 
    475     /* ENCRYPT len (IA)), ENCRYPT (IA) */
    476     {
    477         uint8_t msg[HANDSHAKE_SIZE];
    478         buildHandshakeMessage (handshake, msg);
    479 
    480         evbuffer_add_uint16 (outbuf, sizeof (msg));
    481         evbuffer_add      (outbuf, msg, sizeof (msg));
    482 
    483         handshake->haveSentBitTorrentHandshake = 1;
    484     }
    485 
    486     /* send it */
    487     tr_cryptoDecryptInit (handshake->crypto);
    488     setReadState (handshake, AWAITING_VC);
     395    }
     396
     397  dbgmsg (handshake, "got an %s handshake", (isEncrypted ? "encrypted" : "plain"));
     398
     399  tr_peerIoSetEncryption (handshake->io, isEncrypted ? PEER_ENCRYPTION_RC4
     400                                                     : PEER_ENCRYPTION_NONE);
     401  if (!isEncrypted)
     402    {
     403      setState (handshake, AWAITING_HANDSHAKE);
     404      return READ_NOW;
     405    }
     406
     407  handshake->haveReadAnythingFromPeer = true;
     408
     409  /* compute the secret */
     410  evbuffer_remove (inbuf, yb, KEY_LEN);
     411  secret = tr_cryptoComputeSecret (handshake->crypto, yb);
     412  memcpy (handshake->mySecret, secret, KEY_LEN);
     413
     414  /* now send these: HASH ('req1', S), HASH ('req2', SKEY) xor HASH ('req3', S),
     415   * ENCRYPT (VC, crypto_provide, len (PadC), PadC, len (IA)), ENCRYPT (IA) */
     416  outbuf = evbuffer_new ();
     417
     418  /* HASH ('req1', S) */
     419  {
     420    uint8_t req1[SHA_DIGEST_LENGTH];
     421    tr_sha1 (req1, "req1", 4, secret, KEY_LEN, NULL);
     422    evbuffer_add (outbuf, req1, SHA_DIGEST_LENGTH);
     423  }
     424
     425  /* HASH ('req2', SKEY) xor HASH ('req3', S) */
     426  {
     427    int i;
     428    uint8_t req2[SHA_DIGEST_LENGTH];
     429    uint8_t req3[SHA_DIGEST_LENGTH];
     430    uint8_t buf[SHA_DIGEST_LENGTH];
     431
     432    tr_sha1 (req2, "req2", 4, tr_cryptoGetTorrentHash (handshake->crypto), SHA_DIGEST_LENGTH, NULL);
     433    tr_sha1 (req3, "req3", 4, secret, KEY_LEN, NULL);
     434
     435    for (i=0; i<SHA_DIGEST_LENGTH; ++i)
     436      buf[i] = req2[i] ^ req3[i];
     437
     438    evbuffer_add (outbuf, buf, SHA_DIGEST_LENGTH);
     439  }
     440
     441  /* ENCRYPT (VC, crypto_provide, len (PadC), PadC
     442   * PadC is reserved for future extensions to the handshake...
     443   * standard practice at this time is for it to be zero-length */
     444  {
     445    uint8_t vc[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
     446
    489447    tr_peerIoWriteBuf (handshake->io, outbuf, false);
    490 
    491     /* cleanup */
    492     evbuffer_free (outbuf);
     448    tr_cryptoEncryptInit (handshake->crypto);
     449    tr_peerIoSetEncryption (handshake->io, PEER_ENCRYPTION_RC4);
     450
     451    evbuffer_add        (outbuf, vc, VC_LENGTH);
     452    evbuffer_add_uint32 (outbuf, getCryptoProvide (handshake));
     453    evbuffer_add_uint16 (outbuf, 0);
     454  }
     455
     456  /* ENCRYPT len (IA)), ENCRYPT (IA) */
     457  {
     458    uint8_t msg[HANDSHAKE_SIZE];
     459    buildHandshakeMessage (handshake, msg);
     460
     461    evbuffer_add_uint16 (outbuf, sizeof (msg));
     462    evbuffer_add        (outbuf, msg, sizeof (msg));
     463
     464    handshake->haveSentBitTorrentHandshake = 1;
     465  }
     466
     467  /* send it */
     468  tr_cryptoDecryptInit (handshake->crypto);
     469  setReadState (handshake, AWAITING_VC);
     470  tr_peerIoWriteBuf (handshake->io, outbuf, false);
     471
     472  /* cleanup */
     473  evbuffer_free (outbuf);
     474  return READ_LATER;
     475}
     476
     477static int
     478readVC (tr_handshake    * handshake,
     479        struct evbuffer * inbuf)
     480{
     481  uint8_t tmp[VC_LENGTH];
     482  const int key_len = VC_LENGTH;
     483  const uint8_t key[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
     484
     485  /* note: this works w/o having to `unwind' the buffer if
     486   * we read too much, but it is pretty brute-force.
     487   * it would be nice to make this cleaner. */
     488  for (;;)
     489    {
     490      if (evbuffer_get_length (inbuf) < VC_LENGTH)
     491        {
     492          dbgmsg (handshake, "not enough bytes... returning read_more");
     493          return READ_LATER;
     494        }
     495
     496      memcpy (tmp, evbuffer_pullup (inbuf, key_len), key_len);
     497      tr_cryptoDecryptInit (handshake->crypto);
     498      tr_cryptoDecrypt (handshake->crypto, key_len, tmp, tmp);
     499      if (!memcmp (tmp, key, key_len))
     500        break;
     501
     502      evbuffer_drain (inbuf, 1);
     503    }
     504
     505  dbgmsg (handshake, "got it!");
     506  evbuffer_drain (inbuf, key_len);
     507  setState (handshake, AWAITING_CRYPTO_SELECT);
     508  return READ_NOW;
     509}
     510
     511static int
     512readCryptoSelect (tr_handshake    * handshake,
     513                  struct evbuffer * inbuf)
     514{
     515  uint16_t pad_d_len;
     516  uint32_t crypto_select;
     517  static const size_t needlen = sizeof (uint32_t) + sizeof (uint16_t);
     518
     519  if (evbuffer_get_length (inbuf) < needlen)
    493520    return READ_LATER;
    494 }
    495 
    496 static int
    497 readVC (tr_handshake *    handshake,
    498         struct evbuffer * inbuf)
    499 {
    500     const uint8_t key[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
    501     const int     key_len = VC_LENGTH;
    502     uint8_t       tmp[VC_LENGTH];
    503 
    504     /* note: this works w/o having to `unwind' the buffer if
    505      * we read too much, but it is pretty brute-force.
    506      * it would be nice to make this cleaner. */
    507     for (; ;)
    508     {
    509         if (evbuffer_get_length (inbuf) < VC_LENGTH)
    510         {
    511             dbgmsg (handshake, "not enough bytes... returning read_more");
    512             return READ_LATER;
    513         }
    514 
    515         memcpy (tmp, evbuffer_pullup (inbuf, key_len), key_len);
    516         tr_cryptoDecryptInit (handshake->crypto);
    517         tr_cryptoDecrypt (handshake->crypto, key_len, tmp, tmp);
    518         if (!memcmp (tmp, key, key_len))
    519             break;
    520 
    521         evbuffer_drain (inbuf, 1);
    522     }
    523 
    524     dbgmsg (handshake, "got it!");
    525     evbuffer_drain (inbuf, key_len);
    526     setState (handshake, AWAITING_CRYPTO_SELECT);
    527     return READ_NOW;
    528 }
    529 
    530 static int
    531 readCryptoSelect (tr_handshake *    handshake,
    532                   struct evbuffer * inbuf)
    533 {
    534     uint32_t     crypto_select;
    535     uint16_t     pad_d_len;
    536     const size_t needlen = sizeof (uint32_t) + sizeof (uint16_t);
    537 
    538     if (evbuffer_get_length (inbuf) < needlen)
    539         return READ_LATER;
    540 
    541     tr_peerIoReadUint32 (handshake->io, inbuf, &crypto_select);
    542     handshake->crypto_select = crypto_select;
    543     dbgmsg (handshake, "crypto select is %d", (int)crypto_select);
    544     if (! (crypto_select & getCryptoProvide (handshake)))
    545     {
    546         dbgmsg (handshake,
    547                 "peer selected an encryption option we didn't provide");
    548         return tr_handshakeDone (handshake, false);
    549     }
    550 
    551     tr_peerIoReadUint16 (handshake->io, inbuf, &pad_d_len);
    552     dbgmsg (handshake, "pad_d_len is %d", (int)pad_d_len);
    553 
    554     if (pad_d_len > 512)
    555     {
    556         dbgmsg (handshake, "encryption handshake: pad_d_len is too long");
    557         return tr_handshakeDone (handshake, false);
    558     }
    559 
    560     handshake->pad_d_len = pad_d_len;
    561 
    562     setState (handshake, AWAITING_PAD_D);
    563     return READ_NOW;
    564 }
    565 
    566 static int
    567 readPadD (tr_handshake *    handshake,
     521
     522  tr_peerIoReadUint32 (handshake->io, inbuf, &crypto_select);
     523  handshake->crypto_select = crypto_select;
     524  dbgmsg (handshake, "crypto select is %d", (int)crypto_select);
     525  if (!(crypto_select & getCryptoProvide (handshake)))
     526    {
     527      dbgmsg (handshake, "peer selected an encryption option we didn't offer");
     528      return tr_handshakeDone (handshake, false);
     529    }
     530
     531  tr_peerIoReadUint16 (handshake->io, inbuf, &pad_d_len);
     532  dbgmsg (handshake, "pad_d_len is %d", (int)pad_d_len);
     533
     534  if (pad_d_len > 512)
     535    {
     536      dbgmsg (handshake, "encryption handshake: pad_d_len is too long");
     537      return tr_handshakeDone (handshake, false);
     538    }
     539
     540  handshake->pad_d_len = pad_d_len;
     541
     542  setState (handshake, AWAITING_PAD_D);
     543  return READ_NOW;
     544}
     545
     546static int
     547readPadD (tr_handshake    * handshake,
    568548          struct evbuffer * inbuf)
    569549{
    570     const size_t needlen = handshake->pad_d_len;
    571 
    572     dbgmsg (handshake, "pad d: need %zu, got %zu",
    573             needlen, evbuffer_get_length (inbuf));
    574     if (evbuffer_get_length (inbuf) < needlen)
    575         return READ_LATER;
    576 
    577     tr_peerIoDrain (handshake->io, inbuf, needlen);
    578 
    579     tr_peerIoSetEncryption (handshake->io, handshake->crypto_select);
    580 
    581     setState (handshake, AWAITING_HANDSHAKE);
    582     return READ_NOW;
     550  const size_t needlen = handshake->pad_d_len;
     551
     552  dbgmsg (handshake, "pad d: need %zu, got %zu",
     553          needlen, evbuffer_get_length (inbuf));
     554  if (evbuffer_get_length (inbuf) < needlen)
     555    return READ_LATER;
     556
     557  tr_peerIoDrain (handshake->io, inbuf, needlen);
     558
     559  tr_peerIoSetEncryption (handshake->io, handshake->crypto_select);
     560
     561  setState (handshake, AWAITING_HANDSHAKE);
     562  return READ_NOW;
    583563}
    584564
     
    590570
    591571static int
    592 readHandshake (tr_handshake *    handshake,
     572readHandshake (tr_handshake    * handshake,
    593573               struct evbuffer * inbuf)
    594574{
    595     uint8_t  pstrlen;
    596     uint8_t  pstr[20];
    597     uint8_t  reserved[HANDSHAKE_FLAGS_LEN];
    598     uint8_t  hash[SHA_DIGEST_LENGTH];
    599 
    600     dbgmsg (handshake, "payload: need %d, got %zu",
    601             INCOMING_HANDSHAKE_LEN, evbuffer_get_length (inbuf));
    602 
    603     if (evbuffer_get_length (inbuf) < INCOMING_HANDSHAKE_LEN)
    604         return READ_LATER;
    605 
    606     handshake->haveReadAnythingFromPeer = true;
    607 
    608     pstrlen = evbuffer_pullup (inbuf, 1)[0]; /* peek, don't read. We may be
    609                                                  handing inbuf to AWAITING_YA */
    610 
    611     if (pstrlen == 19) /* unencrypted */
    612     {
    613         tr_peerIoSetEncryption (handshake->io, PEER_ENCRYPTION_NONE);
    614 
    615         if (handshake->encryptionMode == TR_ENCRYPTION_REQUIRED)
     575  uint8_t pstrlen;
     576  uint8_t pstr[20];
     577  uint8_t reserved[HANDSHAKE_FLAGS_LEN];
     578  uint8_t hash[SHA_DIGEST_LENGTH];
     579
     580  dbgmsg (handshake, "payload: need %d, got %zu",
     581          INCOMING_HANDSHAKE_LEN, evbuffer_get_length (inbuf));
     582
     583  if (evbuffer_get_length (inbuf) < INCOMING_HANDSHAKE_LEN)
     584    return READ_LATER;
     585
     586  handshake->haveReadAnythingFromPeer = true;
     587
     588  pstrlen = evbuffer_pullup (inbuf, 1)[0]; /* peek, don't read. We may be
     589                                              handing inbuf to AWAITING_YA */
     590
     591  if (pstrlen == 19) /* unencrypted */
     592    {
     593      tr_peerIoSetEncryption (handshake->io, PEER_ENCRYPTION_NONE);
     594
     595      if (handshake->encryptionMode == TR_ENCRYPTION_REQUIRED)
    616596        {
    617             dbgmsg (handshake,
    618                     "peer is unencrypted, and we're disallowing that");
    619             return tr_handshakeDone (handshake, false);
     597          dbgmsg (handshake, "peer is unencrypted, and we're disallowing that");
     598          return tr_handshakeDone (handshake, false);
    620599        }
    621600    }
    622     else /* encrypted or corrupt */
    623     {
    624         tr_peerIoSetEncryption (handshake->io, PEER_ENCRYPTION_RC4);
    625 
    626         if (tr_peerIoIsIncoming (handshake->io))
     601  else /* encrypted or corrupt */
     602    {
     603      tr_peerIoSetEncryption (handshake->io, PEER_ENCRYPTION_RC4);
     604
     605      if (tr_peerIoIsIncoming (handshake->io))
    627606        {
    628             dbgmsg (handshake,
    629                     "I think peer is sending us an encrypted handshake...");
    630             setState (handshake, AWAITING_YA);
    631             return READ_NOW;
     607          dbgmsg (handshake, "I think peer is sending us an encrypted handshake...");
     608          setState (handshake, AWAITING_YA);
     609          return READ_NOW;
    632610        }
    633         tr_cryptoDecrypt (handshake->crypto, 1, &pstrlen, &pstrlen);
    634 
    635         if (pstrlen != 19)
     611
     612      tr_cryptoDecrypt (handshake->crypto, 1, &pstrlen, &pstrlen);
     613
     614      if (pstrlen != 19)
    636615        {
    637             dbgmsg (handshake,
    638                     "I think peer has sent us a corrupt handshake...");
    639             return tr_handshakeDone (handshake, false);
     616          dbgmsg (handshake, "I think peer has sent us a corrupt handshake...");
     617          return tr_handshakeDone (handshake, false);
    640618        }
    641619    }
    642620
    643     evbuffer_drain (inbuf, 1);
    644 
    645     /* pstr (BitTorrent) */
    646     assert (pstrlen == 19);
    647     tr_peerIoReadBytes (handshake->io, inbuf, pstr, pstrlen);
    648     pstr[pstrlen] = '\0';
    649     if (memcmp (pstr, "BitTorrent protocol", 19))
    650         return tr_handshakeDone (handshake, false);
    651 
    652     /* reserved bytes */
    653     tr_peerIoReadBytes (handshake->io, inbuf, reserved, sizeof (reserved));
    654 
    655     /**
    656     *** Extensions
    657     **/
    658 
    659     tr_peerIoEnableLTEP (handshake->io, HANDSHAKE_HAS_LTEP (reserved));
    660 
    661     tr_peerIoEnableFEXT (handshake->io, HANDSHAKE_HAS_FASTEXT (reserved));
    662 
    663     tr_peerIoEnableDHT (handshake->io, HANDSHAKE_HAS_DHT (reserved));
    664 
    665     /* torrent hash */
    666     tr_peerIoReadBytes (handshake->io, inbuf, hash, sizeof (hash));
    667     if (tr_peerIoIsIncoming (handshake->io))
    668     {
    669         if (!tr_torrentExists (handshake->session, hash))
     621  evbuffer_drain (inbuf, 1);
     622
     623  /* pstr (BitTorrent) */
     624  assert (pstrlen == 19);
     625  tr_peerIoReadBytes (handshake->io, inbuf, pstr, pstrlen);
     626  pstr[pstrlen] = '\0';
     627  if (memcmp (pstr, "BitTorrent protocol", 19))
     628    return tr_handshakeDone (handshake, false);
     629
     630  /* reserved bytes */
     631  tr_peerIoReadBytes (handshake->io, inbuf, reserved, sizeof (reserved));
     632
     633  /**
     634  *** Extensions
     635  **/
     636
     637  tr_peerIoEnableDHT  (handshake->io, HANDSHAKE_HAS_DHT     (reserved));
     638  tr_peerIoEnableLTEP (handshake->io, HANDSHAKE_HAS_LTEP    (reserved));
     639  tr_peerIoEnableFEXT (handshake->io, HANDSHAKE_HAS_FASTEXT (reserved));
     640
     641  /* torrent hash */
     642  tr_peerIoReadBytes (handshake->io, inbuf, hash, sizeof (hash));
     643  if (tr_peerIoIsIncoming (handshake->io))
     644    {
     645      if (!tr_torrentExists (handshake->session, hash))
    670646        {
    671             dbgmsg (handshake, "peer is trying to connect to us for a torrent we don't have.");
    672             return tr_handshakeDone (handshake, false);
     647          dbgmsg (handshake, "peer is trying to connect to us for a torrent we don't have.");
     648          return tr_handshakeDone (handshake, false);
    673649        }
    674         else
     650      else
    675651        {
    676             assert (!tr_peerIoHasTorrentHash (handshake->io));
    677             tr_peerIoSetTorrentHash (handshake->io, hash);
     652          assert (!tr_peerIoHasTorrentHash (handshake->io));
     653          tr_peerIoSetTorrentHash (handshake->io, hash);
    678654        }
    679655    }
    680     else /* outgoing */
    681     {
    682         assert (tr_peerIoHasTorrentHash (handshake->io));
    683         if (memcmp (hash, tr_peerIoGetTorrentHash (handshake->io),
    684                     SHA_DIGEST_LENGTH))
     656  else /* outgoing */
     657    {
     658      assert (tr_peerIoHasTorrentHash (handshake->io));
     659
     660      if (memcmp (hash, tr_peerIoGetTorrentHash (handshake->io), SHA_DIGEST_LENGTH))
    685661        {
    686             dbgmsg (handshake, "peer returned the wrong hash. wtf?");
    687             return tr_handshakeDone (handshake, false);
     662          dbgmsg (handshake, "peer returned the wrong hash. wtf?");
     663          return tr_handshakeDone (handshake, false);
    688664        }
    689665    }
    690666
    691     /**
    692     ***  If it's an incoming message, we need to send a response handshake
    693     **/
    694 
    695     if (!handshake->haveSentBitTorrentHandshake)
    696     {
    697         uint8_t msg[HANDSHAKE_SIZE];
    698         buildHandshakeMessage (handshake, msg);
    699         tr_peerIoWriteBytes (handshake->io, msg, sizeof (msg), false);
    700         handshake->haveSentBitTorrentHandshake = 1;
    701     }
    702 
    703     setReadState (handshake, AWAITING_PEER_ID);
    704     return READ_NOW;
     667  /**
     668  ***  If it's an incoming message, we need to send a response handshake
     669  **/
     670
     671  if (!handshake->haveSentBitTorrentHandshake)
     672    {
     673      uint8_t msg[HANDSHAKE_SIZE];
     674      buildHandshakeMessage (handshake, msg);
     675      tr_peerIoWriteBytes (handshake->io, msg, sizeof (msg), false);
     676      handshake->haveSentBitTorrentHandshake = 1;
     677    }
     678
     679  setReadState (handshake, AWAITING_PEER_ID);
     680  return READ_NOW;
    705681}
    706682
     
    709685            struct evbuffer * inbuf)
    710686{
    711     bool peerIsGood;
    712     char client[128];
    713     tr_torrent * tor;
    714     const uint8_t * tor_peer_id;
    715     uint8_t peer_id[PEER_ID_LEN];
    716 
    717     if (evbuffer_get_length (inbuf) < PEER_ID_LEN)
    718         return READ_LATER;
    719 
    720     /* peer id */
    721     tr_peerIoReadBytes (handshake->io, inbuf, peer_id, PEER_ID_LEN);
    722     tr_peerIoSetPeersId (handshake->io, peer_id);
    723     handshake->havePeerID = true;
    724     tr_clientForId (client, sizeof (client), peer_id);
    725     dbgmsg (handshake, "peer-id is [%s] ... isIncoming is %d", client,
    726             tr_peerIoIsIncoming (handshake->io));
    727 
    728     /* if we've somehow connected to ourselves, don't keep the connection */
    729     tor = tr_torrentFindFromHash (handshake->session, tr_peerIoGetTorrentHash (handshake->io));
    730     tor_peer_id = tor ? tor->peer_id : tr_getPeerId (handshake->session);
    731     peerIsGood = memcmp (peer_id, tor_peer_id, PEER_ID_LEN) != 0;
    732     dbgmsg (handshake, "isPeerGood == %d", (int)peerIsGood);
    733     return tr_handshakeDone (handshake, peerIsGood);
    734 }
    735 
    736 static int
    737 readYa (tr_handshake *    handshake,
     687  bool peerIsGood;
     688  char client[128];
     689  tr_torrent * tor;
     690  const uint8_t * tor_peer_id;
     691  uint8_t peer_id[PEER_ID_LEN];
     692
     693  if (evbuffer_get_length (inbuf) < PEER_ID_LEN)
     694    return READ_LATER;
     695
     696  /* peer id */
     697  tr_peerIoReadBytes (handshake->io, inbuf, peer_id, PEER_ID_LEN);
     698  tr_peerIoSetPeersId (handshake->io, peer_id);
     699  handshake->havePeerID = true;
     700  tr_clientForId (client, sizeof (client), peer_id);
     701  dbgmsg (handshake, "peer-id is [%s] ... isIncoming is %d", client,
     702          tr_peerIoIsIncoming (handshake->io));
     703
     704  /* if we've somehow connected to ourselves, don't keep the connection */
     705  tor = tr_torrentFindFromHash (handshake->session, tr_peerIoGetTorrentHash (handshake->io));
     706  tor_peer_id = tor ? tor->peer_id : tr_getPeerId (handshake->session);
     707  peerIsGood = memcmp (peer_id, tor_peer_id, PEER_ID_LEN) != 0;
     708  dbgmsg (handshake, "isPeerGood == %d", (int)peerIsGood);
     709  return tr_handshakeDone (handshake, peerIsGood);
     710}
     711
     712static int
     713readYa (tr_handshake    * handshake,
    738714        struct evbuffer * inbuf)
    739715{
    740     uint8_t        ya[KEY_LEN];
    741     uint8_t *      walk, outbuf[KEY_LEN + PadB_MAXLEN];
    742     const uint8_t *myKey, *secret;
    743     int            len;
    744 
    745     dbgmsg (handshake, "in readYa... need %d, have %zu",
    746             KEY_LEN, evbuffer_get_length (inbuf));
    747     if (evbuffer_get_length (inbuf) < KEY_LEN)
    748         return READ_LATER;
    749 
    750     /* read the incoming peer's public key */
    751     evbuffer_remove (inbuf, ya, KEY_LEN);
    752     secret = tr_cryptoComputeSecret (handshake->crypto, ya);
    753     memcpy (handshake->mySecret, secret, KEY_LEN);
    754     tr_sha1 (handshake->myReq1, "req1", 4, secret, KEY_LEN, NULL);
    755 
    756     dbgmsg (handshake, "sending B->A: Diffie Hellman Yb, PadB");
    757     /* send our public key to the peer */
    758     walk = outbuf;
    759     myKey = tr_cryptoGetMyPublicKey (handshake->crypto, &len);
    760     memcpy (walk, myKey, len);
    761     walk += len;
    762     len = tr_cryptoRandInt (PadB_MAXLEN);
    763     tr_cryptoRandBuf (walk, len);
    764     walk += len;
    765 
    766     setReadState (handshake, AWAITING_PAD_A);
    767     tr_peerIoWriteBytes (handshake->io, outbuf, walk - outbuf, false);
    768     return READ_NOW;
     716  uint8_t ya[KEY_LEN];
     717  uint8_t * walk, outbuf[KEY_LEN + PadB_MAXLEN];
     718  const uint8_t * myKey;
     719  const uint8_t * secret;
     720  int len;
     721
     722  dbgmsg (handshake, "in readYa... need %d, have %zu",
     723          KEY_LEN, evbuffer_get_length (inbuf));
     724  if (evbuffer_get_length (inbuf) < KEY_LEN)
     725    return READ_LATER;
     726
     727  /* read the incoming peer's public key */
     728  evbuffer_remove (inbuf, ya, KEY_LEN);
     729  secret = tr_cryptoComputeSecret (handshake->crypto, ya);
     730  memcpy (handshake->mySecret, secret, KEY_LEN);
     731  tr_sha1 (handshake->myReq1, "req1", 4, secret, KEY_LEN, NULL);
     732
     733  /* send our public key to the peer */
     734  dbgmsg (handshake, "sending B->A: Diffie Hellman Yb, PadB");
     735  walk = outbuf;
     736  myKey = tr_cryptoGetMyPublicKey (handshake->crypto, &len);
     737  memcpy (walk, myKey, len);
     738  walk += len;
     739  len = tr_cryptoRandInt (PadB_MAXLEN);
     740  tr_cryptoRandBuf (walk, len);
     741  walk += len;
     742
     743  setReadState (handshake, AWAITING_PAD_A);
     744  tr_peerIoWriteBytes (handshake->io, outbuf, walk - outbuf, false);
     745  return READ_NOW;
    769746}
    770747
     
    772749readPadA (tr_handshake * handshake, struct evbuffer * inbuf)
    773750{
    774     /* resynchronizing on HASH ('req1',S) */
    775     struct evbuffer_ptr ptr = evbuffer_search (inbuf, (const char*)handshake->myReq1, SHA_DIGEST_LENGTH, NULL);
    776 
    777     if (ptr.pos != -1) /* match */
    778     {
    779         evbuffer_drain (inbuf, ptr.pos);
    780         dbgmsg (handshake, "found it... looking setting to awaiting_crypto_provide");
    781         setState (handshake, AWAITING_CRYPTO_PROVIDE);
    782         return READ_NOW;
    783     }
    784     else
    785     {
    786         const size_t len = evbuffer_get_length (inbuf);
    787         if (len > SHA_DIGEST_LENGTH)
    788             evbuffer_drain (inbuf, len - SHA_DIGEST_LENGTH);
    789         return READ_LATER;
    790     }
    791 }
    792 
    793 static int
    794 readCryptoProvide (tr_handshake *    handshake,
     751  /* resynchronizing on HASH ('req1',S) */
     752  struct evbuffer_ptr ptr = evbuffer_search (inbuf, (const char*)handshake->myReq1, SHA_DIGEST_LENGTH, NULL);
     753
     754  if (ptr.pos != -1) /* match */
     755    {
     756      evbuffer_drain (inbuf, ptr.pos);
     757      dbgmsg (handshake, "found it... looking setting to awaiting_crypto_provide");
     758      setState (handshake, AWAITING_CRYPTO_PROVIDE);
     759      return READ_NOW;
     760    }
     761  else
     762    {
     763      const size_t len = evbuffer_get_length (inbuf);
     764      if (len > SHA_DIGEST_LENGTH)
     765        evbuffer_drain (inbuf, len - SHA_DIGEST_LENGTH);
     766      return READ_LATER;
     767    }
     768}
     769
     770static int
     771readCryptoProvide (tr_handshake    * handshake,
    795772                   struct evbuffer * inbuf)
    796773{
    797     /* HASH ('req2', SKEY) xor HASH ('req3', S), ENCRYPT (VC, crypto_provide,
    798       len (PadC)) */
    799 
    800     int          i;
    801     uint8_t      vc_in[VC_LENGTH];
    802     uint8_t      req2[SHA_DIGEST_LENGTH];
    803     uint8_t      req3[SHA_DIGEST_LENGTH];
    804     uint8_t      obfuscatedTorrentHash[SHA_DIGEST_LENGTH];
    805     uint16_t     padc_len = 0;
    806     uint32_t     crypto_provide = 0;
    807     const size_t needlen = SHA_DIGEST_LENGTH /* HASH ('req1',s) */
    808                            + SHA_DIGEST_LENGTH /* HASH ('req2', SKEY) xor
    809                                                  HASH ('req3', S) */
    810                            + VC_LENGTH
    811                            + sizeof (crypto_provide)
    812                            + sizeof (padc_len);
    813     tr_torrent * tor = NULL;
    814 
    815     if (evbuffer_get_length (inbuf) < needlen)
    816         return READ_LATER;
    817 
    818     /* TODO: confirm they sent HASH ('req1',S) here? */
    819     evbuffer_drain (inbuf, SHA_DIGEST_LENGTH);
    820 
    821     /* This next piece is HASH ('req2', SKEY) xor HASH ('req3', S) ...
    822      * we can get the first half of that (the obufscatedTorrentHash)
    823      * by building the latter and xor'ing it with what the peer sent us */
    824     dbgmsg (handshake, "reading obfuscated torrent hash...");
    825     evbuffer_remove (inbuf, req2, SHA_DIGEST_LENGTH);
    826     tr_sha1 (req3, "req3", 4, handshake->mySecret, KEY_LEN, NULL);
    827     for (i = 0; i < SHA_DIGEST_LENGTH; ++i)
    828         obfuscatedTorrentHash[i] = req2[i] ^ req3[i];
    829     if ((tor = tr_torrentFindFromObfuscatedHash (handshake->session, obfuscatedTorrentHash)))
    830     {
    831         const bool clientIsSeed = tr_torrentIsSeed (tor);
    832         const bool peerIsSeed = tr_peerMgrPeerIsSeed (tor, tr_peerIoGetAddress (handshake->io, NULL));
    833         dbgmsg (handshake, "got INCOMING connection's encrypted handshake for torrent [%s]",
    834                 tr_torrentName (tor));
    835         tr_peerIoSetTorrentHash (handshake->io, tor->info.hash);
    836 
    837         if (clientIsSeed && peerIsSeed)
     774  /* HASH ('req2', SKEY) xor HASH ('req3', S), ENCRYPT (VC, crypto_provide, len (PadC)) */
     775
     776  int i;
     777  uint8_t vc_in[VC_LENGTH];
     778  uint8_t req2[SHA_DIGEST_LENGTH];
     779  uint8_t req3[SHA_DIGEST_LENGTH];
     780  uint8_t obfuscatedTorrentHash[SHA_DIGEST_LENGTH];
     781  uint16_t padc_len = 0;
     782  uint32_t crypto_provide = 0;
     783  tr_torrent * tor;
     784  const size_t needlen = SHA_DIGEST_LENGTH /* HASH ('req1',s) */
     785                       + SHA_DIGEST_LENGTH /* HASH ('req2', SKEY) xor HASH ('req3', S) */
     786                       + VC_LENGTH
     787                       + sizeof (crypto_provide)
     788                       + sizeof (padc_len);
     789
     790  if (evbuffer_get_length (inbuf) < needlen)
     791    return READ_LATER;
     792
     793  /* TODO: confirm they sent HASH ('req1',S) here? */
     794  evbuffer_drain (inbuf, SHA_DIGEST_LENGTH);
     795
     796  /* This next piece is HASH ('req2', SKEY) xor HASH ('req3', S) ...
     797   * we can get the first half of that (the obufscatedTorrentHash)
     798   * by building the latter and xor'ing it with what the peer sent us */
     799  dbgmsg (handshake, "reading obfuscated torrent hash...");
     800  evbuffer_remove (inbuf, req2, SHA_DIGEST_LENGTH);
     801  tr_sha1 (req3, "req3", 4, handshake->mySecret, KEY_LEN, NULL);
     802  for (i=0; i<SHA_DIGEST_LENGTH; ++i)
     803    obfuscatedTorrentHash[i] = req2[i] ^ req3[i];
     804  if ((tor = tr_torrentFindFromObfuscatedHash (handshake->session, obfuscatedTorrentHash)))
     805    {
     806      const bool clientIsSeed = tr_torrentIsSeed (tor);
     807      const bool peerIsSeed = tr_peerMgrPeerIsSeed (tor, tr_peerIoGetAddress (handshake->io, NULL));
     808      dbgmsg (handshake, "got INCOMING connection's encrypted handshake for torrent [%s]", tr_torrentName (tor));
     809      tr_peerIoSetTorrentHash (handshake->io, tor->info.hash);
     810
     811      if (clientIsSeed && peerIsSeed)
    838812        {
    839             dbgmsg (handshake, "another seed tried to reconnect to us!");
    840             return tr_handshakeDone (handshake, false);
     813          dbgmsg (handshake, "another seed tried to reconnect to us!");
     814          return tr_handshakeDone (handshake, false);
    841815        }
    842816    }
    843     else
    844     {
    845         dbgmsg (handshake, "can't find that torrent...");
    846         return tr_handshakeDone (handshake, false);
    847     }
    848 
    849     /* next part: ENCRYPT (VC, crypto_provide, len (PadC), */
    850 
    851     tr_cryptoDecryptInit (handshake->crypto);
    852 
    853     tr_peerIoReadBytes (handshake->io, inbuf, vc_in, VC_LENGTH);
    854 
    855     tr_peerIoReadUint32 (handshake->io, inbuf, &crypto_provide);
    856     handshake->crypto_provide = crypto_provide;
    857     dbgmsg (handshake, "crypto_provide is %d", (int)crypto_provide);
    858 
    859     tr_peerIoReadUint16 (handshake->io, inbuf, &padc_len);
    860     dbgmsg (handshake, "padc is %d", (int)padc_len);
    861     handshake->pad_c_len = padc_len;
    862     setState (handshake, AWAITING_PAD_C);
    863     return READ_NOW;
    864 }
    865 
    866 static int
    867 readPadC (tr_handshake *    handshake,
     817  else
     818    {
     819      dbgmsg (handshake, "can't find that torrent...");
     820      return tr_handshakeDone (handshake, false);
     821    }
     822
     823  /* next part: ENCRYPT (VC, crypto_provide, len (PadC), */
     824
     825  tr_cryptoDecryptInit (handshake->crypto);
     826
     827  tr_peerIoReadBytes (handshake->io, inbuf, vc_in, VC_LENGTH);
     828
     829  tr_peerIoReadUint32 (handshake->io, inbuf, &crypto_provide);
     830  handshake->crypto_provide = crypto_provide;
     831  dbgmsg (handshake, "crypto_provide is %d", (int)crypto_provide);
     832
     833  tr_peerIoReadUint16 (handshake->io, inbuf, &padc_len);
     834  dbgmsg (handshake, "padc is %d", (int)padc_len);
     835  handshake->pad_c_len = padc_len;
     836  setState (handshake, AWAITING_PAD_C);
     837  return READ_NOW;
     838}
     839
     840static int
     841readPadC (tr_handshake    * handshake,
    868842          struct evbuffer * inbuf)
    869843{
    870     char      * padc;
    871     uint16_t    ia_len;
    872     const size_t needlen = handshake->pad_c_len + sizeof (uint16_t);
    873 
    874     if (evbuffer_get_length (inbuf) < needlen)
    875         return READ_LATER;
    876 
    877     /* read the throwaway padc */
    878     padc = tr_new (char, handshake->pad_c_len);
    879     tr_peerIoReadBytes (handshake->io, inbuf, padc, handshake->pad_c_len);
    880     tr_free (padc);
    881 
    882     /* read ia_len */
    883     tr_peerIoReadUint16 (handshake->io, inbuf, &ia_len);
    884     dbgmsg (handshake, "ia_len is %d", (int)ia_len);
    885     handshake->ia_len = ia_len;
    886     setState (handshake, AWAITING_IA);
    887     return READ_NOW;
    888 }
    889 
    890 static int
    891 readIA (tr_handshake *    handshake,
     844  char * padc;
     845  uint16_t ia_len;
     846  const size_t needlen = handshake->pad_c_len + sizeof (uint16_t);
     847
     848  if (evbuffer_get_length (inbuf) < needlen)
     849    return READ_LATER;
     850
     851  /* read the throwaway padc */
     852  padc = tr_new (char, handshake->pad_c_len);
     853  tr_peerIoReadBytes (handshake->io, inbuf, padc, handshake->pad_c_len);
     854  tr_free (padc);
     855
     856  /* read ia_len */
     857  tr_peerIoReadUint16 (handshake->io, inbuf, &ia_len);
     858  dbgmsg (handshake, "ia_len is %d", (int)ia_len);
     859  handshake->ia_len = ia_len;
     860  setState (handshake, AWAITING_IA);
     861  return READ_NOW;
     862}
     863
     864static int
     865readIA (tr_handshake    * handshake,
    892866        struct evbuffer * inbuf)
    893867{
    894     const size_t      needlen = handshake->ia_len;
    895     struct evbuffer * outbuf;
    896     uint32_t          crypto_select;
    897 
    898     dbgmsg (handshake, "reading IA... have %zu, need %zu",
    899             evbuffer_get_length (inbuf), needlen);
    900     if (evbuffer_get_length (inbuf) < needlen)
    901         return READ_LATER;
    902 
    903     /**
    904     ***  B->A: ENCRYPT (VC, crypto_select, len (padD), padD), ENCRYPT2 (Payload Stream)
    905     **/
    906 
    907     tr_cryptoEncryptInit (handshake->crypto);
    908     outbuf = evbuffer_new ();
    909 
     868  const size_t needlen = handshake->ia_len;
     869  struct evbuffer * outbuf;
     870  uint32_t crypto_select;
     871
     872  dbgmsg (handshake, "reading IA... have %zu, need %zu",
     873          evbuffer_get_length (inbuf), needlen);
     874  if (evbuffer_get_length (inbuf) < needlen)
     875    return READ_LATER;
     876
     877  /**
     878  ***  B->A: ENCRYPT (VC, crypto_select, len (padD), padD), ENCRYPT2 (Payload Stream)
     879  **/
     880
     881  tr_cryptoEncryptInit (handshake->crypto);
     882  outbuf = evbuffer_new ();
     883
     884  {
     885    /* send VC */
     886    uint8_t vc[VC_LENGTH];
     887    memset (vc, 0, VC_LENGTH);
     888    evbuffer_add (outbuf, vc, VC_LENGTH);
    910889    dbgmsg (handshake, "sending vc");
    911     /* send VC */
    912     {
    913         uint8_t vc[VC_LENGTH];
    914         memset (vc, 0, VC_LENGTH);
    915         evbuffer_add (outbuf, vc, VC_LENGTH);
    916     }
    917 
    918     /* send crypto_select */
    919     crypto_select = getCryptoSelect (handshake, handshake->crypto_provide);
    920     if (crypto_select)
    921     {
    922         dbgmsg (handshake, "selecting crypto mode '%d'", (int)crypto_select);
    923         evbuffer_add_uint32 (outbuf, crypto_select);
    924     }
    925     else
    926     {
    927         dbgmsg (handshake, "peer didn't offer an encryption mode we like.");
    928         evbuffer_free (outbuf);
    929         return tr_handshakeDone (handshake, false);
    930     }
    931 
    932     dbgmsg (handshake, "sending pad d");
    933     /* ENCRYPT (VC, crypto_provide, len (PadD), PadD
    934      * PadD is reserved for future extensions to the handshake...
    935      * standard practice at this time is for it to be zero-length */
    936     {
    937         const uint16_t len = 0;
    938         evbuffer_add_uint16 (outbuf, len);
    939     }
    940 
    941     /* maybe de-encrypt our connection */
    942     if (crypto_select == CRYPTO_PROVIDE_PLAINTEXT)
    943     {
    944         tr_peerIoWriteBuf (handshake->io, outbuf, false);
    945         tr_peerIoSetEncryption (handshake->io, PEER_ENCRYPTION_NONE);
    946     }
    947 
    948     dbgmsg (handshake, "sending handshake");
    949     /* send our handshake */
    950     {
    951         uint8_t msg[HANDSHAKE_SIZE];
    952         buildHandshakeMessage (handshake, msg);
    953 
    954         evbuffer_add (outbuf, msg, sizeof (msg));
    955         handshake->haveSentBitTorrentHandshake = 1;
    956     }
    957 
    958     /* send it out */
    959     tr_peerIoWriteBuf (handshake->io, outbuf, false);
    960     evbuffer_free (outbuf);
    961 
    962     /* now await the handshake */
    963     setState (handshake, AWAITING_PAYLOAD_STREAM);
    964     return READ_NOW;
     890  }
     891
     892  /* send crypto_select */
     893  crypto_select = getCryptoSelect (handshake, handshake->crypto_provide);
     894  if (crypto_select)
     895    {
     896      dbgmsg (handshake, "selecting crypto mode '%d'", (int)crypto_select);
     897      evbuffer_add_uint32 (outbuf, crypto_select);
     898    }
     899  else
     900    {
     901      dbgmsg (handshake, "peer didn't offer an encryption mode we like.");
     902      evbuffer_free (outbuf);
     903      return tr_handshakeDone (handshake, false);
     904    }
     905
     906  dbgmsg (handshake, "sending pad d");
     907  /* ENCRYPT (VC, crypto_provide, len (PadD), PadD
     908   * PadD is reserved for future extensions to the handshake...
     909   * standard practice at this time is for it to be zero-length */
     910  {
     911    const uint16_t len = 0;
     912    evbuffer_add_uint16 (outbuf, len);
     913  }
     914
     915  /* maybe de-encrypt our connection */
     916  if (crypto_select == CRYPTO_PROVIDE_PLAINTEXT)
     917    {
     918      tr_peerIoWriteBuf (handshake->io, outbuf, false);
     919      tr_peerIoSetEncryption (handshake->io, PEER_ENCRYPTION_NONE);
     920    }
     921
     922  dbgmsg (handshake, "sending handshake");
     923  /* send our handshake */
     924  {
     925    uint8_t msg[HANDSHAKE_SIZE];
     926    buildHandshakeMessage (handshake, msg);
     927
     928    evbuffer_add (outbuf, msg, sizeof (msg));
     929    handshake->haveSentBitTorrentHandshake = 1;
     930  }
     931
     932  /* send it out */
     933  tr_peerIoWriteBuf (handshake->io, outbuf, false);
     934  evbuffer_free (outbuf);
     935
     936  /* now await the handshake */
     937  setState (handshake, AWAITING_PAYLOAD_STREAM);
     938  return READ_NOW;
    965939}
    966940
     
    969943                   struct evbuffer * inbuf)
    970944{
    971     int i;
    972     const size_t      needlen = HANDSHAKE_SIZE;
    973 
    974     dbgmsg (handshake, "reading payload stream... have %zu, need %zu",
    975             evbuffer_get_length (inbuf), needlen);
    976     if (evbuffer_get_length (inbuf) < needlen)
    977         return READ_LATER;
    978 
    979     /* parse the handshake ... */
    980     i = parseHandshake (handshake, inbuf);
    981     dbgmsg (handshake, "parseHandshake returned %d", i);
    982     if (i != HANDSHAKE_OK)
    983         return tr_handshakeDone (handshake, false);
    984 
    985     /* we've completed the BT handshake... pass the work on to peer-msgs */
    986     return tr_handshakeDone (handshake, true);
     945  int i;
     946  const size_t needlen = HANDSHAKE_SIZE;
     947
     948  dbgmsg (handshake, "reading payload stream... have %zu, need %zu",
     949          evbuffer_get_length (inbuf), needlen);
     950  if (evbuffer_get_length (inbuf) < needlen)
     951    return READ_LATER;
     952
     953  /* parse the handshake ... */
     954  i = parseHandshake (handshake, inbuf);
     955  dbgmsg (handshake, "parseHandshake returned %d", i);
     956  if (i != HANDSHAKE_OK)
     957    return tr_handshakeDone (handshake, false);
     958
     959  /* we've completed the BT handshake... pass the work on to peer-msgs */
     960  return tr_handshakeDone (handshake, true);
    987961}
    988962
     
    996970canRead (struct tr_peerIo * io, void * arg, size_t * piece)
    997971{
    998     tr_handshake    * handshake = arg;
    999     struct evbuffer * inbuf = tr_peerIoGetReadBuffer (io);
    1000     ReadState         ret;
    1001     bool              readyForMore = true;
    1002 
    1003     assert (tr_isPeerIo (io));
    1004 
    1005     /* no piece data in handshake */
    1006     *piece = 0;
    1007 
    1008     dbgmsg (handshake, "handling canRead; state is [%s]",
    1009            getStateName (handshake->state));
    1010 
    1011     while (readyForMore)
    1012     {
    1013         switch (handshake->state)
     972  ReadState ret;
     973  tr_handshake * handshake = arg;
     974  struct evbuffer * inbuf = tr_peerIoGetReadBuffer (io);
     975  bool readyForMore = true;
     976
     977  assert (tr_isPeerIo (io));
     978
     979  /* no piece data in handshake */
     980  *piece = 0;
     981
     982  dbgmsg (handshake, "handling canRead; state is [%s]",
     983          getStateName (handshake->state));
     984
     985  while (readyForMore)
     986    {
     987      switch (handshake->state)
    1014988        {
    1015             case AWAITING_HANDSHAKE:
    1016                 ret = readHandshake  (handshake, inbuf); break;
    1017 
    1018             case AWAITING_PEER_ID:
    1019                 ret = readPeerId     (handshake, inbuf); break;
    1020 
    1021             case AWAITING_YA:
    1022                 ret = readYa         (handshake, inbuf); break;
    1023 
    1024             case AWAITING_PAD_A:
    1025                 ret = readPadA       (handshake, inbuf); break;
    1026 
    1027             case AWAITING_CRYPTO_PROVIDE:
    1028                 ret = readCryptoProvide (handshake, inbuf); break;
    1029 
    1030             case AWAITING_PAD_C:
    1031                 ret = readPadC       (handshake, inbuf); break;
    1032 
    1033             case AWAITING_IA:
    1034                 ret = readIA         (handshake, inbuf); break;
    1035 
    1036             case AWAITING_PAYLOAD_STREAM:
    1037                 ret = readPayloadStream (handshake, inbuf); break;
    1038 
    1039             case AWAITING_YB:
    1040                 ret = readYb         (handshake, inbuf); break;
    1041 
    1042             case AWAITING_VC:
    1043                 ret = readVC         (handshake, inbuf); break;
    1044 
    1045             case AWAITING_CRYPTO_SELECT:
    1046                 ret = readCryptoSelect (handshake, inbuf); break;
    1047 
    1048             case AWAITING_PAD_D:
    1049                 ret = readPadD       (handshake, inbuf); break;
    1050 
    1051             default:
    1052                 assert (0);
     989          case AWAITING_HANDSHAKE:
     990            ret = readHandshake (handshake, inbuf);
     991            break;
     992
     993          case AWAITING_PEER_ID:
     994            ret = readPeerId (handshake, inbuf);
     995            break;
     996
     997          case AWAITING_YA:
     998            ret = readYa (handshake, inbuf);
     999            break;
     1000
     1001          case AWAITING_PAD_A:
     1002            ret = readPadA (handshake, inbuf);
     1003            break;
     1004
     1005          case AWAITING_CRYPTO_PROVIDE:
     1006            ret = readCryptoProvide (handshake, inbuf);
     1007            break;
     1008
     1009          case AWAITING_PAD_C:
     1010            ret = readPadC (handshake, inbuf);
     1011            break;
     1012
     1013          case AWAITING_IA:
     1014            ret = readIA (handshake, inbuf);
     1015            break;
     1016
     1017          case AWAITING_PAYLOAD_STREAM:
     1018            ret = readPayloadStream (handshake, inbuf);
     1019            break;
     1020
     1021          case AWAITING_YB:
     1022            ret = readYb (handshake, inbuf);
     1023            break;
     1024
     1025          case AWAITING_VC:
     1026            ret = readVC (handshake, inbuf);
     1027            break;
     1028
     1029          case AWAITING_CRYPTO_SELECT:
     1030            ret = readCryptoSelect (handshake, inbuf);
     1031            break;
     1032
     1033          case AWAITING_PAD_D:
     1034            ret = readPadD (handshake, inbuf);
     1035            break;
     1036
     1037          default:
     1038            assert (0);
    10531039        }
    10541040
    1055         if (ret != READ_NOW)
    1056             readyForMore = false;
    1057         else if (handshake->state == AWAITING_PAD_C)
    1058             readyForMore = evbuffer_get_length (inbuf) >= handshake->pad_c_len;
    1059         else if (handshake->state == AWAITING_PAD_D)
    1060             readyForMore = evbuffer_get_length (inbuf) >= handshake->pad_d_len;
    1061         else if (handshake->state == AWAITING_IA)
    1062             readyForMore = evbuffer_get_length (inbuf) >= handshake->ia_len;
    1063     }
    1064 
    1065     return ret;
     1041      if (ret != READ_NOW)
     1042        readyForMore = false;
     1043      else if (handshake->state == AWAITING_PAD_C)
     1044        readyForMore = evbuffer_get_length (inbuf) >= handshake->pad_c_len;
     1045      else if (handshake->state == AWAITING_PAD_D)
     1046        readyForMore = evbuffer_get_length (inbuf) >= handshake->pad_d_len;
     1047      else if (handshake->state == AWAITING_IA)
     1048        readyForMore = evbuffer_get_length (inbuf) >= handshake->ia_len;
     1049    }
     1050
     1051  return ret;
    10661052}
    10671053
     
    10691055fireDoneFunc (tr_handshake * handshake, bool isConnected)
    10701056{
    1071     const uint8_t * peer_id = isConnected && handshake->havePeerID
    1072                             ? tr_peerIoGetPeersId (handshake->io)
    1073                             : NULL;
    1074     const bool success = (*handshake->doneCB)(handshake,
    1075                                                  handshake->io,
    1076                                                  handshake->haveReadAnythingFromPeer,
    1077                                                  isConnected,
    1078                                                  peer_id,
    1079                                                  handshake->doneUserData);
    1080 
    1081     return success;
     1057  const uint8_t * peer_id = isConnected && handshake->havePeerID
     1058                          ? tr_peerIoGetPeersId (handshake->io)
     1059                          : NULL;
     1060  const bool success = (*handshake->doneCB)(handshake,
     1061                                            handshake->io,
     1062                                            handshake->haveReadAnythingFromPeer,
     1063                                            isConnected,
     1064                                            peer_id,
     1065                                            handshake->doneUserData);
     1066
     1067  return success;
    10821068}
    10831069
     
    10851071tr_handshakeFree (tr_handshake * handshake)
    10861072{
    1087     if (handshake->io)
    1088         tr_peerIoUnref (handshake->io); /* balanced by the ref in tr_handshakeNew */
    1089 
    1090     event_free (handshake->timeout_timer);
    1091     tr_free (handshake);
     1073  if (handshake->io)
     1074    tr_peerIoUnref (handshake->io); /* balanced by the ref in tr_handshakeNew */
     1075
     1076  event_free (handshake->timeout_timer);
     1077  tr_free (handshake);
    10921078}
    10931079
     
    10951081tr_handshakeDone (tr_handshake * handshake, bool isOK)
    10961082{
    1097     bool success;
    1098 
    1099     dbgmsg (handshake, "handshakeDone: %s", isOK ? "connected" : "aborting");
    1100     tr_peerIoSetIOFuncs (handshake->io, NULL, NULL, NULL, NULL);
    1101 
    1102     success = fireDoneFunc (handshake, isOK);
    1103 
    1104     tr_handshakeFree (handshake);
    1105 
    1106     return success ? READ_LATER : READ_ERR;
     1083  bool success;
     1084
     1085  dbgmsg (handshake, "handshakeDone: %s", isOK ? "connected" : "aborting");
     1086  tr_peerIoSetIOFuncs (handshake->io, NULL, NULL, NULL, NULL);
     1087
     1088  success = fireDoneFunc (handshake, isOK);
     1089
     1090  tr_handshakeFree (handshake);
     1091
     1092  return success ? READ_LATER : READ_ERR;
    11071093}
    11081094
     
    11101096tr_handshakeAbort (tr_handshake * handshake)
    11111097{
    1112     if (handshake != NULL)
    1113         tr_handshakeDone (handshake, false);
     1098  if (handshake != NULL)
     1099    tr_handshakeDone (handshake, false);
    11141100}
    11151101
     
    11191105          void       * vhandshake)
    11201106{
    1121     int errcode = errno;
    1122     tr_handshake * handshake = vhandshake;
    1123 
    1124     if (io->utp_socket && !io->isIncoming && handshake->state == AWAITING_YB) {
    1125         /* This peer probably doesn't speak uTP. */
    1126         tr_torrent *tor =
    1127             tr_peerIoHasTorrentHash (io) ?
    1128             tr_torrentFindFromHash (handshake->session,
    1129                                     tr_peerIoGetTorrentHash (io)) :
    1130             NULL;
    1131         /* Don't mark a peer as non-uTP unless it's really a connect failure. */
    1132         if ((errcode == ETIMEDOUT || errcode == ECONNREFUSED) && tr_isTorrent(tor))
    1133             tr_peerMgrSetUtpFailed (tor, tr_peerIoGetAddress (io, NULL), true);
    1134 
    1135         if (!tr_peerIoReconnect (handshake->io)) {
    1136             uint8_t msg[HANDSHAKE_SIZE];
    1137             buildHandshakeMessage (handshake, msg);
    1138             handshake->haveSentBitTorrentHandshake = 1;
    1139             setReadState (handshake, AWAITING_HANDSHAKE);
    1140             tr_peerIoWriteBytes (handshake->io, msg, sizeof (msg), false);
     1107  int errcode = errno;
     1108  tr_handshake * handshake = vhandshake;
     1109
     1110  if (io->utp_socket && !io->isIncoming && handshake->state == AWAITING_YB)
     1111    {
     1112      /* This peer probably doesn't speak uTP. */
     1113
     1114      tr_torrent *tor;
     1115
     1116      if (tr_peerIoHasTorrentHash (io))
     1117        tor = tr_torrentFindFromHash (handshake->session, tr_peerIoGetTorrentHash (io));
     1118      else
     1119        tor = NULL;
     1120
     1121      /* Don't mark a peer as non-uTP unless it's really a connect failure. */
     1122      if ((errcode == ETIMEDOUT || errcode == ECONNREFUSED) && tr_isTorrent(tor))
     1123        tr_peerMgrSetUtpFailed (tor, tr_peerIoGetAddress (io, NULL), true);
     1124
     1125      if (!tr_peerIoReconnect (handshake->io))
     1126        {
     1127          uint8_t msg[HANDSHAKE_SIZE];
     1128          buildHandshakeMessage (handshake, msg);
     1129          handshake->haveSentBitTorrentHandshake = 1;
     1130          setReadState (handshake, AWAITING_HANDSHAKE);
     1131          tr_peerIoWriteBytes (handshake->io, msg, sizeof (msg), false);
    11411132        }
    11421133    }
    11431134
    1144     /* if the error happened while we were sending a public key, we might
    1145      * have encountered a peer that doesn't do encryption... reconnect and
    1146      * try a plaintext handshake */
    1147     if (((handshake->state == AWAITING_YB)
    1148         || (handshake->state == AWAITING_VC))
     1135  /* if the error happened while we were sending a public key, we might
     1136   * have encountered a peer that doesn't do encryption... reconnect and
     1137   * try a plaintext handshake */
     1138  if (((handshake->state == AWAITING_YB) || (handshake->state == AWAITING_VC))
    11491139      && (handshake->encryptionMode != TR_ENCRYPTION_REQUIRED)
    11501140      && (!tr_peerIoReconnect (handshake->io)))
    11511141    {
    1152         uint8_t msg[HANDSHAKE_SIZE];
    1153 
    1154         dbgmsg (handshake, "handshake failed, trying plaintext...");
    1155         buildHandshakeMessage (handshake, msg);
    1156         handshake->haveSentBitTorrentHandshake = 1;
    1157         setReadState (handshake, AWAITING_HANDSHAKE);
    1158         tr_peerIoWriteBytes (handshake->io, msg, sizeof (msg), false);
    1159     }
    1160     else
    1161     {
    1162         dbgmsg (handshake, "libevent got an error what==%d, errno=%d (%s)",
    1163              (int)what, errno, tr_strerror (errno));
    1164         tr_handshakeDone (handshake, false);
     1142      uint8_t msg[HANDSHAKE_SIZE];
     1143
     1144      dbgmsg (handshake, "handshake failed, trying plaintext...");
     1145      buildHandshakeMessage (handshake, msg);
     1146      handshake->haveSentBitTorrentHandshake = 1;
     1147      setReadState (handshake, AWAITING_HANDSHAKE);
     1148      tr_peerIoWriteBytes (handshake->io, msg, sizeof (msg), false);
     1149    }
     1150  else
     1151    {
     1152      dbgmsg (handshake, "libevent got an error what==%d, errno=%d (%s)",
     1153                         (int)what, errno, tr_strerror (errno));
     1154      tr_handshakeDone (handshake, false);
    11651155    }
    11661156}
     
    11731163handshakeTimeout (int foo UNUSED, short bar UNUSED, void * handshake)
    11741164{
    1175     tr_handshakeAbort (handshake);
     1165  tr_handshakeAbort (handshake);
    11761166}
    11771167
     
    11821172                 void                * doneUserData)
    11831173{
    1184     tr_handshake * handshake;
    1185     tr_session * session = tr_peerIoGetSession (io);
    1186 
    1187     handshake = tr_new0 (tr_handshake, 1);
    1188     handshake->io = io;
    1189     handshake->crypto = tr_peerIoGetCrypto (io);
    1190     handshake->encryptionMode = encryptionMode;
    1191     handshake->doneCB = doneCB;
    1192     handshake->doneUserData = doneUserData;
    1193     handshake->session = session;
    1194     handshake->timeout_timer = evtimer_new (session->event_base, handshakeTimeout, handshake);
    1195     tr_timerAdd (handshake->timeout_timer, HANDSHAKE_TIMEOUT_SEC, 0);
    1196 
    1197     tr_peerIoRef (io); /* balanced by the unref in tr_handshakeFree */
    1198     tr_peerIoSetIOFuncs (handshake->io, canRead, NULL, gotError, handshake);
    1199     tr_peerIoSetEncryption (io, PEER_ENCRYPTION_NONE);
    1200 
    1201     if (tr_peerIoIsIncoming (handshake->io))
    1202         setReadState (handshake, AWAITING_HANDSHAKE);
    1203     else if (encryptionMode != TR_CLEAR_PREFERRED)
    1204         sendYa (handshake);
    1205     else
    1206     {
    1207         uint8_t msg[HANDSHAKE_SIZE];
    1208         buildHandshakeMessage (handshake, msg);
    1209 
    1210         handshake->haveSentBitTorrentHandshake = 1;
    1211         setReadState (handshake, AWAITING_HANDSHAKE);
    1212         tr_peerIoWriteBytes (handshake->io, msg, sizeof (msg), false);
    1213     }
    1214 
    1215     return handshake;
     1174  tr_handshake * handshake;
     1175  tr_session * session = tr_peerIoGetSession (io);
     1176
     1177  handshake = tr_new0 (tr_handshake, 1);
     1178  handshake->io = io;
     1179  handshake->crypto = tr_peerIoGetCrypto (io);
     1180  handshake->encryptionMode = encryptionMode;
     1181  handshake->doneCB = doneCB;
     1182  handshake->doneUserData = doneUserData;
     1183  handshake->session = session;
     1184  handshake->timeout_timer = evtimer_new (session->event_base, handshakeTimeout, handshake);
     1185  tr_timerAdd (handshake->timeout_timer, HANDSHAKE_TIMEOUT_SEC, 0);
     1186
     1187  tr_peerIoRef (io); /* balanced by the unref in tr_handshakeFree */
     1188  tr_peerIoSetIOFuncs (handshake->io, canRead, NULL, gotError, handshake);
     1189  tr_peerIoSetEncryption (io, PEER_ENCRYPTION_NONE);
     1190
     1191  if (tr_peerIoIsIncoming (handshake->io))
     1192    {
     1193      setReadState (handshake, AWAITING_HANDSHAKE);
     1194    }
     1195  else if (encryptionMode != TR_CLEAR_PREFERRED)
     1196    {
     1197      sendYa (handshake);
     1198    }
     1199  else
     1200    {
     1201      uint8_t msg[HANDSHAKE_SIZE];
     1202      buildHandshakeMessage (handshake, msg);
     1203
     1204      handshake->haveSentBitTorrentHandshake = 1;
     1205      setReadState (handshake, AWAITING_HANDSHAKE);
     1206      tr_peerIoWriteBytes (handshake->io, msg, sizeof (msg), false);
     1207    }
     1208
     1209  return handshake;
    12161210}
    12171211
     
    12191213tr_handshakeGetIO (tr_handshake * handshake)
    12201214{
    1221     assert (handshake);
    1222     assert (handshake->io);
    1223 
    1224     return handshake->io;
     1215  assert (handshake != NULL);
     1216  assert (handshake->io != NULL);
     1217
     1218  return handshake->io;
    12251219}
    12261220
     
    12281222tr_handshakeStealIO (tr_handshake * handshake)
    12291223{
    1230     struct tr_peerIo * io;
    1231 
    1232     assert (handshake);
    1233     assert (handshake->io);
    1234 
    1235     io = handshake->io;
    1236     handshake->io = NULL;
    1237     return io;
     1224  struct tr_peerIo * io;
     1225
     1226  assert (handshake != NULL);
     1227  assert (handshake->io != NULL);
     1228
     1229  io = handshake->io;
     1230  handshake->io = NULL;
     1231  return io;
    12381232}
    12391233
     
    12421236                     tr_port                   * port)
    12431237{
    1244     assert (handshake);
    1245     assert (handshake->io);
    1246 
    1247     return tr_peerIoGetAddress (handshake->io, port);
    1248 }
    1249 
     1238  assert (handshake != NULL);
     1239  assert (handshake->io != NULL);
     1240
     1241  return tr_peerIoGetAddress (handshake->io, port);
     1242}
     1243
Note: See TracChangeset for help on using the changeset viewer.