/**
   * Process connection response data.
   *
   * @param conn connection to read response data from.
   * @return assembled response as string.
   * @throws IOException on I/O error
   */
  private StringBuilder readResponse(URLConnection conn) throws IOException {
    StringBuilder retval = new StringBuilder();
    HttpURLConnection http = (HttpURLConnection) conn;
    int resp = 200;
    try {
      resp = http.getResponseCode();
    } catch (Throwable ex) {
    }

    if (resp >= 200 && resp < 300) {
      BufferedReader input = null;
      try {
        input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      } catch (Throwable ex) {
        retval.append(ex.toString());
        return retval;
      }

      String line = null;
      while ((line = input.readLine()) != null) {
        retval.append(line);
        retval.append("\n");
      }
      input.close();
    } else {
      retval.append(http.getResponseMessage());
    }

    LogContext.getLogger().finer(String.format("<-- HTTP Response: %d: %s", resp, retval));

    return retval;
  }
Ejemplo n.º 2
0
  /**
   * Processes a packet read from either the multicast or unicast socket. Needs to be synchronized
   * because mcast or unicast socket reads can be concurrent
   */
  void handleIncomingUdpPacket(byte[] data) {
    ByteArrayInputStream inp_stream;
    ObjectInputStream inp;
    Message msg = null;
    List l; // used if bundling is enabled

    try {
      // skip the first n bytes (default: 4), this is the version info
      inp_stream = new ByteArrayInputStream(data, VERSION_LENGTH, data.length - VERSION_LENGTH);
      inp = new ObjectInputStream(inp_stream);
      if (enable_bundling) {
        l = new List();
        l.readExternal(inp);
        for (Enumeration en = l.elements(); en.hasMoreElements(); ) {
          msg = (Message) en.nextElement();
          try {
            handleMessage(msg);
          } catch (Throwable t) {
            Trace.error("UDP.handleIncomingUdpPacket()", "failure: " + t.toString());
          }
        }
      } else {
        msg = new Message();
        msg.readExternal(inp);
        handleMessage(msg);
      }
    } catch (Throwable e) {
      Trace.error("UDP.handleIncomingUdpPacket()", "exception=" + Trace.getStackTrace(e));
    }
  }
Ejemplo n.º 3
0
 /**
  * Returns an string array representation of the specified throwable.
  *
  * @param th throwable
  * @return string array
  */
 private static String[] toArray(final Throwable th) {
   final StackTraceElement[] st = th.getStackTrace();
   final String[] obj = new String[st.length + 1];
   obj[0] = th.toString();
   for (int i = 0; i < st.length; i++) obj[i + 1] = "  " + st[i];
   return obj;
 }
Ejemplo n.º 4
0
    public void run() {
      Throwable t = null;
      while (canRun()) {
        Buffer data = null;
        try {
          data = send_queue.take();
          if (data.hashCode() == termination.hashCode()) break;
        } catch (InterruptedException e) {
          t = e;
          break;
        }

        if (data != null) {
          try {
            _send(data.getBuf(), 0, data.getLength(), false, send_queue.isEmpty());
          } catch (Throwable ignored) {
            t = ignored;
          }
        }
      }
      server.notifyConnectionClosed(
          TcpConnection.this,
          String.format(
              "%s: %s", getClass().getSimpleName(), t != null ? t.toString() : "normal stop"));
    }
Ejemplo n.º 5
0
 /**
  * Returns a more user-friendly error message for the specified exception.
  *
  * @param ex throwable reference
  * @return error message
  */
 public static String message(final Throwable ex) {
   debug(ex);
   if (ex instanceof BindException) return SRV_RUNNING;
   if (ex instanceof LoginException) return ACCESS_DENIED;
   if (ex instanceof ConnectException) return CONNECTION_ERROR;
   if (ex instanceof SocketTimeoutException) return TIMEOUT_EXCEEDED;
   if (ex instanceof SocketException) return CONNECTION_ERROR;
   String msg = ex.getMessage();
   if (msg == null || msg.isEmpty()) msg = ex.toString();
   if (ex instanceof FileNotFoundException) return info(RES_NOT_FOUND_X, msg);
   if (ex instanceof UnknownHostException) return info(UNKNOWN_HOST_X, msg);
   return msg;
 }
Ejemplo n.º 6
0
 public void run() {
   Throwable t = null;
   while (canRun()) {
     try {
       int len = in.readInt();
       if (buffer == null || buffer.length < len) buffer = new byte[len];
       in.readFully(buffer, 0, len);
       updateLastAccessed();
       server.receive(peer_addr, buffer, 0, len);
     } catch (OutOfMemoryError mem_ex) {
       t = mem_ex;
       break; // continue;
     } catch (IOException io_ex) {
       t = io_ex;
       break;
     } catch (Throwable e) {
     }
   }
   server.notifyConnectionClosed(
       TcpConnection.this,
       String.format("%s: %s", getClass().getSimpleName(), t != null ? t.toString() : "n/a"));
 }
Ejemplo n.º 7
0
 /**
  * Repeatedly receive a packet from the group, process it. No messages are sent from here.
  * sendPacket().
  */
 public void receiveGroupMessages() {
   if (LOG.isDebugEnabled()) {
     LOG.debug("Starting group receive loop for " + nodeId);
   }
   while (this.isRunning()) {
     try {
       final byte[] data = new byte[BUFFER_SIZE]; // set up an empty packet
       final DatagramPacket packet = new DatagramPacket(data, data.length);
       if (LOG.isDebugEnabled()) {
         LOG.debug("Waiting for group message on " + groupSocket);
       }
       groupSocket.receive(packet); // wait for a packet
       final String msg = toString(packet);
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Received group msg "
                 + msg
                 + " from "
                 + packet.getAddress()
                 + ":"
                 + packet.getPort()
                 + ".");
       }
       processGroupMessage(msg);
     } catch (SocketTimeoutException e) {
       if (LOG.isInfoEnabled()) {
         LOG.info(BUNDLE_MARKER, "GroupSocket receive timed out.");
       }
     } catch (IOException e) {
       LOG.error(BUNDLE_MARKER, e.toString(), e);
     } catch (Throwable t) {
       LOG.error(BUNDLE_MARKER, t.toString(), t);
     }
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug("Group receive loop for " + nodeId + " was stopped.");
   }
 }
  public void runSupport() {
    byte[] input_buffer = new byte[request_dg.getLength()];

    System.arraycopy(request_dg.getData(), 0, input_buffer, 0, input_buffer.length);

    int packet_data_length = input_buffer.length;

    String auth_user = null;
    byte[] auth_user_bytes = null;
    byte[] auth_hash = null;

    if (server.isTrackerPasswordEnabled()) {

      // auth detail should be attached to the packet. Auth details are 16
      // bytes

      if (input_buffer.length < 17) {

        Logger.log(
            new LogEvent(
                LOGID,
                LogEvent.LT_WARNING,
                "TRTrackerServerProcessorUDP: " + "packet received but authorisation missing"));

        return;
      }

      packet_data_length -= 16;

      auth_user_bytes = new byte[8];

      auth_hash = new byte[8];

      System.arraycopy(input_buffer, packet_data_length, auth_user_bytes, 0, 8);

      int user_len = 0;

      while (user_len < 8 && auth_user_bytes[user_len] != 0) {

        user_len++;
      }

      auth_user = new String(auth_user_bytes, 0, user_len);

      System.arraycopy(input_buffer, packet_data_length + 8, auth_hash, 0, 8);
    }

    DataInputStream is =
        new DataInputStream(new ByteArrayInputStream(input_buffer, 0, packet_data_length));

    try {
      String client_ip_address = request_dg.getAddress().getHostAddress();

      PRUDPPacketRequest request = PRUDPPacketRequest.deserialiseRequest(null, is);

      Logger.log(
          new LogEvent(
              LOGID, "TRTrackerServerProcessorUDP: packet received: " + request.getString()));

      PRUDPPacket reply = null;
      TRTrackerServerTorrentImpl torrent = null;

      if (auth_user_bytes != null) {

        // user name is irrelevant as we only have one at the moment

        // <parg_home> so <new_packet> = <old_packet> + <user_padded_to_8_bytes> + <hash>
        // <parg_home> where <hash> = first 8 bytes of sha1(<old_packet> + <user_padded_to_8> +
        // sha1(pass))
        // <XTF> Yes

        byte[] sha1_pw = null;

        if (server.hasExternalAuthorisation()) {

          try {
            URL resource = new URL("udp://" + server.getHost() + ":" + server.getPort() + "/");

            sha1_pw = server.performExternalAuthorisation(resource, auth_user);

          } catch (MalformedURLException e) {

            Debug.printStackTrace(e);
          }

          if (sha1_pw == null) {

            Logger.log(
                new LogEvent(
                    LOGID,
                    LogEvent.LT_ERROR,
                    "TRTrackerServerProcessorUDP: auth fails for user '" + auth_user + "'"));

            reply = new PRUDPPacketReplyError(request.getTransactionId(), "Access Denied");
          }
        } else {

          sha1_pw = server.getPassword();
        }

        // if we haven't already failed then check the PW

        if (reply == null) {

          SHA1Hasher hasher = new SHA1Hasher();

          hasher.update(input_buffer, 0, packet_data_length);
          hasher.update(auth_user_bytes);
          hasher.update(sha1_pw);

          byte[] digest = hasher.getDigest();

          for (int i = 0; i < auth_hash.length; i++) {

            if (auth_hash[i] != digest[i]) {

              Logger.log(
                  new LogEvent(
                      LOGID,
                      LogEvent.LT_ERROR,
                      "TRTrackerServerProcessorUDP: auth fails for user '" + auth_user + "'"));

              reply = new PRUDPPacketReplyError(request.getTransactionId(), "Access Denied");

              break;
            }
          }
        }
      }

      int request_type = TRTrackerServerRequest.RT_UNKNOWN;

      if (reply == null) {

        if (server.isEnabled()) {

          try {
            int type = request.getAction();

            if (type == PRUDPPacketTracker.ACT_REQUEST_CONNECT) {

              reply = handleConnect(client_ip_address, request);

            } else if (type == PRUDPPacketTracker.ACT_REQUEST_ANNOUNCE) {

              Object[] x =
                  handleAnnounceAndScrape(
                      client_ip_address, request, TRTrackerServerRequest.RT_ANNOUNCE);

              if (x == null) {

                throw (new Exception("Connection ID mismatch"));
              }

              reply = (PRUDPPacket) x[0];
              torrent = (TRTrackerServerTorrentImpl) x[1];

              request_type = TRTrackerServerRequest.RT_ANNOUNCE;

            } else if (type == PRUDPPacketTracker.ACT_REQUEST_SCRAPE) {

              Object[] x =
                  handleAnnounceAndScrape(
                      client_ip_address, request, TRTrackerServerRequest.RT_SCRAPE);

              if (x == null) {

                throw (new Exception("Connection ID mismatch"));
              }

              reply = (PRUDPPacket) x[0];
              torrent = (TRTrackerServerTorrentImpl) x[1];

              request_type = TRTrackerServerRequest.RT_SCRAPE;

            } else {

              reply = new PRUDPPacketReplyError(request.getTransactionId(), "unsupported action");
            }
          } catch (Throwable e) {

            // e.printStackTrace();

            String error = e.getMessage();

            if (error == null) {

              error = e.toString();
            }

            reply = new PRUDPPacketReplyError(request.getTransactionId(), error);
          }
        } else {

          System.out.println("UDP Tracker: replying 'disabled' to " + client_ip_address);

          reply = new PRUDPPacketReplyError(request.getTransactionId(), "UDP Tracker disabled");
        }
      }

      if (reply != null) {

        InetAddress address = request_dg.getAddress();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DataOutputStream os = new DataOutputStream(baos);

        reply.serialise(os);

        byte[] output_buffer = baos.toByteArray();

        DatagramPacket reply_packet =
            new DatagramPacket(output_buffer, output_buffer.length, address, request_dg.getPort());

        socket.send(reply_packet);

        server.updateStats(request_type, torrent, input_buffer.length, output_buffer.length);
      }

    } catch (Throwable e) {

      Logger.log(new LogEvent(LOGID, "TRTrackerServerProcessorUDP: processing fails", e));
    } finally {

      try {
        is.close();

      } catch (Throwable e) {

      }
    }
  }
Ejemplo n.º 9
0
 protected void recordError(String msg, Throwable t) {
   log.error(msg, t);
   errors.add(msg + ": " + t.toString());
 }