KernelTcp.cc 16.4 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
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,
20
                 struct ip const * ipPacket,
21 22 23 24 25 26 27
                 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
        || (receiveBufferSize != 0 && !changeSocket(sockfd, SOL_SOCKET,
                                                    SO_RCVBUF,
                                                    receiveBufferSize,
                                                    "SO_RCVBUF"))
        || !changeSocket(sockfd, IPPROTO_TCP, TCP_NODELAY, !useNagles,
                         "TCP_NODELAY"))
    {
79
      // Error message already printed
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
      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
    {
      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);

137 138
    logWrite(CONNECTION_MODEL, "Connected to peer at %s:%d",
             ipToString(htonl(planet.ip)).c_str(), global::peerServerPort);
139 140 141 142 143 144 145
    peersock = sockfd;
    state = CONNECTED;
  }
}

void KernelTcp::addParam(ConnectionModelCommand const & param)
{
146 147 148 149 150 151
  if (state == CONNECTED)
  {
    logWrite(ERROR, "A ConnectionModelCommand was received after connection. "
             "It will not be applied unless the connection dies and is "
             "re-established.");
  }
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  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)
  {
175 176
    logWrite(CONNECTION_MODEL,
             "writeMessage() called while disconnected from peer.");
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    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;
196
      result.bufferFull = false;
197 198 199 200 201
      result.isConnected = false;
      return 0;
    }
    else if (error == -1)
    {
202 203 204 205 206
      if (errno == EWOULDBLOCK)
      {
        result.bufferFull = true;
      }
      else
207 208 209
      {
        logWrite(EXCEPTION, "Failed write to peer: %s", strerror(errno));
      }
210 211 212 213 214 215 216
      return -1;
    }
    else
    {
      return error;
    }
  }
217
  result.bufferFull = false;
218 219 220 221 222 223 224 225 226
  result.isConnected = false;
  return -1;
}

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

227 228 229 230 231
int KernelTcp::getSock(void) const
{
  return peersock;
}

232 233 234
enum { SNIFF_WAIT = 10 };

void KernelTcp::init(void)
235 236
{
  // Set up the peerAccept socket
237 238 239
  global::peerAccept = createServer(global::peerServerPort,
                                    "Peer accept socket (No incoming peer "
                                    "connections will be accepted)");
240 241
  logWrite(PEER_CYCLE, "Created peer server on port %d",
           global::peerServerPort);
242

243
  // Set up the connectionModelExemplar
244 245
  global::connectionModelExemplar.reset(new KernelTcp());

246
  // Set up packet capture
247
  char errbuf[PCAP_ERRBUF_SIZE];
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
  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
266 267 268
  else if(pcap_compile(pcapDescriptor, &fp,
                       const_cast<char *>(filter.str().c_str()),
                       1, maskp) == -1)
269
  {
270 271
    logWrite(ERROR, "pcap_compile() failed: %s", pcap_geterr(pcapDescriptor));
    pcap_close(pcapDescriptor);
272 273 274 275
  }
  // set the compiled program as the filter
  else if(pcap_setfilter(pcapDescriptor,&fp) == -1)
  {
276 277
    logWrite(ERROR, "pcap_filter() failed: %s", pcap_geterr(pcapDescriptor));
    pcap_close(pcapDescriptor);
278 279 280 281 282 283
  }
  else
  {
    pcapfd = pcap_get_selectable_fd(pcapDescriptor);
    if (pcapfd == -1)
    {
284 285 286
      logWrite(ERROR, "Failed to get a selectable file descriptor "
               "for pcap: %s", pcap_geterr(pcapDescriptor));
      pcap_close(pcapDescriptor);
287 288 289 290 291 292
    }
    else
    {
      setDescriptor(pcapfd);
    }
  }
293 294
}

295
void KernelTcp::addNewPeer(fd_set * readable)
296 297 298 299 300
{
  if (global::peerAccept != -1
      && FD_ISSET(global::peerAccept, readable))
  {
    struct sockaddr_in remoteAddress;
301 302 303
    int fd = acceptServer(global::peerAccept, &remoteAddress,
                          "Peer socket (Incoming peer connection was not "
                          "accepted)");
304 305
    if (fd != -1)
    {
306 307 308 309 310 311
      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());
312 313 314 315
    }
  }
}

316
void KernelTcp::readFromPeers(fd_set * readable)
317
{
318 319
  list< pair<int, string> >::iterator pos = global::peers.begin();
  while (pos != global::peers.end())
320
  {
321
    if (pos->first != -1 && FD_ISSET(pos->first, readable))
322 323 324 325 326 327 328 329
    {
      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.",
330
                 pos->first, pos->second.c_str());
331
        close(pos->first);
332
        clearDescriptor(pos->first);
333
        list< pair<int, string> >::iterator temp = pos;
334 335 336 337 338 339 340
        ++pos;
        global::peers.erase(temp);
      }
      else if (size == -1 && errno != EAGAIN && errno != EINTR)
      {
        logWrite(EXCEPTION,
                 "Failed to read peer connection %d from %s so "
341
                 "I'm shutting it down: %s", pos->first, pos->second.c_str(),
342 343
                 strerror(errno));
        close(pos->first);
344
        list< pair<int, string> >::iterator temp = pos;
345 346 347 348 349 350 351 352 353 354 355 356 357 358
        ++pos;
        global::peers.erase(temp);
      }
      else
      {
        ++pos;
      }
    }
    else
    {
      ++pos;
    }
  }
}
359

360 361 362
void KernelTcp::packetCapture(fd_set * readable)
{
  unsigned char * args = NULL;
363
  if (pcapfd != -1 && FD_ISSET(pcapfd, readable))
364
  {
365
    pcap_dispatch(pcapDescriptor, 1, kernelTcpCallback, args);
366 367 368
  }
}

369
namespace
370
{
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  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());
387
      return false;
388 389 390 391 392 393 394 395 396
    }
    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)
397
  {
398
    logWrite(PCAP, "Captured a packet");
399 400 401 402 403 404 405 406 407 408 409
    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;
    }
410
    struct ip const * ipPacket;
411
    struct tcphdr const * tcpPacket;
412
    size_t bytesRemaining = pcapInfo->caplen - sizeof(struct ether_header);
413

414
    ipPacket = reinterpret_cast<struct ip const *>
415
      (packet + sizeof(struct ether_header));
416
    if (bytesRemaining < sizeof(struct ip))
417 418 419
    {
      logWrite(ERROR, "A captured packet was too short to contain an "
               "IP header");
420
      return;
421
    }
422 423
    // ipHeaderLength and version are in a one byte field so
    // endian-ness doesn't matter.
424 425
    int ipHeaderLength = ipPacket->ip_hl;
    int version = ipPacket->ip_v;
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    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);
454 455
  }

456 457 458
  int getLinkLayer(struct pcap_pkthdr const * pcapInfo,
                   unsigned char const * packet)
  {
459 460
    unsigned int caplen = pcapInfo->caplen;

461
    if (caplen < sizeof(struct ether_header))
462 463 464 465 466 467 468 469 470 471 472
    {
      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);
    }
  }
473 474

  void handleTcp(struct pcap_pkthdr const * pcapInfo,
475
                 struct ip const * ipPacket,
476
                 struct tcphdr const * tcpPacket)
477
  {
478
    logWrite(PCAP, "Captured a TCP packet");
479 480 481
    struct tcp_info kernelInfo;
    bool isAck;
    if (tcpPacket->ack & 0x0001)
482
    {
483
      isAck = true;
484
    }
485 486 487 488 489 490 491 492 493 494 495 496 497
    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.
498
    key.transport = TCP_CONNECTION;
499 500 501
    key.ip = ntohl(ipPacket->ip_dst.s_addr);
    key.localPort = ntohs(tcpPacket->source);
    key.remotePort = ntohs(tcpPacket->dest);
502

503
    map<Order, Connection *>::iterator pos;
504 505 506
    pos = global::planetMap.find(key);
    if (pos != global::planetMap.end())
    {
507 508
      // This is an outgoing packet.
      if (!isAck)
509
      {
510
        // We only care about sent packets, not acked packets.
511
        handleKernel(pos->second, &kernelInfo);
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        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);
        }
533 534 535 536
      }
    }
  }

537
  void handleKernel(Connection * conn, struct tcp_info * kernel)
538
  {
539 540 541 542 543 544 545
    // 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)
546
    {
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
      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");
563 564
    }
  }
565
}