KernelTcp.cc 17 KB
Newer Older
1 2 3
// KernelTcp.cc

#include "lib.h"
4
#include "log.h"
5
#include "KernelTcp.h"
6
#include "Command.h"
7

8 9
using namespace std;

10 11 12 13 14 15 16 17 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,
                 IpHeader const * ipPacket,
                 struct tcphdr const * tcpPacket);
  void handleKernel(Connection * conn, struct tcp_info * kernel);
}

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

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
KernelTcp::KernelTcp()
  : state(DISCONNECTED)
  , peersock(-1)
  , sendBufferSize(0)
  , receiveBufferSize(0)
  , maxSegmentSize(0)
  , useNagles(1)
{
}

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

auto_ptr<ConnectionModel> KernelTcp::clone(void)
{
  auto_ptr<KernelTcp> result(new KernelTcp());
49 50 51 52 53 54 55
  result->sendBufferSize = sendBufferSize;
  result->receiveBufferSize = receiveBufferSize;
  result->maxSegmentSize = maxSegmentSize;
  result->useNagles = useNagles;
  result->state = state;
  auto_ptr<ConnectionModel> modelResult(result.release());
  return modelResult;
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
}

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,
71
                                              sendBufferSize, "SO_SNDBUF"))
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        || (receiveBufferSize != 0 && !changeSocket(sockfd, SOL_SOCKET,
                                                    SO_RCVBUF,
                                                    receiveBufferSize,
                                                    "SO_RCVBUF"))
        || !changeSocket(sockfd, IPPROTO_TCP, TCP_NODELAY, !useNagles,
                         "TCP_NODELAY"))
    {
      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);
117
    if (error == -1)
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    {
      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);

    peersock = sockfd;
    state = CONNECTED;
  }
}

void KernelTcp::addParam(ConnectionModelCommand const & param)
{
144 145 146 147 148 149
  if (state == CONNECTED)
  {
    logWrite(ERROR, "A ConnectionModelCommand was received after connection. "
             "It will not be applied unless the connection dies and is "
             "re-established.");
  }
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  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);
  }
}

int KernelTcp::writeMessage(int size, WriteResult & result)
{
  if (state == DISCONNECTED)
  {
    connect(result.planet);
  }
  if (state == CONNECTED)
  {
    // Create a different random write each time.
    vector<char> buffer;
    buffer.resize(size);
    size_t i = 0;
    for (i = 0; i < buffer.size(); ++i)
    {
      buffer[i] = static_cast<char>(random() & 0xff);
    }
    // Actually write the darn thing.
    int error = send(peersock, & buffer[0], buffer.size(), 0);
    if (error == 0)
    {
      close(peersock);
      peersock = -1;
      state = DISCONNECTED;
192
      result.bufferFull = false;
193 194 195 196 197 198 199 200 201 202 203 204 205
      result.isConnected = false;
      return 0;
    }
    else if (error == -1)
    {
      logWrite(EXCEPTION, "Failed write to peer: %s", strerror(errno));
      return -1;
    }
    else
    {
      return error;
    }
  }
206
  result.bufferFull = false;
207 208 209 210 211 212 213 214 215
  result.isConnected = false;
  return -1;
}

bool KernelTcp::isConnected(void)
{
  return state == CONNECTED;
}

216 217 218 219 220
int KernelTcp::getSock(void) const
{
  return peersock;
}

221 222 223
enum { SNIFF_WAIT = 10 };

void KernelTcp::init(void)
224 225 226
{
  int error = 0;
  // Set up the peerAccept socket
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd == -1)
  {
    logWrite(ERROR, "Unable to generate a peer accept socket. "
             "No incoming peer connections will ever be accepted: %s",
             strerror(errno));
  }
  else
  {
    struct sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_port = htons(global::peerServerPort);
    address.sin_addr.s_addr = INADDR_ANY;
    error = bind(sockfd, reinterpret_cast<struct sockaddr *>(&address),
                 sizeof(struct sockaddr));
    if (error == -1)
    {
      logWrite(ERROR, "Unable to bind peer accept socket. "
245
               "No incoming peer connections will ever be accepted: %s",
246 247 248 249 250 251 252 253 254 255
               strerror(errno));
      close(sockfd);
    }
    else
    {
      setDescriptor(sockfd);
      global::peerAccept = sockfd;
    }
  }

256
  // Set up the connectionModelExemplar
257 258
  global::connectionModelExemplar.reset(new KernelTcp());

259
  // Set up packet capture
260
  char errbuf[PCAP_ERRBUF_SIZE];
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  struct bpf_program fp;      /* hold compiled program     */
  bpf_u_int32 maskp;          /* subnet mask               */
  bpf_u_int32 netp;           /* ip                        */
  ostringstream filter;

  /* 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";

  /* 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
279 280 281
  else if(pcap_compile(pcapDescriptor, &fp,
                       const_cast<char *>(filter.str().c_str()),
                       1, maskp) == -1)
282
  {
283 284
    logWrite(ERROR, "pcap_compile() failed: %s", pcap_geterr(pcapDescriptor));
    pcap_close(pcapDescriptor);
285 286 287 288
  }
  // set the compiled program as the filter
  else if(pcap_setfilter(pcapDescriptor,&fp) == -1)
  {
289 290
    logWrite(ERROR, "pcap_filter() failed: %s", pcap_geterr(pcapDescriptor));
    pcap_close(pcapDescriptor);
291 292 293 294 295 296
  }
  else
  {
    pcapfd = pcap_get_selectable_fd(pcapDescriptor);
    if (pcapfd == -1)
    {
297 298 299
      logWrite(ERROR, "Failed to get a selectable file descriptor "
               "for pcap: %s", pcap_geterr(pcapDescriptor));
      pcap_close(pcapDescriptor);
300 301 302 303 304 305
    }
    else
    {
      setDescriptor(pcapfd);
    }
  }
306 307
}

308
void KernelTcp::addNewPeer(fd_set * readable)
309 310 311 312 313 314
{
  if (global::peerAccept != -1
      && FD_ISSET(global::peerAccept, readable))
  {
    struct sockaddr_in remoteAddress;
    socklen_t addressSize = sizeof(remoteAddress);
315 316 317
    int fd = accept(global::peerAccept,
                    reinterpret_cast<struct sockaddr *>(&remoteAddress),
                    &addressSize);
318 319 320
    if (fd != -1)
    {
      // Add the peer.
321
      int flags = fcntl(fd, F_GETFL);
322 323
      if (flags != -1)
      {
324
        int error = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
325 326 327 328
        if (error != -1)
        {
          global::peers.push_back(
            make_pair(fd, ipToString(remoteAddress.sin_addr.s_addr)));
329
          setDescriptor(fd);
330 331
          logWrite(PEER_CYCLE,
                   "Peer connection %d from %s was accepted normally.",
332 333
                   global::peers.back().first,
                   global::peers.back().second.c_str());
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        }
        else
        {
          logWrite(EXCEPTION, "fctl(F_SETFL) failed: %s", strerror(errno));
          close(fd);
        }
      }
      else
      {
        logWrite(EXCEPTION, "fctl(F_GETFL) failed: %s", strerror(errno));
        close(fd);
      }
    }
    else
    {
      logWrite(EXCEPTION, "accept() called on a peer connection failed: %s",
               strerror(errno));
    }
  }
}

355
void KernelTcp::readFromPeers(fd_set * readable)
356
{
357 358
  list< pair<int, string> >::iterator pos = global::peers.begin();
  while (pos != global::peers.end())
359 360 361 362 363 364 365 366 367 368
  {
    if (FD_ISSET(pos->first, readable))
    {
      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.",
369
                 pos->first, pos->second.c_str());
370
        close(pos->first);
371
        list< pair<int, string> >::iterator temp = pos;
372 373 374 375 376 377 378
        ++pos;
        global::peers.erase(temp);
      }
      else if (size == -1 && errno != EAGAIN && errno != EINTR)
      {
        logWrite(EXCEPTION,
                 "Failed to read peer connection %d from %s so "
379
                 "I'm shutting it down: %s", pos->first, pos->second.c_str(),
380 381
                 strerror(errno));
        close(pos->first);
382
        list< pair<int, string> >::iterator temp = pos;
383 384 385 386 387 388 389 390 391 392 393 394 395 396
        ++pos;
        global::peers.erase(temp);
      }
      else
      {
        ++pos;
      }
    }
    else
    {
      ++pos;
    }
  }
}
397

398 399 400 401 402
void KernelTcp::packetCapture(fd_set * readable)
{
  unsigned char * args = NULL;
  if (FD_ISSET(pcapfd, readable))
  {
403
    pcap_dispatch(pcapDescriptor, -1, kernelTcpCallback, args);
404 405 406
  }
}

407
namespace
408
{
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  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());
    return false;
    }
    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)
435
  {
436 437 438 439 440 441 442 443 444 445 446
    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;
    }
447 448
    IpHeader const * ipPacket;
    struct tcphdr const * tcpPacket;
449
    size_t bytesRemaining = pcapInfo->caplen - sizeof(struct ether_header);
450 451 452

    ipPacket = reinterpret_cast<IpHeader const *>
      (packet + sizeof(struct ether_header));
453
    if (bytesRemaining < sizeof(IpHeader))
454 455 456
    {
      logWrite(ERROR, "A captured packet was too short to contain an "
               "IP header");
457
      return;
458
    }
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
    // ipHeaderLength and version are in a one byte field so
    // endian-ness doesn't matter.
    int ipHeaderLength = IP_HL(ipPacket);
    int version = IP_V(ipPacket);
    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;
    }
    // ipHeaderLength is multiplied by 4 because it is a
    // length in 4-byte words.
    tcpPacket = reinterpret_cast<struct tcphdr const *>
      (packet + sizeof(struct ether_header)
       + ipHeaderLength*4);
    bytesRemaining -= ipHeaderLength*4;
    if (bytesRemaining < sizeof(struct tcphdr))
    {
      logWrite(ERROR, "A captured packet was to short to contain "
               "a TCP header");
      return;
    }
    handleTcp(pcapInfo, ipPacket, tcpPacket);
491 492
  }

493 494 495
  int getLinkLayer(struct pcap_pkthdr const * pcapInfo,
                   unsigned char const * packet)
  {
496 497
    unsigned int caplen = pcapInfo->caplen;

498
    if (caplen < sizeof(struct ether_header))
499 500 501 502 503 504 505 506 507 508 509
    {
      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);
    }
  }
510 511 512 513

  void handleTcp(struct pcap_pkthdr const * pcapInfo,
                 IpHeader const * ipPacket,
                 struct tcphdr const * tcpPacket)
514
  {
515 516 517
    struct tcp_info kernelInfo;
    bool isAck;
    if (tcpPacket->ack & 0x0001)
518
    {
519
      isAck = true;
520
    }
521 522 523 524 525 526 527 528 529 530 531 532 533
    else
    {
      isAck = false;
    }
    PacketInfo packet;
    packet.packetTime = Time(pcapInfo->ts);
    packet.packetLength = pcapInfo->len;
    packet.kernel = &kernelInfo;
    packet.ip = ipPacket;
    packet.tcp = tcpPacket;

    Order key;
    // Assume that this is an outgoing packet.
534
    key.transport = TCP_CONNECTION;
535 536 537
    key.ip = ntohl(ipPacket->ip_dst.s_addr);
    key.localPort = ntohs(tcpPacket->source);
    key.remotePort = ntohs(tcpPacket->dest);
538

539
    map<Order, Connection *>::iterator pos;
540 541 542
    pos = global::planetMap.find(key);
    if (pos != global::planetMap.end())
    {
543 544
      // This is an outgoing packet.
      if (!isAck)
545
      {
546
        // We only care about sent packets, not acked packets.
547
        handleKernel(pos->second, &kernelInfo);
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
        pos->second->captureSend(&packet);
      }
    }
    else
    {
      // Assume that this is an incoming packet.
      key.transport = TCP_CONNECTION;
      key.ip = ntohl(ipPacket->ip_src.s_addr);
      key.localPort = ntohs(tcpPacket->dest);
      key.remotePort = ntohs(tcpPacket->source);

      pos = global::planetMap.find(key);
      if (pos != global::planetMap.end())
      {
        // This is an incoming packet.
        if (isAck)
        {
          // We only care about ack packets, not sent packets.
          handleKernel(pos->second, &kernelInfo);
          pos->second->captureAck(&packet);
        }
569 570 571 572
      }
    }
  }

573
  void handleKernel(Connection * conn, struct tcp_info * kernel)
574
  {
575 576 577 578 579 580 581
    // 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)
582
    {
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
      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));
      }
    }
    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");
599 600
    }
  }
601
}