KernelTcp.cc 16.2 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
        || (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
      if (errno != EWOULDBLOCK)
      {
        logWrite(EXCEPTION, "Failed write to peer: %s", strerror(errno));
      }
206 207 208 209 210 211 212
      return -1;
    }
    else
    {
      return error;
    }
  }
213
  result.bufferFull = false;
214 215 216 217 218 219 220 221 222
  result.isConnected = false;
  return -1;
}

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

223 224 225 226 227
int KernelTcp::getSock(void) const
{
  return peersock;
}

228 229 230
enum { SNIFF_WAIT = 10 };

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

239
  // Set up the connectionModelExemplar
240 241
  global::connectionModelExemplar.reset(new KernelTcp());

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

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

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

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

365
namespace
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());
383
      return false;
384 385 386 387 388 389 390 391 392
    }
    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)
393
  {
394 395 396 397 398 399 400 401 402 403 404
    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;
    }
405 406
    IpHeader const * ipPacket;
    struct tcphdr const * tcpPacket;
407
    size_t bytesRemaining = pcapInfo->caplen - sizeof(struct ether_header);
408 409 410

    ipPacket = reinterpret_cast<IpHeader const *>
      (packet + sizeof(struct ether_header));
411
    if (bytesRemaining < sizeof(IpHeader))
412 413 414
    {
      logWrite(ERROR, "A captured packet was too short to contain an "
               "IP header");
415
      return;
416
    }
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    // 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);
449 450
  }

451 452 453
  int getLinkLayer(struct pcap_pkthdr const * pcapInfo,
                   unsigned char const * packet)
  {
454 455
    unsigned int caplen = pcapInfo->caplen;

456
    if (caplen < sizeof(struct ether_header))
457 458 459 460 461 462 463 464 465 466 467
    {
      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);
    }
  }
468 469 470 471

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

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

531
  void handleKernel(Connection * conn, struct tcp_info * kernel)
532
  {
533 534 535 536 537 538 539
    // 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)
540
    {
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
      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");
557 558
    }
  }
559
}