Home | History | Annotate | Download | only in p2p
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "content/browser/renderer_host/p2p/socket_host.h"
      6 
      7 #include "base/metrics/histogram.h"
      8 #include "base/sys_byteorder.h"
      9 #include "content/browser/renderer_host/p2p/socket_host_tcp.h"
     10 #include "content/browser/renderer_host/p2p/socket_host_tcp_server.h"
     11 #include "content/browser/renderer_host/p2p/socket_host_udp.h"
     12 #include "content/browser/renderer_host/render_process_host_impl.h"
     13 #include "content/public/browser/browser_thread.h"
     14 #include "crypto/hmac.h"
     15 #include "third_party/libjingle/source/talk/p2p/base/stun.h"
     16 #include "third_party/webrtc/base/asyncpacketsocket.h"
     17 #include "third_party/webrtc/base/byteorder.h"
     18 #include "third_party/webrtc/base/messagedigest.h"
     19 
     20 namespace {
     21 
     22 const uint32 kStunMagicCookie = 0x2112A442;
     23 const size_t kMinRtpHeaderLength = 12;
     24 const size_t kMinRtcpHeaderLength = 8;
     25 const size_t kRtpExtensionHeaderLength = 4;
     26 const size_t kDtlsRecordHeaderLength = 13;
     27 const size_t kTurnChannelHeaderLength = 4;
     28 const size_t kAbsSendTimeExtensionLength = 3;
     29 const size_t kOneByteHeaderLength = 1;
     30 const size_t kMaxRtpPacketLength = 2048;
     31 
     32 // Fake auth tag written by the render process if external authentication is
     33 // enabled. HMAC in packet will be compared against this value before updating
     34 // packet with actual HMAC value.
     35 static const unsigned char kFakeAuthTag[10] = {
     36     0xba, 0xdd, 0xba, 0xdd, 0xba, 0xdd, 0xba, 0xdd, 0xba, 0xdd
     37 };
     38 
     39 bool IsTurnChannelData(const char* data, size_t length) {
     40   return length >= kTurnChannelHeaderLength && ((*data & 0xC0) == 0x40);
     41 }
     42 
     43 bool IsDtlsPacket(const char* data, size_t length) {
     44   const uint8* u = reinterpret_cast<const uint8*>(data);
     45   return (length >= kDtlsRecordHeaderLength && (u[0] > 19 && u[0] < 64));
     46 }
     47 
     48 bool IsRtcpPacket(const char* data, size_t length) {
     49   if (length < kMinRtcpHeaderLength) {
     50     return false;
     51   }
     52 
     53   int type = (static_cast<uint8>(data[1]) & 0x7F);
     54   return (type >= 64 && type < 96);
     55 }
     56 
     57 bool IsTurnSendIndicationPacket(const char* data, size_t length) {
     58   if (length < content::P2PSocketHost::kStunHeaderSize) {
     59     return false;
     60   }
     61 
     62   uint16 type = rtc::GetBE16(data);
     63   return (type == cricket::TURN_SEND_INDICATION);
     64 }
     65 
     66 bool IsRtpPacket(const char* data, size_t length) {
     67   return (length >= kMinRtpHeaderLength) && ((*data & 0xC0) == 0x80);
     68 }
     69 
     70 // Verifies rtp header and message length.
     71 bool ValidateRtpHeader(const char* rtp, size_t length, size_t* header_length) {
     72   if (header_length) {
     73     *header_length = 0;
     74   }
     75 
     76   if (length < kMinRtpHeaderLength) {
     77     return false;
     78   }
     79 
     80   size_t cc_count = rtp[0] & 0x0F;
     81   size_t header_length_without_extension = kMinRtpHeaderLength + 4 * cc_count;
     82   if (header_length_without_extension > length) {
     83     return false;
     84   }
     85 
     86   // If extension bit is not set, we are done with header processing, as input
     87   // length is verified above.
     88   if (!(rtp[0] & 0x10)) {
     89     if (header_length)
     90       *header_length = header_length_without_extension;
     91 
     92     return true;
     93   }
     94 
     95   rtp += header_length_without_extension;
     96 
     97   if (header_length_without_extension + kRtpExtensionHeaderLength > length) {
     98     return false;
     99   }
    100 
    101   // Getting extension profile length.
    102   // Length is in 32 bit words.
    103   uint16 extension_length_in_32bits = rtc::GetBE16(rtp + 2);
    104   size_t extension_length = extension_length_in_32bits * 4;
    105 
    106   size_t rtp_header_length = extension_length +
    107                              header_length_without_extension +
    108                              kRtpExtensionHeaderLength;
    109 
    110   // Verify input length against total header size.
    111   if (rtp_header_length > length) {
    112     return false;
    113   }
    114 
    115   if (header_length) {
    116     *header_length = rtp_header_length;
    117   }
    118   return true;
    119 }
    120 
    121 void UpdateAbsSendTimeExtensionValue(char* extension_data,
    122                                      size_t length,
    123                                      uint32 abs_send_time) {
    124   // Absolute send time in RTP streams.
    125   //
    126   // The absolute send time is signaled to the receiver in-band using the
    127   // general mechanism for RTP header extensions [RFC5285]. The payload
    128   // of this extension (the transmitted value) is a 24-bit unsigned integer
    129   // containing the sender's current time in seconds as a fixed point number
    130   // with 18 bits fractional part.
    131   //
    132   // The form of the absolute send time extension block:
    133   //
    134   //    0                   1                   2                   3
    135   //    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    136   //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    137   //   |  ID   | len=2 |              absolute send time               |
    138   //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    139   if (length != kAbsSendTimeExtensionLength) {
    140     NOTREACHED();
    141     return;
    142   }
    143 
    144   // Now() has resolution ~1-15ms, using HighResNow(). But it is warned not to
    145   // use it unless necessary, as it is expensive than Now().
    146   uint32 now_second = abs_send_time;
    147   if (!now_second) {
    148     uint64 now_us =
    149         (base::TimeTicks::HighResNow() - base::TimeTicks()).InMicroseconds();
    150     // Convert second to 24-bit unsigned with 18 bit fractional part
    151     now_second =
    152         ((now_us << 18) / base::Time::kMicrosecondsPerSecond) & 0x00FFFFFF;
    153   }
    154   // TODO(mallinath) - Add SetBE24 to byteorder.h in libjingle.
    155   extension_data[0] = static_cast<uint8>(now_second >> 16);
    156   extension_data[1] = static_cast<uint8>(now_second >> 8);
    157   extension_data[2] = static_cast<uint8>(now_second);
    158 }
    159 
    160 // Assumes |length| is actual packet length + tag length. Updates HMAC at end of
    161 // the RTP packet.
    162 void UpdateRtpAuthTag(char* rtp,
    163                       size_t length,
    164                       const rtc::PacketOptions& options) {
    165   // If there is no key, return.
    166   if (options.packet_time_params.srtp_auth_key.empty()) {
    167     return;
    168   }
    169 
    170   size_t tag_length = options.packet_time_params.srtp_auth_tag_len;
    171 
    172   // ROC (rollover counter) is at the beginning of the auth tag.
    173   const size_t kRocLength = 4;
    174   if (tag_length < kRocLength || tag_length > length) {
    175     NOTREACHED();
    176     return;
    177   }
    178 
    179   crypto::HMAC hmac(crypto::HMAC::SHA1);
    180   if (!hmac.Init(reinterpret_cast<const unsigned char*>(
    181         &options.packet_time_params.srtp_auth_key[0]),
    182         options.packet_time_params.srtp_auth_key.size())) {
    183     NOTREACHED();
    184     return;
    185   }
    186 
    187   if (tag_length > hmac.DigestLength()) {
    188     NOTREACHED();
    189     return;
    190   }
    191 
    192   char* auth_tag = rtp + (length - tag_length);
    193 
    194   // We should have a fake HMAC value @ auth_tag.
    195   DCHECK_EQ(0, memcmp(auth_tag, kFakeAuthTag, tag_length));
    196 
    197   // Copy ROC after end of rtp packet.
    198   memcpy(auth_tag, &options.packet_time_params.srtp_packet_index, kRocLength);
    199   // Authentication of a RTP packet will have RTP packet + ROC size.
    200   int auth_required_length = length - tag_length + kRocLength;
    201 
    202   unsigned char output[64];
    203   if (!hmac.Sign(base::StringPiece(rtp, auth_required_length),
    204                  output, sizeof(output))) {
    205     NOTREACHED();
    206     return;
    207   }
    208   // Copy HMAC from output to packet. This is required as auth tag length
    209   // may not be equal to the actual HMAC length.
    210   memcpy(auth_tag, output, tag_length);
    211 }
    212 
    213 }  // namespace
    214 
    215 namespace content {
    216 
    217 namespace packet_processing_helpers {
    218 
    219 bool ApplyPacketOptions(char* data,
    220                         size_t length,
    221                         const rtc::PacketOptions& options,
    222                         uint32 abs_send_time) {
    223   DCHECK(data != NULL);
    224   DCHECK(length > 0);
    225   // if there is no valid |rtp_sendtime_extension_id| and |srtp_auth_key| in
    226   // PacketOptions, nothing to be updated in this packet.
    227   if (options.packet_time_params.rtp_sendtime_extension_id == -1 &&
    228       options.packet_time_params.srtp_auth_key.empty()) {
    229     return true;
    230   }
    231 
    232   DCHECK(!IsDtlsPacket(data, length));
    233   DCHECK(!IsRtcpPacket(data, length));
    234 
    235   // If there is a srtp auth key present then packet must be a RTP packet.
    236   // RTP packet may have been wrapped in a TURN Channel Data or
    237   // TURN send indication.
    238   size_t rtp_start_pos;
    239   size_t rtp_length;
    240   if (!GetRtpPacketStartPositionAndLength(
    241       data, length, &rtp_start_pos, &rtp_length)) {
    242     // This method should never return false.
    243     NOTREACHED();
    244     return false;
    245   }
    246 
    247   // Skip to rtp packet.
    248   char* start = data + rtp_start_pos;
    249   // If packet option has non default value (-1) for sendtime extension id,
    250   // then we should parse the rtp packet to update the timestamp. Otherwise
    251   // just calculate HMAC and update packet with it.
    252   if (options.packet_time_params.rtp_sendtime_extension_id != -1) {
    253     UpdateRtpAbsSendTimeExtension(
    254         start,
    255         rtp_length,
    256         options.packet_time_params.rtp_sendtime_extension_id,
    257         abs_send_time);
    258   }
    259 
    260   UpdateRtpAuthTag(start, rtp_length, options);
    261   return true;
    262 }
    263 
    264 bool GetRtpPacketStartPositionAndLength(const char* packet,
    265                                         size_t length,
    266                                         size_t* rtp_start_pos,
    267                                         size_t* rtp_packet_length) {
    268   if (length < kMinRtpHeaderLength || length > kMaxRtpPacketLength) {
    269     return false;
    270   }
    271 
    272   size_t rtp_begin;
    273   size_t rtp_length = 0;
    274   if (IsTurnChannelData(packet, length)) {
    275     // Turn Channel Message header format.
    276     //   0                   1                   2                   3
    277     //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    278     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    279     // |         Channel Number        |            Length             |
    280     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    281     // |                                                               |
    282     // /                       Application Data                        /
    283     // /                                                               /
    284     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    285     rtp_begin = kTurnChannelHeaderLength;
    286     rtp_length = rtc::GetBE16(&packet[2]);
    287     if (length < rtp_length + kTurnChannelHeaderLength) {
    288       return false;
    289     }
    290   } else if (IsTurnSendIndicationPacket(packet, length)) {
    291     // Validate STUN message length.
    292     const size_t stun_message_length = rtc::GetBE16(&packet[2]);
    293     if (stun_message_length + P2PSocketHost::kStunHeaderSize != length) {
    294       return false;
    295     }
    296 
    297     // First skip mandatory stun header which is of 20 bytes.
    298     rtp_begin = P2PSocketHost::kStunHeaderSize;
    299     // Loop through STUN attributes until we find STUN DATA attribute.
    300     bool data_attr_present = false;
    301     while (rtp_begin < length) {
    302       // Keep reading STUN attributes until we hit DATA attribute.
    303       // Attribute will be a TLV structure.
    304       // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    305       // |         Type                  |            Length             |
    306       // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    307       // |                         Value (variable)                ....
    308       // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    309       // The value in the length field MUST contain the length of the Value
    310       // part of the attribute, prior to padding, measured in bytes.  Since
    311       // STUN aligns attributes on 32-bit boundaries, attributes whose content
    312       // is not a multiple of 4 bytes are padded with 1, 2, or 3 bytes of
    313       // padding so that its value contains a multiple of 4 bytes.  The
    314       // padding bits are ignored, and may be any value.
    315       uint16 attr_type, attr_length;
    316       const int kAttrHeaderLength = sizeof(attr_type) + sizeof(attr_length);
    317 
    318       if (length < rtp_begin + kAttrHeaderLength) {
    319         return false;
    320       }
    321 
    322       // Getting attribute type and length.
    323       attr_type = rtc::GetBE16(&packet[rtp_begin]);
    324       attr_length = rtc::GetBE16(
    325           &packet[rtp_begin + sizeof(attr_type)]);
    326 
    327       rtp_begin += kAttrHeaderLength;  // Skip STUN_DATA_ATTR header.
    328 
    329       // Checking for bogus attribute length.
    330       if (length < rtp_begin + attr_length) {
    331         return false;
    332       }
    333 
    334       if (attr_type != cricket::STUN_ATTR_DATA) {
    335         rtp_begin += attr_length;
    336         if ((attr_length % 4) != 0) {
    337           rtp_begin += (4 - (attr_length % 4));
    338         }
    339         continue;
    340       }
    341 
    342       data_attr_present = true;
    343       rtp_length = attr_length;
    344 
    345       // We found STUN_DATA_ATTR. We can skip parsing rest of the packet.
    346       break;
    347     }
    348 
    349     if (!data_attr_present) {
    350       // There is no data attribute present in the message. We can't do anything
    351       // with the message.
    352       return false;
    353     }
    354 
    355   } else {
    356     // This is a raw RTP packet.
    357     rtp_begin = 0;
    358     rtp_length = length;
    359   }
    360 
    361   // Making sure we have a valid RTP packet at the end.
    362   if (IsRtpPacket(packet + rtp_begin, rtp_length) &&
    363       ValidateRtpHeader(packet + rtp_begin, rtp_length, NULL)) {
    364     *rtp_start_pos = rtp_begin;
    365     *rtp_packet_length = rtp_length;
    366     return true;
    367   }
    368   return false;
    369 }
    370 
    371 // ValidateRtpHeader must be called before this method to make sure, we have
    372 // a sane rtp packet.
    373 bool UpdateRtpAbsSendTimeExtension(char* rtp,
    374                                    size_t length,
    375                                    int extension_id,
    376                                    uint32 abs_send_time) {
    377   //  0                   1                   2                   3
    378   //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    379   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    380   // |V=2|P|X|  CC   |M|     PT      |       sequence number         |
    381   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    382   // |                           timestamp                           |
    383   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    384   // |           synchronization source (SSRC) identifier            |
    385   // +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
    386   // |            contributing source (CSRC) identifiers             |
    387   // |                             ....                              |
    388   // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    389 
    390   // Return if extension bit is not set.
    391   if (!(rtp[0] & 0x10)) {
    392     return true;
    393   }
    394 
    395   size_t cc_count = rtp[0] & 0x0F;
    396   size_t header_length_without_extension = kMinRtpHeaderLength + 4 * cc_count;
    397 
    398   rtp += header_length_without_extension;
    399 
    400   // Getting extension profile ID and length.
    401   uint16 profile_id = rtc::GetBE16(rtp);
    402   // Length is in 32 bit words.
    403   uint16 extension_length_in_32bits = rtc::GetBE16(rtp + 2);
    404   size_t extension_length = extension_length_in_32bits * 4;
    405 
    406   rtp += kRtpExtensionHeaderLength;  // Moving past extension header.
    407 
    408   bool found = false;
    409   // WebRTC is using one byte header extension.
    410   // TODO(mallinath) - Handle two byte header extension.
    411   if (profile_id == 0xBEDE) {  // OneByte extension header
    412     //  0
    413     //  0 1 2 3 4 5 6 7
    414     // +-+-+-+-+-+-+-+-+
    415     // |  ID   |length |
    416     // +-+-+-+-+-+-+-+-+
    417 
    418     //  0                   1                   2                   3
    419     //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    420     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    421     // |       0xBE    |    0xDE       |           length=3            |
    422     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    423     // |  ID   | L=0   |     data      |  ID   |  L=1  |   data...
    424     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    425     //       ...data   |    0 (pad)    |    0 (pad)    |  ID   | L=3   |
    426     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    427     // |                          data                                 |
    428     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    429     const char* extension_start = rtp;
    430     const char* extension_end = extension_start + extension_length;
    431 
    432     while (rtp < extension_end) {
    433       const int id = (*rtp & 0xF0) >> 4;
    434       const size_t length = (*rtp & 0x0F) + 1;
    435       if (rtp + kOneByteHeaderLength + length > extension_end) {
    436         return false;
    437       }
    438       // The 4-bit length is the number minus one of data bytes of this header
    439       // extension element following the one-byte header.
    440       if (id == extension_id) {
    441         UpdateAbsSendTimeExtensionValue(
    442             rtp + kOneByteHeaderLength, length, abs_send_time);
    443         found = true;
    444         break;
    445       }
    446       rtp += kOneByteHeaderLength + length;
    447       // Counting padding bytes.
    448       while ((rtp < extension_end) && (*rtp == 0)) {
    449         ++rtp;
    450       }
    451     }
    452   }
    453   return found;
    454 }
    455 
    456 }  // packet_processing_helpers
    457 
    458 P2PSocketHost::P2PSocketHost(IPC::Sender* message_sender,
    459                              int socket_id,
    460                              ProtocolType protocol_type)
    461     : message_sender_(message_sender),
    462       id_(socket_id),
    463       state_(STATE_UNINITIALIZED),
    464       dump_incoming_rtp_packet_(false),
    465       dump_outgoing_rtp_packet_(false),
    466       weak_ptr_factory_(this),
    467       protocol_type_(protocol_type),
    468       send_packets_delayed_total_(0),
    469       send_packets_total_(0),
    470       send_bytes_delayed_max_(0),
    471       send_bytes_delayed_cur_(0) {
    472 }
    473 
    474 P2PSocketHost::~P2PSocketHost() {
    475   if (protocol_type_ == P2PSocketHost::UDP) {
    476     UMA_HISTOGRAM_COUNTS_10000("WebRTC.SystemMaxConsecutiveBytesDelayed_UDP",
    477                                send_bytes_delayed_max_);
    478   } else {
    479     UMA_HISTOGRAM_COUNTS_10000("WebRTC.SystemMaxConsecutiveBytesDelayed_TCP",
    480                                send_bytes_delayed_max_);
    481   }
    482 
    483   if (send_packets_total_ > 0) {
    484     int delay_rate = (send_packets_delayed_total_ * 100) / send_packets_total_;
    485     if (protocol_type_ == P2PSocketHost::UDP) {
    486       UMA_HISTOGRAM_PERCENTAGE("WebRTC.SystemPercentPacketsDelayed_UDP",
    487                                delay_rate);
    488     } else {
    489       UMA_HISTOGRAM_PERCENTAGE("WebRTC.SystemPercentPacketsDelayed_TCP",
    490                                delay_rate);
    491     }
    492   }
    493 }
    494 
    495 // Verifies that the packet |data| has a valid STUN header.
    496 // static
    497 bool P2PSocketHost::GetStunPacketType(
    498     const char* data, int data_size, StunMessageType* type) {
    499 
    500   if (data_size < kStunHeaderSize) {
    501     return false;
    502   }
    503 
    504   uint32 cookie = base::NetToHost32(*reinterpret_cast<const uint32*>(data + 4));
    505   if (cookie != kStunMagicCookie) {
    506     return false;
    507   }
    508 
    509   uint16 length = base::NetToHost16(*reinterpret_cast<const uint16*>(data + 2));
    510   if (length != data_size - kStunHeaderSize) {
    511     return false;
    512   }
    513 
    514   int message_type = base::NetToHost16(*reinterpret_cast<const uint16*>(data));
    515 
    516   // Verify that the type is known:
    517   switch (message_type) {
    518     case STUN_BINDING_REQUEST:
    519     case STUN_BINDING_RESPONSE:
    520     case STUN_BINDING_ERROR_RESPONSE:
    521     case STUN_SHARED_SECRET_REQUEST:
    522     case STUN_SHARED_SECRET_RESPONSE:
    523     case STUN_SHARED_SECRET_ERROR_RESPONSE:
    524     case STUN_ALLOCATE_REQUEST:
    525     case STUN_ALLOCATE_RESPONSE:
    526     case STUN_ALLOCATE_ERROR_RESPONSE:
    527     case STUN_SEND_REQUEST:
    528     case STUN_SEND_RESPONSE:
    529     case STUN_SEND_ERROR_RESPONSE:
    530     case STUN_DATA_INDICATION:
    531       *type = static_cast<StunMessageType>(message_type);
    532       return true;
    533 
    534     default:
    535       return false;
    536   }
    537 }
    538 
    539 // static
    540 bool P2PSocketHost::IsRequestOrResponse(StunMessageType type) {
    541   return type == STUN_BINDING_REQUEST || type == STUN_BINDING_RESPONSE ||
    542       type == STUN_ALLOCATE_REQUEST || type == STUN_ALLOCATE_RESPONSE;
    543 }
    544 
    545 // static
    546 P2PSocketHost* P2PSocketHost::Create(IPC::Sender* message_sender,
    547                                      int socket_id,
    548                                      P2PSocketType type,
    549                                      net::URLRequestContextGetter* url_context,
    550                                      P2PMessageThrottler* throttler) {
    551   switch (type) {
    552     case P2P_SOCKET_UDP:
    553       return new P2PSocketHostUdp(message_sender, socket_id, throttler);
    554     case P2P_SOCKET_TCP_SERVER:
    555       return new P2PSocketHostTcpServer(
    556           message_sender, socket_id, P2P_SOCKET_TCP_CLIENT);
    557 
    558     case P2P_SOCKET_STUN_TCP_SERVER:
    559       return new P2PSocketHostTcpServer(
    560           message_sender, socket_id, P2P_SOCKET_STUN_TCP_CLIENT);
    561 
    562     case P2P_SOCKET_TCP_CLIENT:
    563     case P2P_SOCKET_SSLTCP_CLIENT:
    564     case P2P_SOCKET_TLS_CLIENT:
    565       return new P2PSocketHostTcp(message_sender, socket_id, type, url_context);
    566 
    567     case P2P_SOCKET_STUN_TCP_CLIENT:
    568     case P2P_SOCKET_STUN_SSLTCP_CLIENT:
    569     case P2P_SOCKET_STUN_TLS_CLIENT:
    570       return new P2PSocketHostStunTcp(
    571           message_sender, socket_id, type, url_context);
    572   }
    573 
    574   NOTREACHED();
    575   return NULL;
    576 }
    577 
    578 void P2PSocketHost::StartRtpDump(
    579     bool incoming,
    580     bool outgoing,
    581     const RenderProcessHost::WebRtcRtpPacketCallback& packet_callback) {
    582   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    583   DCHECK(!packet_callback.is_null());
    584   DCHECK(incoming || outgoing);
    585 
    586   if (incoming) {
    587     dump_incoming_rtp_packet_ = true;
    588   }
    589 
    590   if (outgoing) {
    591     dump_outgoing_rtp_packet_ = true;
    592   }
    593 
    594   packet_dump_callback_ = packet_callback;
    595 }
    596 
    597 void P2PSocketHost::StopRtpDump(bool incoming, bool outgoing) {
    598   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    599   DCHECK(incoming || outgoing);
    600 
    601   if (incoming) {
    602     dump_incoming_rtp_packet_ = false;
    603   }
    604 
    605   if (outgoing) {
    606     dump_outgoing_rtp_packet_ = false;
    607   }
    608 
    609   if (!dump_incoming_rtp_packet_ && !dump_outgoing_rtp_packet_) {
    610     packet_dump_callback_.Reset();
    611   }
    612 }
    613 
    614 void P2PSocketHost::DumpRtpPacket(const char* packet,
    615                                   size_t length,
    616                                   bool incoming) {
    617   if (IsDtlsPacket(packet, length) || IsRtcpPacket(packet, length)) {
    618     return;
    619   }
    620 
    621   size_t rtp_packet_pos = 0;
    622   size_t rtp_packet_length = length;
    623   if (!packet_processing_helpers::GetRtpPacketStartPositionAndLength(
    624           packet, length, &rtp_packet_pos, &rtp_packet_length)) {
    625     return;
    626   }
    627 
    628   packet += rtp_packet_pos;
    629 
    630   size_t header_length = 0;
    631   bool valid = ValidateRtpHeader(packet, rtp_packet_length, &header_length);
    632   if (!valid) {
    633     DCHECK(false);
    634     return;
    635   }
    636 
    637   scoped_ptr<uint8[]> header_buffer(new uint8[header_length]);
    638   memcpy(header_buffer.get(), packet, header_length);
    639 
    640   // Posts to the IO thread as the data members should be accessed on the IO
    641   // thread only.
    642   BrowserThread::PostTask(BrowserThread::IO,
    643                           FROM_HERE,
    644                           base::Bind(&P2PSocketHost::DumpRtpPacketOnIOThread,
    645                                      weak_ptr_factory_.GetWeakPtr(),
    646                                      Passed(&header_buffer),
    647                                      header_length,
    648                                      rtp_packet_length,
    649                                      incoming));
    650 }
    651 
    652 void P2PSocketHost::DumpRtpPacketOnIOThread(scoped_ptr<uint8[]> packet_header,
    653                                             size_t header_length,
    654                                             size_t packet_length,
    655                                             bool incoming) {
    656   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    657 
    658   if ((incoming && !dump_incoming_rtp_packet_) ||
    659       (!incoming && !dump_outgoing_rtp_packet_) ||
    660       packet_dump_callback_.is_null()) {
    661     return;
    662   }
    663 
    664   // |packet_dump_callback_| must be called on the UI thread.
    665   BrowserThread::PostTask(BrowserThread::UI,
    666                           FROM_HERE,
    667                           base::Bind(packet_dump_callback_,
    668                                      Passed(&packet_header),
    669                                      header_length,
    670                                      packet_length,
    671                                      incoming));
    672 }
    673 
    674 void P2PSocketHost::IncrementDelayedPackets() {
    675   send_packets_delayed_total_++;
    676 }
    677 
    678 void P2PSocketHost::IncrementTotalSentPackets() {
    679   send_packets_total_++;
    680 }
    681 
    682 void P2PSocketHost::IncrementDelayedBytes(uint32 size) {
    683   send_bytes_delayed_cur_ += size;
    684   if (send_bytes_delayed_cur_ > send_bytes_delayed_max_) {
    685     send_bytes_delayed_max_ = send_bytes_delayed_cur_;
    686   }
    687 }
    688 
    689 void P2PSocketHost::DecrementDelayedBytes(uint32 size) {
    690   send_bytes_delayed_cur_ -= size;
    691   DCHECK_GE(send_bytes_delayed_cur_, 0);
    692 }
    693 
    694 }  // namespace content
    695