Ejemplo n.º 1
1
  private String detectAgentUrl(
      HttpServer pServer, JolokiaServerConfig pConfig, String pContextPath) {
    serverAddress = pServer.getAddress();
    InetAddress realAddress;
    int port;
    if (serverAddress != null) {
      realAddress = serverAddress.getAddress();
      if (realAddress.isAnyLocalAddress()) {
        try {
          realAddress = NetworkUtil.getLocalAddress();
        } catch (IOException e) {
          try {
            realAddress = InetAddress.getLocalHost();
          } catch (UnknownHostException e1) {
            // Ok, ok. We take the original one
            realAddress = serverAddress.getAddress();
          }
        }
      }
      port = serverAddress.getPort();
    } else {
      realAddress = pConfig.getAddress();
      port = pConfig.getPort();
    }

    return String.format(
        "%s://%s:%d%s", pConfig.getProtocol(), realAddress.getHostAddress(), port, pContextPath);
  }
Ejemplo n.º 2
1
  /**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy with Basic
   * authentication. It issues a CONNECT request and authenticates with the HTTP proxy with Basic
   * protocol.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket authenticateBasic(InetSocketAddress address, ConnectivitySettings cs)
      throws IOException {
    Socket proxy = new Socket(cs.getProxyHost(), cs.getProxyPort());
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    String username = cs.getProxyUsername() == null ? "" : cs.getProxyUsername();
    String password = cs.getProxyPassword() == null ? "" : String.valueOf(cs.getProxyPassword());
    String credentials = username + ":" + password;
    String basicCookie = Base64Encoder.encode(credentials.getBytes("US-ASCII"));

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n");
    dos.writeBytes("Proxy-Authorization: Basic " + basicCookie + "\r\n");
    dos.writeBytes("\r\n");
    dos.flush();

    String line = r.readLine();
    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    }
    throw new IOException("Basic authentication failed: " + line);
  }
Ejemplo n.º 3
0
 void connected(TcpSocket fan) throws IOException {
   InetSocketAddress sockAddr = (InetSocketAddress) socket.getRemoteSocketAddress();
   this.remoteAddr = IpAddrPeer.make(sockAddr.getAddress());
   this.remotePort = sockAddr.getPort();
   this.in = SysInStream.make(socket.getInputStream(), getInBufferSize(fan));
   this.out = SysOutStream.make(socket.getOutputStream(), getOutBufferSize(fan));
 }
Ejemplo n.º 4
0
  /** Initialize SecondaryNameNode. */
  private void initialize(Configuration conf) throws IOException {
    // initiate Java VM metrics
    JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));

    // Create connection to the namenode.
    shouldRun = true;
    nameNodeAddr = NameNode.getAddress(conf);

    this.conf = conf;
    this.namenode =
        (NamenodeProtocol)
            RPC.waitForProxy(
                NamenodeProtocol.class, NamenodeProtocol.versionID, nameNodeAddr, conf);

    // initialize checkpoint directories
    fsName = getInfoServer();
    checkpointDirs = FSImage.getCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary");
    checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf, "/tmp/hadoop/dfs/namesecondary");
    checkpointImage = new CheckpointStorage(conf);
    checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);

    // Initialize other scheduling parameters from the configuration
    checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
    checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);

    // initialize the webserver for uploading files.
    String infoAddr =
        NetUtils.getServerAddress(
            conf,
            "dfs.secondary.info.bindAddress",
            "dfs.secondary.info.port",
            "dfs.secondary.http.address");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    infoBindAddress = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort, tmpInfoPort == 0, conf);
    infoServer.setAttribute("name.system.image", checkpointImage);
    this.infoServer.setAttribute("name.conf", conf);
    infoServer.addInternalServlet("getimage", "/getimage", GetImageServlet.class);
    infoServer.start();

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = infoServer.getPort();
    conf.set("dfs.secondary.http.address", infoBindAddress + ":" + infoPort);
    LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" + infoPort);
    LOG.warn(
        "Checkpoint Period   :"
            + checkpointPeriod
            + " secs "
            + "("
            + checkpointPeriod / 60
            + " min)");
    LOG.warn(
        "Log Size Trigger    :"
            + checkpointSize
            + " bytes "
            + "("
            + checkpointSize / 1024
            + " KB)");
  }
Ejemplo n.º 5
0
 private void setupProxy(
     ConnectivitySettings cs, int connectionType, InetSocketAddress inetSocketAddress) {
   cs.setConnectionType(connectionType);
   InetAddress address = inetSocketAddress.getAddress();
   cs.setProxyHost((address != null) ? address.getHostAddress() : inetSocketAddress.getHostName());
   cs.setProxyPort(inetSocketAddress.getPort());
 }
Ejemplo n.º 6
0
  /**
   * Binds the socket to the givent local address/port
   *
   * @param bindpoint The address/port to bind to
   * @exception IOException If an error occurs
   * @exception SecurityException If a security manager exists and its checkConnect method doesn't
   *     allow the operation
   * @exception IllegalArgumentException If the address type is not supported
   * @since 1.4
   */
  public void bind(SocketAddress bindpoint) throws IOException {
    if (closed) throw new SocketException("Socket is closed");

    if (!(bindpoint instanceof InetSocketAddress)) throw new IllegalArgumentException();

    InetSocketAddress tmp = (InetSocketAddress) bindpoint;
    impl.bind(tmp.getAddress(), tmp.getPort());
  }
 /**
  * Sends a specific <tt>RawPacket</tt> through this <tt>OutputDataStream</tt> to a specific
  * <tt>InetSocketAddress</tt>.
  *
  * @param packet the <tt>RawPacket</tt> to send through this <tt>OutputDataStream</tt> to the
  *     specified <tt>target</tt>
  * @param target the <tt>InetSocketAddress</tt> to which the specified <tt>packet</tt> is to be
  *     sent through this <tt>OutputDataStream</tt>
  * @throws IOException if anything goes wrong while sending the specified <tt>packet</tt> through
  *     this <tt>OutputDataStream</tt> to the specified <tt>target</tt>
  */
 @Override
 protected void sendToTarget(RawPacket packet, InetSocketAddress target) throws IOException {
   socket.send(
       new DatagramPacket(
           packet.getBuffer(),
           packet.getOffset(),
           packet.getLength(),
           target.getAddress(),
           target.getPort()));
 }
Ejemplo n.º 8
0
    private void doConnect(InetSocketAddress addr) throws IOException {
      dest = new Socket();
      try {
        dest.connect(addr, 10000);
      } catch (SocketTimeoutException ex) {
        sendError(HOST_UNREACHABLE);
        return;
      } catch (ConnectException cex) {
        sendError(CONN_REFUSED);
        return;
      }
      // Success
      InetAddress iadd = addr.getAddress();
      if (iadd instanceof Inet4Address) {
        out.write(PROTO_VERS);
        out.write(REQUEST_OK);
        out.write(0);
        out.write(IPV4);
        out.write(iadd.getAddress());
      } else if (iadd instanceof Inet6Address) {
        out.write(PROTO_VERS);
        out.write(REQUEST_OK);
        out.write(0);
        out.write(IPV6);
        out.write(iadd.getAddress());
      } else {
        sendError(GENERAL_FAILURE);
        return;
      }
      out.write((addr.getPort() >> 8) & 0xff);
      out.write((addr.getPort() >> 0) & 0xff);
      out.flush();

      InputStream in2 = dest.getInputStream();
      OutputStream out2 = dest.getOutputStream();

      Tunnel tunnel = new Tunnel(in2, out);
      tunnel.start();

      int b = 0;
      do {
        // Note that the socket might be closed from another thread (the tunnel)
        try {
          b = in.read();
          if (b == -1) {
            in.close();
            out2.close();
            return;
          }
          out2.write(b);
        } catch (IOException ioe) {
        }
      } while (!client.isClosed());
    }
Ejemplo n.º 9
0
  /**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy. It issues a
   * CONNECT request and eventually authenticates with the HTTP proxy. Supported authentication
   * methods include: Basic.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws UnknownHostException if the proxy host name cannot be resolved
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket getHttpsTunnelSocket(
      InetSocketAddress address, ConnectivitySettings cs, int timeout) throws IOException {
    Socket proxy = new Socket();
    proxy.connect(new InetSocketAddress(cs.getProxyHost(), cs.getProxyPort()), timeout);
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n\r\n");
    dos.flush();

    String line;
    line = r.readLine();

    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    } else if (sProxyAuthRequiredPattern.matcher(line).find()) {
      boolean authMethodSelected = false;
      String authMethod = AUTH_NONE;
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
        if (line.startsWith("Proxy-Authenticate:") && !authMethodSelected) {
          authMethod = line.substring(19).trim();
          if (authMethod.equals(AUTH_BASIC)) {
            authMethodSelected = true;
          }
        }
      }
      // TODO: need to read full response before closing connection?
      proxy.close();

      if (authMethod.startsWith(AUTH_BASIC)) {
        return authenticateBasic(address, cs);
      } else {
        throw new IOException("Unsupported authentication method: " + authMethod);
      }
    } else {
      proxy.close();
      throw new IOException("HTTP proxy does not support CONNECT command. Received reply: " + line);
    }
  }
Ejemplo n.º 10
0
 private URI addressToURI(InetSocketAddress address, String schema) {
   URI uri;
   try {
     if (address.isUnresolved()) {
       uri = new URI(schema + "://" + address.getHostName() + ":" + address.getPort());
     } else {
       uri =
           new URI(
               schema + "://" + address.getAddress().getHostAddress() + ":" + address.getPort());
     }
   } catch (URISyntaxException e) {
     throw new RuntimeException(e);
   }
   return uri;
 }
Ejemplo n.º 11
0
    DBPortPool get(InetSocketAddress addr) {

      DBPortPool p = _pools.get(addr);

      if (p != null) return p;

      synchronized (_pools) {
        p = _pools.get(addr);
        if (p != null) {
          return p;
        }

        p = new DBPortPool(addr, _options);
        _pools.put(addr, p);
        String name = "com.mongodb:type=ConnectionPool,host=" + addr.toString().replace(':', '_');

        try {
          ObjectName on = new ObjectName(name);
          if (_server.isRegistered(on)) {
            _server.unregisterMBean(on);
            Bytes.LOGGER.log(
                Level.INFO, "multiple Mongo instances for same host, jmx numbers might be off");
          }
          _server.registerMBean(p, on);
        } catch (JMException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        } catch (java.security.AccessControlException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        }
      }

      return p;
    }
Ejemplo n.º 12
0
 DBPortPool(InetSocketAddress addr, MongoOptions options) {
   super("DBPortPool-" + addr.toString(), options.connectionsPerHost, options.connectionsPerHost);
   _options = options;
   _addr = addr;
   _waitingSem =
       new Semaphore(
           _options.connectionsPerHost * _options.threadsAllowedToBlockForConnectionMultiplier);
 }
Ejemplo n.º 13
0
  /** Start the JobTracker process, listen on the indicated port */
  JobTracker(Configuration conf) throws IOException {
    //
    // Grab some static constants
    //
    maxCurrentTasks = conf.getInt("mapred.tasktracker.tasks.maximum", 2);
    RETIRE_JOB_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.interval", 24 * 60 * 60 * 1000);
    RETIRE_JOB_CHECK_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.check", 60 * 1000);
    TASK_ALLOC_EPSILON = conf.getFloat("mapred.jobtracker.taskalloc.loadbalance.epsilon", 0.2f);
    PAD_FRACTION = conf.getFloat("mapred.jobtracker.taskalloc.capacitypad", 0.1f);
    MIN_SLOTS_FOR_PADDING = 3 * maxCurrentTasks;

    // This is a directory of temporary submission files.  We delete it
    // on startup, and can delete any files that we're done with
    this.conf = conf;
    JobConf jobConf = new JobConf(conf);
    this.systemDir = jobConf.getSystemDir();
    this.fs = FileSystem.get(conf);
    FileUtil.fullyDelete(fs, systemDir);
    fs.mkdirs(systemDir);

    // Same with 'localDir' except it's always on the local disk.
    jobConf.deleteLocalFiles(SUBDIR);

    // Set ports, start RPC servers, etc.
    InetSocketAddress addr = getAddress(conf);
    this.localMachine = addr.getHostName();
    this.port = addr.getPort();
    this.interTrackerServer = RPC.getServer(this, addr.getPort(), 10, false, conf);
    this.interTrackerServer.start();
    Properties p = System.getProperties();
    for (Iterator it = p.keySet().iterator(); it.hasNext(); ) {
      String key = (String) it.next();
      String val = (String) p.getProperty(key);
      LOG.info("Property '" + key + "' is " + val);
    }

    this.infoPort = conf.getInt("mapred.job.tracker.info.port", 50030);
    this.infoServer = new JobTrackerInfoServer(this, infoPort);
    this.infoServer.start();

    this.startTime = System.currentTimeMillis();

    new Thread(this.expireTrackers).start();
    new Thread(this.retireJobs).start();
    new Thread(this.initJobs).start();
  }
Ejemplo n.º 14
0
  DBPort(InetSocketAddress addr, DBPortPool pool, MongoOptions options) throws IOException {
    _options = options;
    _addr = addr;
    _pool = pool;

    _hashCode = _addr.hashCode();

    _logger = Logger.getLogger(_rootLogger.getName() + "." + addr.toString());
  }
Ejemplo n.º 15
0
    private void doBind(InetSocketAddress addr) throws IOException {
      ServerSocket svr = new ServerSocket();
      svr.bind(null);
      InetSocketAddress bad = (InetSocketAddress) svr.getLocalSocketAddress();
      out.write(PROTO_VERS);
      out.write(REQUEST_OK);
      out.write(0);
      out.write(IPV4);
      out.write(bad.getAddress().getAddress());
      out.write((bad.getPort() >> 8) & 0xff);
      out.write((bad.getPort() & 0xff));
      out.flush();
      dest = svr.accept();
      bad = (InetSocketAddress) dest.getRemoteSocketAddress();
      out.write(PROTO_VERS);
      out.write(REQUEST_OK);
      out.write(0);
      out.write(IPV4);
      out.write(bad.getAddress().getAddress());
      out.write((bad.getPort() >> 8) & 0xff);
      out.write((bad.getPort() & 0xff));
      out.flush();
      InputStream in2 = dest.getInputStream();
      OutputStream out2 = dest.getOutputStream();

      Tunnel tunnel = new Tunnel(in2, out);
      tunnel.start();

      int b = 0;
      do {
        // Note that the socket might be close from another thread (the tunnel)
        try {
          b = in.read();
          if (b == -1) {
            in.close();
            out2.close();
            return;
          }
          out2.write(b);
        } catch (IOException ioe) {
        }
      } while (!client.isClosed());
    }
Ejemplo n.º 16
0
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
Ejemplo n.º 17
0
    @Override
    public void run() {
      ProxyConnection connection = provider.getConnection();
      if (connection == null) {
        logger.error("No connection found to send CRLF keep alive" + " with " + provider);
        return;
      }

      ListeningPoint lp = provider.getListeningPoint(connection.getTransport());

      if (!(lp instanceof ListeningPointExt)) {
        logger.error("ListeningPoint is not ListeningPointExt" + "(or is null)");
        return;
      }

      InetSocketAddress address = connection.getAddress();
      try {
        ((ListeningPointExt) lp)
            .sendHeartbeat(address.getAddress().getHostAddress(), address.getPort());
      } catch (IOException e) {
        logger.error("Error while sending a heartbeat", e);
      }
    }
  /**
   * Log the packet.
   *
   * @param packet packet to log
   */
  @Override
  protected void doLogPacket(RawPacket packet, InetSocketAddress target) {
    if (socket == null || packet == null || target == null) return;

    // Do not log the packet if it has been processed (and already
    // logged) by the ice4j stack.
    if (socket instanceof MultiplexingDatagramSocket) return;

    PacketLoggingService pktLogging = getPacketLoggingService();

    if (pktLogging != null) {
      pktLogging.logPacket(
          PacketLoggingService.ProtocolName.RTP,
          socket.getLocalAddress().getAddress(),
          socket.getLocalPort(),
          target.getAddress().getAddress(),
          target.getPort(),
          PacketLoggingService.TransportName.UDP,
          true,
          packet.getBuffer(),
          packet.getOffset(),
          packet.getLength());
    }
  }
  public void testInetSocketAddress() throws IOException {
    InetSocketAddress address = MAPPER.readValue(quote("127.0.0.1"), InetSocketAddress.class);
    assertEquals("127.0.0.1", address.getAddress().getHostAddress());

    InetSocketAddress ip6 =
        MAPPER.readValue(quote("2001:db8:85a3:8d3:1319:8a2e:370:7348"), InetSocketAddress.class);
    assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6.getAddress().getHostAddress());

    InetSocketAddress ip6port =
        MAPPER.readValue(
            quote("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443"), InetSocketAddress.class);
    assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6port.getAddress().getHostAddress());
    assertEquals(443, ip6port.getPort());

    // should we try resolving host names? That requires connectivity...
    final String HOST = "www.ning.com";
    address = MAPPER.readValue(quote(HOST), InetSocketAddress.class);
    assertEquals(HOST, address.getHostName());
  }
Ejemplo n.º 20
0
 public void setPort(int port) {
   address = new InetSocketAddress(address.getAddress(), port);
 }
Ejemplo n.º 21
0
 /**
  * Sets the address of the server to communicate with (on the default DNS port)
  *
  * @param addr The address of the DNS server
  */
 public void setAddress(InetAddress addr) {
   address = new InetSocketAddress(addr, address.getPort());
 }
Ejemplo n.º 22
0
  /**
   * Sends a message to a single server and waits for a response. No checking is done to ensure that
   * the response is associated with the query.
   *
   * @param query The query to send.
   * @return The response.
   * @throws IOException An error occurred while sending or receiving.
   */
  public Message send(Message query) throws IOException {
    if (Options.check("verbose"))
      System.err.println(
          "Sending to " + address.getAddress().getHostAddress() + ":" + address.getPort());

    if (query.getHeader().getOpcode() == Opcode.QUERY) {
      Record question = query.getQuestion();
      if (question != null && question.getType() == Type.AXFR) return sendAXFR(query);
    }

    query = (Message) query.clone();
    applyEDNS(query);
    if (tsig != null) {
      tsig.apply(query, null);
    }

    byte[] out = query.toWire(Message.MAXLENGTH);
    int udpSize = maxUDPSize(query);
    boolean tcp = false;
    long endTime = System.currentTimeMillis() + timeoutValue;
    do {
      byte[] b_in;

      if (useTCP || out.length > udpSize) {
        tcp = true;
      }
      if (tcp) {
        b_in = TCPClient.sendrecv(localAddress, address, out, endTime);
      } else {
        b_in = UDPClient.sendrecv(localAddress, address, out, udpSize, endTime);
      }

      /*
       * Check that the response is long enough.
       */
      if (b_in.length < Header.LENGTH) {
        throw new WireParseException("invalid DNS header - " + "too short");
      }
      /*
       * Check that the response ID matches the query ID.  We want
       * to check this before actually parsing the message, so that
       * if there's a malformed response that's not ours, it
       * doesn't confuse us.
       */
      int id = ((b_in[0] & 0xFF) << 8) + (b_in[1] & 0xFF);
      int qid = query.getHeader().getID();
      if (id != qid) {
        String error = "invalid message id: expected " + qid + "; got id " + id;
        if (tcp) {
          throw new WireParseException(error);
        } else {
          if (Options.check("verbose")) {
            System.err.println(error);
          }
          continue;
        }
      }
      Message response = parseMessage(b_in);
      verifyTSIG(query, response, b_in, tsig);
      if (!tcp && !ignoreTruncation && response.getHeader().getFlag(Flags.TC)) {
        tcp = true;
        continue;
      }
      return response;
    } while (true);
  }
Ejemplo n.º 23
0
 public UDPMessageServer(InetSocketAddress address) throws IOException {
   this(IP.fromInetAddress(address.getAddress()), address.getPort());
 }
Ejemplo n.º 24
0
 /**
  * Returns the number of a port on the switch
  *
  * @param os the port
  * @return the number of the port
  */
 public int getPortNumber(InetSocketAddress os) {
   for (int i = 0; i < ports.length; i++) if (os.equals(ports[i])) return i;
   throw new NoSuchElementException();
 }
Ejemplo n.º 25
0
  /**
   * Logs the specified message and details to the packet logging service if enabled.
   *
   * @param message the message to log
   * @param sender determines whether we are the origin of this message.
   */
  private void logPacket(SIPMessage message, boolean sender) {
    try {
      PacketLoggingService packetLogging = SipActivator.getPacketLogging();
      if (packetLogging == null
          || !packetLogging.isLoggingEnabled(PacketLoggingService.ProtocolName.SIP)
          /* Via not present in CRLF packet on TCP - causes NPE */
          || message.getTopmostVia() == null) return;

      String transport = message.getTopmostVia().getTransport();
      boolean isTransportUDP = transport.equalsIgnoreCase("UDP");

      byte[] srcAddr;
      int srcPort;
      byte[] dstAddr;
      int dstPort;

      // if addresses are not set use empty byte array with length
      // equals to the other address or just empty
      // byte array with length 4 (ipv4 0.0.0.0)
      if (sender) {
        if (!isTransportUDP) {
          InetSocketAddress localAddress =
              getLocalAddressForDestination(
                  message.getRemoteAddress(),
                  message.getRemotePort(),
                  message.getLocalAddress(),
                  transport);
          srcPort = localAddress.getPort();
          srcAddr = localAddress.getAddress().getAddress();
        } else {
          srcPort = message.getLocalPort();
          if (message.getLocalAddress() != null) srcAddr = message.getLocalAddress().getAddress();
          else if (message.getRemoteAddress() != null)
            srcAddr = new byte[message.getRemoteAddress().getAddress().length];
          else srcAddr = new byte[4];
        }

        dstPort = message.getRemotePort();
        if (message.getRemoteAddress() != null) dstAddr = message.getRemoteAddress().getAddress();
        else dstAddr = new byte[srcAddr.length];
      } else {
        if (!isTransportUDP) {
          InetSocketAddress dstAddress =
              getLocalAddressForDestination(
                  message.getRemoteAddress(),
                  message.getRemotePort(),
                  message.getLocalAddress(),
                  transport);
          dstPort = dstAddress.getPort();
          dstAddr = dstAddress.getAddress().getAddress();
        } else {
          dstPort = message.getLocalPort();
          if (message.getLocalAddress() != null) dstAddr = message.getLocalAddress().getAddress();
          else if (message.getRemoteAddress() != null)
            dstAddr = new byte[message.getRemoteAddress().getAddress().length];
          else dstAddr = new byte[4];
        }

        srcPort = message.getRemotePort();
        if (message.getRemoteAddress() != null) srcAddr = message.getRemoteAddress().getAddress();
        else srcAddr = new byte[dstAddr.length];
      }

      byte[] msg = null;
      if (message instanceof SIPRequest) {
        SIPRequest req = (SIPRequest) message;
        if (req.getMethod().equals(SIPRequest.MESSAGE)
            && message.getContentTypeHeader() != null
            && message.getContentTypeHeader().getContentType().equalsIgnoreCase("text")) {
          int len = req.getContentLength().getContentLength();

          if (len > 0) {
            SIPRequest newReq = (SIPRequest) req.clone();

            byte[] newContent = new byte[len];
            Arrays.fill(newContent, (byte) '.');
            newReq.setMessageContent(newContent);
            msg = newReq.toString().getBytes("UTF-8");
          }
        }
      }

      if (msg == null) {
        msg = message.toString().getBytes("UTF-8");
      }

      packetLogging.logPacket(
          PacketLoggingService.ProtocolName.SIP,
          srcAddr,
          srcPort,
          dstAddr,
          dstPort,
          isTransportUDP
              ? PacketLoggingService.TransportName.UDP
              : PacketLoggingService.TransportName.TCP,
          sender,
          msg);
    } catch (Throwable e) {
      logger.error("Cannot obtain message body", e);
    }
  }