KernelTcp.cc 15.7 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
{
  // Set up the peerAccept socket
226 227 228
  global::peerAccept = createServer(global::peerServerPort,
                                    "Peer accept socket (No incoming peer "
                                    "connections will be accepted)");
229

230
  // Set up the connectionModelExemplar
231 232
  global::connectionModelExemplar.reset(new KernelTcp());

233
  // Set up packet capture
234
  char errbuf[PCAP_ERRBUF_SIZE];
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  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
253 254 255
  else if(pcap_compile(pcapDescriptor, &fp,
                       const_cast<char *>(filter.str().c_str()),
                       1, maskp) == -1)
256
  {
257 258
    logWrite(ERROR, "pcap_compile() failed: %s", pcap_geterr(pcapDescriptor));
    pcap_close(pcapDescriptor);
259 260 261 262
  }
  // set the compiled program as the filter
  else if(pcap_setfilter(pcapDescriptor,&fp) == -1)
  {
263 264
    logWrite(ERROR, "pcap_filter() failed: %s", pcap_geterr(pcapDescriptor));
    pcap_close(pcapDescriptor);
265 266 267 268 269 270
  }
  else
  {
    pcapfd = pcap_get_selectable_fd(pcapDescriptor);
    if (pcapfd == -1)
    {
271 272 273
      logWrite(ERROR, "Failed to get a selectable file descriptor "
               "for pcap: %s", pcap_geterr(pcapDescriptor));
      pcap_close(pcapDescriptor);
274 275 276 277 278 279
    }
    else
    {
      setDescriptor(pcapfd);
    }
  }
280 281
}

282
void KernelTcp::addNewPeer(fd_set * readable)
283 284 285 286 287
{
  if (global::peerAccept != -1
      && FD_ISSET(global::peerAccept, readable))
  {
    struct sockaddr_in remoteAddress;
288 289 290
    int fd = acceptServer(global::peerAccept, &remoteAddress,
                          "Peer socket (Incoming peer connection was not "
                          "accepted)");
291 292
    if (fd != -1)
    {
293 294 295 296 297 298
      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());
299 300 301 302
    }
  }
}

303
void KernelTcp::readFromPeers(fd_set * readable)
304
{
305 306
  list< pair<int, string> >::iterator pos = global::peers.begin();
  while (pos != global::peers.end())
307
  {
308
    if (pos->first != -1 && FD_ISSET(pos->first, readable))
309 310 311 312 313 314 315 316
    {
      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.",
317
                 pos->first, pos->second.c_str());
318
        close(pos->first);
319
        list< pair<int, string> >::iterator temp = pos;
320 321 322 323 324 325 326
        ++pos;
        global::peers.erase(temp);
      }
      else if (size == -1 && errno != EAGAIN && errno != EINTR)
      {
        logWrite(EXCEPTION,
                 "Failed to read peer connection %d from %s so "
327
                 "I'm shutting it down: %s", pos->first, pos->second.c_str(),
328 329
                 strerror(errno));
        close(pos->first);
330
        list< pair<int, string> >::iterator temp = pos;
331 332 333 334 335 336 337 338 339 340 341 342 343 344
        ++pos;
        global::peers.erase(temp);
      }
      else
      {
        ++pos;
      }
    }
    else
    {
      ++pos;
    }
  }
}
345

346 347 348
void KernelTcp::packetCapture(fd_set * readable)
{
  unsigned char * args = NULL;
349
  if (pcapfd != -1 && FD_ISSET(pcapfd, readable))
350
  {
351
    pcap_dispatch(pcapDescriptor, -1, kernelTcpCallback, args);
352 353 354
  }
}

355
namespace
356
{
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
  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)
383
  {
384 385 386 387 388 389 390 391 392 393 394
    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;
    }
395 396
    IpHeader const * ipPacket;
    struct tcphdr const * tcpPacket;
397
    size_t bytesRemaining = pcapInfo->caplen - sizeof(struct ether_header);
398 399 400

    ipPacket = reinterpret_cast<IpHeader const *>
      (packet + sizeof(struct ether_header));
401
    if (bytesRemaining < sizeof(IpHeader))
402 403 404
    {
      logWrite(ERROR, "A captured packet was too short to contain an "
               "IP header");
405
      return;
406
    }
407 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 435 436 437 438
    // 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);
439 440
  }

441 442 443
  int getLinkLayer(struct pcap_pkthdr const * pcapInfo,
                   unsigned char const * packet)
  {
444 445
    unsigned int caplen = pcapInfo->caplen;

446
    if (caplen < sizeof(struct ether_header))
447 448 449 450 451 452 453 454 455 456 457
    {
      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);
    }
  }
458 459 460 461

  void handleTcp(struct pcap_pkthdr const * pcapInfo,
                 IpHeader const * ipPacket,
                 struct tcphdr const * tcpPacket)
462
  {
463 464 465
    struct tcp_info kernelInfo;
    bool isAck;
    if (tcpPacket->ack & 0x0001)
466
    {
467
      isAck = true;
468
    }
469 470 471 472 473 474 475 476 477 478 479 480 481
    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.
482
    key.transport = TCP_CONNECTION;
483 484 485
    key.ip = ntohl(ipPacket->ip_dst.s_addr);
    key.localPort = ntohs(tcpPacket->source);
    key.remotePort = ntohs(tcpPacket->dest);
486

487
    map<Order, Connection *>::iterator pos;
488 489 490
    pos = global::planetMap.find(key);
    if (pos != global::planetMap.end())
    {
491 492
      // This is an outgoing packet.
      if (!isAck)
493
      {
494
        // We only care about sent packets, not acked packets.
495
        handleKernel(pos->second, &kernelInfo);
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
        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);
        }
517 518 519 520
      }
    }
  }

521
  void handleKernel(Connection * conn, struct tcp_info * kernel)
522
  {
523 524 525 526 527 528 529
    // 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)
530
    {
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
      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");
547 548
    }
  }
549
}