KernelTcp.cc 22.9 KB
Newer Older
Robert Ricci's avatar
Robert Ricci committed
1 2 3 4 5 6
/*
 * EMULAB-COPYRIGHT
 * Copyright (c) 2006 University of Utah and the Flux Group.
 * All rights reserved.
 */

7 8 9
// KernelTcp.cc

#include "lib.h"
10
#include "log.h"
11
#include "KernelTcp.h"
12
#include "Command.h"
13

14 15
#include "TSThroughputSensor.h"

16 17
using namespace std;

18 19 20 21 22 23 24 25 26 27
namespace
{
  bool changeSocket(int sockfd, int level, int optname, int value,
                    string optstring);
  void kernelTcpCallback(unsigned char *,
                         struct pcap_pkthdr const * pcapInfo,
                         unsigned char const * packet);
  int getLinkLayer(struct pcap_pkthdr const * pcapInfo,
                   unsigned char const * packet);
  void handleTcp(struct pcap_pkthdr const * pcapInfo,
28
                 struct ip const * ipPacket,
29 30 31 32 33 34
                 struct tcphdr const * tcpPacket,
                 unsigned char const * tcpPacketStart,
                 list<Option> & ipOptions);
  bool handleKernel(Connection * conn, struct tcp_info * kernel);
  void parseOptions(unsigned char const * buffer, int size,
                    list<Option> * options);
35 36 37 38 39
}

pcap_t * KernelTcp::pcapDescriptor = NULL;
int KernelTcp::pcapfd = -1;

40 41 42 43 44 45 46
KernelTcp::KernelTcp()
  : state(DISCONNECTED)
  , peersock(-1)
  , sendBufferSize(0)
  , receiveBufferSize(0)
  , maxSegmentSize(0)
  , useNagles(1)
47 48
  , debugPrevTime(getCurrentTime())
  , debugByteCount(0)
49 50 51 52 53 54 55 56 57 58 59 60 61 62
{
}

KernelTcp::~KernelTcp()
{
  if (peersock != -1)
  {
    close(peersock);
  }
}

auto_ptr<ConnectionModel> KernelTcp::clone(void)
{
  auto_ptr<KernelTcp> result(new KernelTcp());
63 64 65 66 67 68 69
  result->sendBufferSize = sendBufferSize;
  result->receiveBufferSize = receiveBufferSize;
  result->maxSegmentSize = maxSegmentSize;
  result->useNagles = useNagles;
  result->state = state;
  auto_ptr<ConnectionModel> modelResult(result.release());
  return modelResult;
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
}

void KernelTcp::connect(Order & planet)
{
  if (state == DISCONNECTED)
  {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
      logWrite(EXCEPTION, "Cannot create a peer socket: %s", strerror(errno));
      return;
    }

    // Set up all parameters
    if ((sendBufferSize != 0 && !changeSocket(sockfd, SOL_SOCKET, SO_SNDBUF,
85
                                              sendBufferSize, "SO_SNDBUF"))
86 87 88 89 90 91 92
        || (receiveBufferSize != 0 && !changeSocket(sockfd, SOL_SOCKET,
                                                    SO_RCVBUF,
                                                    receiveBufferSize,
                                                    "SO_RCVBUF"))
        || !changeSocket(sockfd, IPPROTO_TCP, TCP_NODELAY, !useNagles,
                         "TCP_NODELAY"))
    {
93
      // Error message already printed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
      close(sockfd);
      return;
    }


    struct sockaddr_in destAddress;
    destAddress.sin_family = AF_INET;
    destAddress.sin_port = htons(global::peerServerPort);
    destAddress.sin_addr.s_addr = htonl(planet.ip);
    int error = ::connect(sockfd, (struct sockaddr *)&destAddress,
                          sizeof(destAddress));
    if (error == -1)
    {
      logWrite(EXCEPTION, "Cannot connect to peer: %s", strerror(errno));
      close(sockfd);
      return;
    }

    if (maxSegmentSize != 0 && !changeSocket(sockfd, IPPROTO_TCP,
                                             TCP_MAXSEG, maxSegmentSize,
                                             "TCP_MAXSEG"))
    {
      close(sockfd);
      return;
    }


    int flags = fcntl(sockfd, F_GETFL);
    if (flags == -1)
    {
      logWrite(EXCEPTION, "Cannot get fcntl flags from a peer socket: %s",
               strerror(errno));
      close(sockfd);
      return;
    }

    error = fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
131
    if (error == -1)
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    {
      logWrite(EXCEPTION, "Cannot set fcntl flags (nonblocking) "
               "on a peer socket: %s", strerror(errno));
      close(sockfd);
      return;
    }

    struct sockaddr_in sourceAddress;
    socklen_t len = sizeof(sourceAddress);
    error = getsockname(sockfd, (struct sockaddr *)&sourceAddress,
                        &len);
    if (error == -1)
    {
      logWrite(EXCEPTION, "Cannot find the source address for a peer: %s");
      close(sockfd);
      return;
    }
    planet.localPort = ntohs(sourceAddress.sin_port);

151 152
    logWrite(CONNECTION_MODEL, "Connected to peer at %s:%d",
             ipToString(htonl(planet.ip)).c_str(), global::peerServerPort);
153 154 155 156 157 158 159
    peersock = sockfd;
    state = CONNECTED;
  }
}

void KernelTcp::addParam(ConnectionModelCommand const & param)
{
160 161 162 163 164 165
  if (state == CONNECTED)
  {
    logWrite(ERROR, "A ConnectionModelCommand was received after connection. "
             "It will not be applied unless the connection dies and is "
             "re-established.");
  }
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  switch (param.type)
  {
  case CONNECTION_SEND_BUFFER_SIZE:
    sendBufferSize = param.value;
    break;
  case CONNECTION_RECEIVE_BUFFER_SIZE:
    receiveBufferSize = param.value;
    break;
  case CONNECTION_MAX_SEGMENT_SIZE:
    maxSegmentSize = param.value;
    break;
  case CONNECTION_USE_NAGLES:
    useNagles = param.value;
    break;
  default:
    logWrite(ERROR, "Invalid ConnectionModelCommand type: %d", param.type);
  }
}

185 186 187
// MAX_WRITESIZE is in chars, and must be a multiple of 4
const int KernelTcp::MAX_WRITESIZE = 8192;

188 189 190 191
int KernelTcp::writeMessage(int size, WriteResult & result)
{
  if (state == DISCONNECTED)
  {
192 193
    logWrite(CONNECTION_MODEL,
             "writeMessage() called while disconnected from peer.");
194 195 196 197
    connect(result.planet);
  }
  if (state == CONNECTED)
  {
198 199 200 201 202 203 204 205 206 207 208
    /*
     * Create a different random write each time.
     * We do this in terms of full words rather than chars because this is a
     * performance-critical piece of code.
     * XXX: What I really want here is a compile-time assert, not a runtime
     * assert...
     */
    assert(MAX_WRITESIZE % 4 == 0);
    uint32_t buffer[MAX_WRITESIZE / 4];
    int bufferwords = min(MAX_WRITESIZE / 4, size / 4);
    for (int i = 0; i < bufferwords; ++i)
209
    {
210
      buffer[i] = random();
211
    }
212 213 214 215 216 217 218 219

    /*
     * We only have MAX_WRITESIZE bytes of random data - therefore, we may have
     * to do more than one write if they asked for a bigger write than
     * MAX_WRITESIZE
     */
    int bytesToWrite;
    int bytesWritten = 0;
220
    result.bufferFull = false;
221
    for (bytesToWrite = size; bytesToWrite > 0; bytesToWrite -= MAX_WRITESIZE) {
222
      int writeSize = min(MAX_WRITESIZE,bytesToWrite);
223
      // Actually write the darn thing.
224
      logWrite(CONNECTION_MODEL, "About to write %d bytes", writeSize);
225
      int error = send(peersock, &buffer[0], writeSize, 0);
226 227
      logWrite(CONNECTION_MODEL,
               "Tried to write %d bytes, actually wrote %d", writeSize, error);
228 229 230 231 232 233 234 235 236 237 238

      if (error == 0)
      {
        close(peersock);
        peersock = -1;
        state = DISCONNECTED;
        result.bufferFull = false;
        result.isConnected = false;
        return 0;
      }
      else if (error == -1)
239
      {
240 241 242 243
        if (errno == EWOULDBLOCK)
        {
          logWrite(CONNECTION_MODEL,"Buffer is full");
          result.bufferFull = true;
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

          Time currentTime = getCurrentTime();
          uint32_t timeTotal = (currentTime - debugPrevTime).toMilliseconds();
          if (debugByteCount > 0 && timeTotal > 0)
          {
            logWrite(CONNECTION_MODEL,
                     "Load estimate: %d kbps, %d kilobits, %d millis",
                     TSThroughputSensor::getThroughputInKbps(timeTotal,
                                                             debugByteCount),
                     debugByteCount, timeTotal);
            debugPrevTime = currentTime;
            debugByteCount = 0;
          }

          // XXX This doesn't make sense. We know that error is -1.
259
          // No point in trying more writes
260
          return bytesWritten + error;
261 262 263 264 265 266
        }
        else
        {
          logWrite(EXCEPTION, "Failed write to peer: %s", strerror(errno));
        }
        return -1;
267 268
      }
      else
269
      {
270
        debugByteCount += error;
271
        // Write succeeded, all bytes got written
272
        // XXX Shouldn't this be error?
273
        bytesWritten += bytesToWrite;
274
      }
275
    }
276 277 278 279 280 281 282 283

    // Return the total number of bytes written
    return bytesWritten;

  } else {
    result.bufferFull = false;
    result.isConnected = false;
    return -1;
284 285 286 287 288 289 290
  }
}
bool KernelTcp::isConnected(void)
{
  return state == CONNECTED;
}

291 292 293 294 295
int KernelTcp::getSock(void) const
{
  return peersock;
}

296 297 298
enum { SNIFF_WAIT = 10 };

void KernelTcp::init(void)
299 300
{
  // Set up the peerAccept socket
301 302
  if (global::peerServerPort != 0) {
    global::peerAccept = createServer(global::peerServerPort,
303 304
                                      "Peer accept socket (No incoming peer "
                                      "connections will be accepted)");
305
    logWrite(PEER_CYCLE, "Created peer server on port %d",
306
             global::peerServerPort);
307
  }
308

309
  // Set up the connectionModelExemplar
310 311
  global::connectionModelExemplar.reset(new KernelTcp());

312
  if (global::replayArg != REPLAY_LOAD) {
313 314 315 316 317 318
    // Set up packet capture
    char errbuf[PCAP_ERRBUF_SIZE];
    struct bpf_program fp;      /* hold compiled program     */
    bpf_u_int32 maskp;          /* subnet mask               */
    bpf_u_int32 netp;           /* ip                        */
    ostringstream filter;
319

320 321 322
    /* ask pcap for the network address and mask of the device */
    pcap_lookupnet(global::interface.c_str(), &netp, &maskp, errbuf);
    filter << "port " << global::peerServerPort << " and tcp";
323

324 325 326 327 328 329 330 331 332 333 334 335
    /* open device for reading.
     * NOTE: We use non-promiscuous */
    pcapDescriptor = pcap_open_live(global::interface.c_str(), BUFSIZ, 0,
                                    SNIFF_WAIT, errbuf);
    if(pcapDescriptor == NULL)
    {
      logWrite(ERROR, "pcap_open_live() failed: %s", errbuf);
    }
    // Lets try and compile the program, optimized
    else if(pcap_compile(pcapDescriptor, &fp,
                         const_cast<char *>(filter.str().c_str()),
                         1, maskp) == -1)
336
    {
337 338 339 340 341 342 343
      logWrite(ERROR, "pcap_compile() failed: %s", pcap_geterr(pcapDescriptor));
      pcap_close(pcapDescriptor);
    }
    // set the compiled program as the filter
    else if(pcap_setfilter(pcapDescriptor,&fp) == -1)
    {
      logWrite(ERROR, "pcap_filter() failed: %s", pcap_geterr(pcapDescriptor));
344
      pcap_close(pcapDescriptor);
345 346 347
    }
    else
    {
348 349 350 351 352 353 354 355 356 357 358
      pcapfd = pcap_get_selectable_fd(pcapDescriptor);
      if (pcapfd == -1)
      {
        logWrite(ERROR, "Failed to get a selectable file descriptor "
                 "for pcap: %s", pcap_geterr(pcapDescriptor));
        pcap_close(pcapDescriptor);
      }
      else
      {
        setDescriptor(pcapfd);
      }
359 360
    }
  }
361 362
}

363
void KernelTcp::addNewPeer(fd_set * readable)
364 365 366 367 368
{
  if (global::peerAccept != -1
      && FD_ISSET(global::peerAccept, readable))
  {
    struct sockaddr_in remoteAddress;
369 370 371
    int fd = acceptServer(global::peerAccept, &remoteAddress,
                          "Peer socket (Incoming peer connection was not "
                          "accepted)");
372 373
    if (fd != -1)
    {
374 375 376 377 378 379
      global::peers.push_back(make_pair(fd, ipToString(
        remoteAddress.sin_addr.s_addr)));
      logWrite(PEER_CYCLE,
               "Peer connection %d from %s was accepted normally.",
               global::peers.back().first,
               global::peers.back().second.c_str());
380 381 382 383
    }
  }
}

384
void KernelTcp::readFromPeers(fd_set * readable)
385
{
386 387
  list< pair<int, string> >::iterator pos = global::peers.begin();
  while (pos != global::peers.end())
388
  {
389
    if (pos->first != -1 && FD_ISSET(pos->first, readable))
390 391 392 393 394 395 396 397
    {
      static const int bufferSize = 8096;
      static char buffer[bufferSize];
      int size = read(pos->first, buffer, bufferSize);
      if (size == 0)
      {
        logWrite(PEER_CYCLE,
                 "Peer connection %d from %s is closing normally.",
398
                 pos->first, pos->second.c_str());
399
        close(pos->first);
400
        clearDescriptor(pos->first);
401
        list< pair<int, string> >::iterator temp = pos;
402 403 404 405 406 407 408
        ++pos;
        global::peers.erase(temp);
      }
      else if (size == -1 && errno != EAGAIN && errno != EINTR)
      {
        logWrite(EXCEPTION,
                 "Failed to read peer connection %d from %s so "
409
                 "I'm shutting it down: %s", pos->first, pos->second.c_str(),
410 411
                 strerror(errno));
        close(pos->first);
412
        list< pair<int, string> >::iterator temp = pos;
413 414 415 416 417 418 419 420 421 422 423 424 425 426
        ++pos;
        global::peers.erase(temp);
      }
      else
      {
        ++pos;
      }
    }
    else
    {
      ++pos;
    }
  }
}
427

428 429 430
void KernelTcp::packetCapture(fd_set * readable)
{
  unsigned char * args = NULL;
431
  if (pcapfd != -1 && FD_ISSET(pcapfd, readable))
432
  {
433
    pcap_dispatch(pcapDescriptor, 1, kernelTcpCallback, args);
434 435 436
  }
}

437
namespace
438
{
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
  bool changeSocket(int sockfd, int level, int optname, int value,
                    string optstring)
  {
    int error = setsockopt(sockfd, SOL_SOCKET, optname, &value, sizeof(value));
    if (error == -1)
    {
      logWrite(ERROR, "Cannot set socket option %s", optstring.c_str());
      return false;
    }
    int newValue = 0;
    socklen_t newValueLength = sizeof(newValue);
    error = getsockopt(sockfd, level, optname, &newValue,
                       &newValueLength);
    if (error == -1)
    {
      logWrite(ERROR, "Cannot read back socket option %s", optstring.c_str());
455
      return false;
456 457 458 459 460 461 462 463 464
    }
    logWrite(CONNECTION_MODEL, "Socket option %s is now %d", optstring.c_str(),
             newValue);
    return true;
  }

  void kernelTcpCallback(unsigned char *,
                         struct pcap_pkthdr const * pcapInfo,
                         unsigned char const * packet)
465
  {
466
    logWrite(PCAP, "Captured a packet");
467 468 469 470 471 472 473 474 475 476 477
    int packetType = getLinkLayer(pcapInfo, packet);
    if (packetType == -1)
    {
      // Error message already printed in getLinkLayer();
      return;
    }
    if (packetType != ETHERTYPE_IP)
    {
      logWrite(ERROR, "Unknown link layer type: %d", packetType);
      return;
    }
478
    struct ip const * ipPacket;
479
    struct tcphdr const * tcpPacket;
480
    size_t bytesRemaining = pcapInfo->caplen - sizeof(struct ether_header);
481

482
    ipPacket = reinterpret_cast<struct ip const *>
483
      (packet + sizeof(struct ether_header));
484
    if (bytesRemaining < sizeof(struct ip))
485 486 487
    {
      logWrite(ERROR, "A captured packet was too short to contain an "
               "IP header");
488
      return;
489
    }
490 491
    // ipHeaderLength and version are in a one byte field so
    // endian-ness doesn't matter.
492 493
    int ipHeaderLength = ipPacket->ip_hl;
    int version = ipPacket->ip_v;
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    if (version != 4)
    {
      logWrite(ERROR, "A non IPv4 packet was captured");
      return;
    }
    if (ipHeaderLength < 5)
    {
      logWrite(ERROR, "Bad IP header length: %d", ipHeaderLength);
      return;
    }
    if (ipPacket->ip_p != IPPROTO_TCP)
    {
      logWrite(ERROR, "A non TCP packet was captured");
      return;
    }
509 510 511 512 513 514 515

    list<Option> ipOptions;
    unsigned char const * optionsBegin = packet + sizeof(struct ether_header)
      + sizeof(struct ip);
    int optionsSize = ipHeaderLength*4 - sizeof(struct ip);
    parseOptions(optionsBegin, optionsSize, &ipOptions);

516 517
    // ipHeaderLength is multiplied by 4 because it is a
    // length in 4-byte words.
518 519 520
    unsigned char const * tcpPacketStart = packet + sizeof(struct ether_header)
      + ipHeaderLength*4;
    tcpPacket = reinterpret_cast<struct tcphdr const *>(tcpPacketStart);
521 522 523 524 525 526 527
    bytesRemaining -= ipHeaderLength*4;
    if (bytesRemaining < sizeof(struct tcphdr))
    {
      logWrite(ERROR, "A captured packet was to short to contain "
               "a TCP header");
      return;
    }
528
    handleTcp(pcapInfo, ipPacket, tcpPacket, tcpPacketStart, ipOptions);
529 530
  }

531 532 533
  int getLinkLayer(struct pcap_pkthdr const * pcapInfo,
                   unsigned char const * packet)
  {
534 535
    unsigned int caplen = pcapInfo->caplen;

536
    if (caplen < sizeof(struct ether_header))
537 538 539 540 541 542 543 544 545 546 547
    {
      logWrite(ERROR, "A captured packet was too short to contain "
               "an ethernet header");
      return -1;
    }
    else
    {
      struct ether_header * etherPacket = (struct ether_header *) packet;
      return ntohs(etherPacket->ether_type);
    }
  }
548 549

  void handleTcp(struct pcap_pkthdr const * pcapInfo,
550
                 struct ip const * ipPacket,
551 552 553
                 struct tcphdr const * tcpPacket,
                 unsigned char const * tcpPacketStart,
                 list<Option> & ipOptions)
554
  {
555
    logWrite(PCAP, "Captured a TCP packet");
556
    struct tcp_info kernelInfo;
557 558 559 560 561 562 563

    list<Option> tcpOptions;
    unsigned char const * tcpOptionsBegin = tcpPacketStart
      + sizeof(struct tcphdr);
    int tcpOptionsSize = tcpPacket->doff*4 - sizeof(struct tcphdr);
    parseOptions(tcpOptionsBegin, tcpOptionsSize, &tcpOptions);

564 565 566 567 568
    PacketInfo packet;
    packet.packetTime = Time(pcapInfo->ts);
    packet.packetLength = pcapInfo->len;
    packet.kernel = &kernelInfo;
    packet.ip = ipPacket;
569
    packet.ipOptions = &ipOptions;
570
    packet.tcp = tcpPacket;
571
    packet.tcpOptions = &tcpOptions;
572

573 574 575 576 577 578 579
    /*
     * Classify this packet as outgoing or incoming, by trying to look it up
     * with the the local and remote ports in the same order as they appear in
     * the packet, and reversed.
     * NOTE: We put the destination IP address in the planetMap, so we
     * reverse the sense of ip_dst and ip_src
     */
580
    Order key;
581
    key.transport = TCP_CONNECTION;
582 583 584
    key.ip = ntohl(ipPacket->ip_dst.s_addr);
    key.localPort = ntohs(tcpPacket->source);
    key.remotePort = ntohs(tcpPacket->dest);
585

586 587 588 589
    bool outgoing;

    logWrite(PCAP,"Looking up key (outgoing): i=%s,lp=%i,rp=%i",
        inet_ntoa(ipPacket->ip_dst),key.localPort,key.remotePort);
590
    map<Order, Connection *>::iterator pos;
591
    pos = global::planetMap.find(key);
592 593 594 595

    if (pos != global::planetMap.end()) {
      outgoing = true;
    } else {
596 597 598
      key.ip = ntohl(ipPacket->ip_src.s_addr);
      key.localPort = ntohs(tcpPacket->dest);
      key.remotePort = ntohs(tcpPacket->source);
599 600
      logWrite(PCAP,"Looking up key (incoming): i=%s,lp=%i,rp=%i",
          inet_ntoa(ipPacket->ip_src),key.localPort,key.remotePort);
601
      pos = global::planetMap.find(key);
602 603 604
      if (pos != global::planetMap.end()) {
        outgoing = false;
      } else {
605
        logWrite(ERROR,"Unable to find packet in planetMap");
606 607 608 609
        return;
      }
    }

610 611 612 613 614 615
    if (pos->second == NULL)
    {
      logWrite(EXCEPTION, "Packet captured after the end of a connection.");
      return;
    }

616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
    /*
     * Next, determine if this packet is an ACK (note that it can also be a
     * data packet, even if it's an ACK. This is called piggybacking)
     */
    bool isAck = (tcpPacket->ack & 0x0001);

    /*
     * Finally, figure out if this packet contains any data
     */
    bool hasData;
    uint32_t totalHeaderLength = ipPacket->ip_hl * 4 + tcpPacket->doff * 4;
    uint32_t totalIPLen = ntohs(ipPacket->ip_len);
    if (totalHeaderLength == totalIPLen) {
      hasData = false;
    } else {
      if (totalHeaderLength < totalIPLen) {
        hasData = true;
      } else {
        logWrite(ERROR,"Internal error in packet data size computation: hl=%i, il=%i",
            totalHeaderLength, totalIPLen);
      }
    }

    /*
     * Now that we've classified this packet, do something about it
     */
    logWrite(PCAP,"Packet classified: outgoing=%i, isAck=%i, hasData=%i",
        outgoing, isAck, hasData);
    if (!handleKernel(pos->second, &kernelInfo)) {
      logWrite(ERROR,"handleKernel() failed");
      return;
    }

649 650 651 652
    // We want to distinguish between packets that are outgoing and
    // packets that are incoming. All other separation can be done
    // inside the sensors themselves. We call these 'Send' and 'Ack'
    // packets because my thinking was originally muddied about this.
653 654 655 656
    if (outgoing) {
      /*
       * Outgoing packets
       */
657 658
      packet.packetType = PACKET_INFO_SEND_COMMAND;
      pos->second->capturePacket(&packet);
659 660 661 662
    } else {
      /*
       * Incoming packets
       */
663 664
      packet.packetType = PACKET_INFO_ACK_COMMAND;
      pos->second->capturePacket(&packet);
665 666 667
    }
  }

668
  bool handleKernel(Connection * conn, struct tcp_info * kernel)
669
  {
670
    bool result = true;
671 672 673 674 675 676 677
    // This is a filthy filthy hack. Basically, I need the fd in order
    // to introspect the kernel for it. But I don't want that part of
    // the main interface because we don't even know that a random
    // connection model *has* a unique fd.
    ConnectionModel const * genericModel = conn->getConnectionModel();
    KernelTcp const * model = dynamic_cast<KernelTcp const *>(genericModel);
    if (model != NULL)
678
    {
679 680 681 682 683 684 685 686
      socklen_t infoSize = sizeof(tcp_info);
      int error = 0;
      error = getsockopt(model->getSock(), SOL_TCP, TCP_INFO, kernel,
                         &infoSize);
      if (error == -1)
      {
        logWrite(ERROR, "Failed to get the kernel TCP info: %s",
                 strerror(errno));
687
        result = false;
688 689 690 691 692 693 694 695
      }
    }
    else
    {
      logWrite(ERROR, "handleKernel() called for KernelTcp, but the "
               "ConnectionModel on the actual connection wasn't of type "
               "KernelTcp. This inconsistency will lead to "
               "undefined/uninitialized behaviour");
696 697 698 699 700 701 702 703
      result = false;
    }
  return result;
  }

  void parseOptions(unsigned char const * buffer, int size,
                    list<Option> * options)
  {
704 705
//    logWrite(PCAP, "Parsing options");
    unsigned char const * pos = buffer;
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
    unsigned char const * limit = buffer + size;
    Option current;
    bool done = false;
    while (pos < limit && !done)
    {
      current.type = *pos;
      ++pos;
      if (current.type == 0)
      {
        // This is the ending marker. We're done here.
        current.length = 0;
        current.buffer = NULL;
        options->push_back(current);
        done = true;
      }
      else if (current.type == 1)
      {
        // This is the padding no-op marker. There is no length field.
        current.length = 0;
        current.buffer = NULL;
        options->push_back(current);
      }
      else
      {
        // This is some other code. There is a length field and length-2
        // other bytes.
        current.length = *pos - 2;
        ++pos;

        if (current.length > 0)
        {
          current.buffer = pos;
          pos += current.length;
        }
        else
        {
          current.buffer = NULL;
        }
        options->push_back(current);
      }
746
    }
747
//    logWrite(PCAP, "Finished parsing options");
748
  }
749
}