public Result authenticate(HttpExchange t) {
    Headers rmap = t.getRequestHeaders();
    /*
     * look for auth token
     */
    String auth = rmap.getFirst("Authorization");
    if (auth == null) {
      Headers map = t.getResponseHeaders();
      map.set("WWW-Authenticate", "Basic realm=" + "\"" + realm + "\"");
      return new Authenticator.Retry(401);
    }
    int sp = auth.indexOf(' ');
    if (sp == -1 || !auth.substring(0, sp).equals("Basic")) {
      return new Authenticator.Failure(401);
    }
    byte[] b = Base64.getDecoder().decode(auth.substring(sp + 1));
    String userpass = new String(b);
    int colon = userpass.indexOf(':');
    String uname = userpass.substring(0, colon);
    String pass = userpass.substring(colon + 1);

    if (checkCredentials(uname, pass)) {
      return new Authenticator.Success(new HttpPrincipal(uname, realm));
    } else {
      /* reject the request again with 401 */

      Headers map = t.getResponseHeaders();
      map.set("WWW-Authenticate", "Basic realm=" + "\"" + realm + "\"");
      return new Authenticator.Failure(401);
    }
  }
  /**
   * Processes a new connection making it idle or active depending on whether requests are waiting
   * to be sent.
   *
   * <p>A new connection is created when a request needs to be executed; it is possible that the
   * request that triggered the request creation is executed by another connection that was just
   * released, so the new connection may become idle.
   *
   * <p>If a request is waiting to be executed, it will be dequeued and executed by the new
   * connection.
   *
   * @param connection the new connection
   */
  public void process(final C connection) {
    HttpClient client = getHttpClient();
    final HttpExchange exchange = getHttpExchanges().poll();
    if (LOG.isDebugEnabled())
      LOG.debug("Processing exchange {} on {} of {}", exchange, connection, this);
    if (exchange == null) {
      if (!connectionPool.release(connection)) connection.close();

      if (!client.isRunning()) {
        if (LOG.isDebugEnabled()) LOG.debug("{} is stopping", client);
        connection.close();
      }
    } else {
      final Request request = exchange.getRequest();
      Throwable cause = request.getAbortCause();
      if (cause != null) {
        if (LOG.isDebugEnabled()) LOG.debug("Aborted before processing {}: {}", exchange, cause);
        // It may happen that the request is aborted before the exchange
        // is created. Aborting the exchange a second time will result in
        // a no-operation, so we just abort here to cover that edge case.
        exchange.abort(cause);
      } else {
        send(connection, exchange);
      }
    }
  }
Esempio n. 3
0
 /**
  * Aborts all the {@link HttpExchange}s queued in this destination.
  *
  * @param cause the abort cause
  */
 public void abort(Throwable cause) {
   // Copy the queue of exchanges and fail only those that are queued at this moment.
   // The application may queue another request from the failure/complete listener
   // and we don't want to fail it immediately as if it was queued before the failure.
   // The call to Request.abort() will remove the exchange from the exchanges queue.
   for (HttpExchange exchange : new ArrayList<>(exchanges)) exchange.getRequest().abort(cause);
 }
    @Override
    public void handle(HttpExchange t) throws IOException {
      LOGGER.debug("root req " + t.getRequestURI());
      if (RemoteUtil.deny(t)) {
        throw new IOException("Access denied");
      }
      if (t.getRequestURI().getPath().contains("favicon")) {
        RemoteUtil.sendLogo(t);
        return;
      }

      HashMap<String, Object> vars = new HashMap<>();
      vars.put("logs", getLogs(true));
      if (configuration.getUseCache()) {
        vars.put(
            "cache",
            "http://"
                + PMS.get().getServer().getHost()
                + ":"
                + PMS.get().getServer().getPort()
                + "/console/home");
      }

      String response = parent.getResources().getTemplate("doc.html").execute(vars);
      RemoteUtil.respond(t, response, 200, "text/html");
    }
Esempio n. 5
0
  protected boolean success() {
    HttpExchange exchange = connection.getExchange();
    if (exchange == null) return false;

    AtomicMarkableReference<Result> completion = exchange.responseComplete(null);
    if (!completion.isMarked()) return false;

    parser.reset();
    decoder = null;

    if (!updateState(State.RECEIVE, State.IDLE)) throw new IllegalStateException();

    exchange.terminateResponse();

    HttpResponse response = exchange.getResponse();
    List<Response.ResponseListener> listeners = exchange.getConversation().getResponseListeners();
    ResponseNotifier notifier = connection.getDestination().getResponseNotifier();
    notifier.notifySuccess(listeners, response);
    LOG.debug("Received {}", response);

    Result result = completion.getReference();
    if (result != null) {
      connection.complete(exchange, !result.isFailed());
      notifier.notifyComplete(listeners, result);
    }

    return true;
  }
Esempio n. 6
0
 private static void writePostReply(HttpExchange msg, byte[] buf) throws Exception {
   msg.getResponseHeaders().add("Content-Type", "text/xml");
   msg.sendResponseHeaders(200, buf.length);
   OutputStream out = msg.getResponseBody();
   out.write(buf);
   out.close();
 }
Esempio n. 7
0
 @Override
 public void badMessage(int status, String reason) {
   HttpExchange exchange = connection.getExchange();
   HttpResponse response = exchange.getResponse();
   response.status(status).reason(reason);
   failAndClose(new HttpResponseException("HTTP protocol violation: bad response", response));
 }
Esempio n. 8
0
  @Override
  public boolean headerComplete() {
    if (updateState(State.RECEIVE, State.RECEIVE)) {
      HttpExchange exchange = connection.getExchange();
      // The exchange may be null if it failed concurrently
      if (exchange != null) {
        HttpConversation conversation = exchange.getConversation();
        HttpResponse response = exchange.getResponse();
        LOG.debug("Headers {}", response);
        ResponseNotifier notifier = connection.getDestination().getResponseNotifier();
        notifier.notifyHeaders(conversation.getResponseListeners(), response);

        Enumeration<String> contentEncodings =
            response.getHeaders().getValues(HttpHeader.CONTENT_ENCODING.asString(), ",");
        if (contentEncodings != null) {
          for (ContentDecoder.Factory factory :
              connection.getHttpClient().getContentDecoderFactories()) {
            while (contentEncodings.hasMoreElements()) {
              if (factory.getEncoding().equalsIgnoreCase(contentEncodings.nextElement())) {
                this.decoder = factory.newContentDecoder();
                break;
              }
            }
          }
        }
      }
    }
    return false;
  }
Esempio n. 9
0
 @Override
 public boolean parsedHeader(HttpField field) {
   if (updateState(State.RECEIVE, State.RECEIVE)) {
     HttpExchange exchange = connection.getExchange();
     // The exchange may be null if it failed concurrently
     if (exchange != null) {
       HttpConversation conversation = exchange.getConversation();
       HttpResponse response = exchange.getResponse();
       ResponseNotifier notifier = connection.getDestination().getResponseNotifier();
       boolean process =
           notifier.notifyHeader(conversation.getResponseListeners(), response, field);
       if (process) {
         response.getHeaders().add(field);
         HttpHeader fieldHeader = field.getHeader();
         if (fieldHeader != null) {
           switch (fieldHeader) {
             case SET_COOKIE:
             case SET_COOKIE2:
               {
                 storeCookie(exchange.getRequest().getURI(), field);
                 break;
               }
             default:
               {
                 break;
               }
           }
         }
       }
     }
   }
   return false;
 }
 protected void abort(HttpExchange exchange, Throwable cause) {
   Request request = exchange.getRequest();
   HttpResponse response = exchange.getResponse();
   getRequestNotifier().notifyFailure(request, cause);
   List<Response.ResponseListener> listeners = exchange.getConversation().getResponseListeners();
   getResponseNotifier().notifyFailure(listeners, response, cause);
   getResponseNotifier().notifyComplete(listeners, new Result(request, cause, response, cause));
 }
Esempio n. 11
0
  /* (non-Javadoc)
   * @see com.sun.net.httpserver.HttpHandler#handle(com.sun.net.httpserver.HttpExchange)
   */
  @Override
  public void handle(HttpExchange exchange) throws IOException {
    Search_Params params = (Search_Params) xmlStream.fromXML(exchange.getRequestBody());
    Search_Result results = new Search_Result();

    try {
      results = ServerFacade.search(params);
    } catch (ServerException e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_INTERNAL_ERROR, -1);
      return;
    }

    exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
    xmlStream.toXML(results, exchange.getResponseBody());
    exchange.getResponseBody().close();
  }
  @Override
  public void handle(HttpExchange exchange) throws IOException {

    UpdateContact_Params params =
        (UpdateContact_Params) xmlStream.fromXML(exchange.getRequestBody());
    Contact contact = params.getContact();

    try {
      ServerFacade.updateContact(contact);
    } catch (ServerException e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_INTERNAL_ERROR, -1);
      return;
    }

    exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, -1);
  }
Esempio n. 13
0
    @Override
    public void handle(HttpExchange t) throws IOException {
      LOGGER.debug("root req " + t.getRequestURI());
      if (RemoteUtil.deny(t)) {
        throw new IOException("Access denied");
      }
      if (t.getRequestURI().getPath().contains("favicon")) {
        RemoteUtil.sendLogo(t);
        return;
      }

      HashMap<String, Object> vars = new HashMap<>();
      vars.put("serverName", configuration.getServerName());
      vars.put("profileName", configuration.getProfileName());

      String response = parent.getResources().getTemplate("start.html").execute(vars);
      RemoteUtil.respond(t, response, 200, "text/html");
    }
  /**
   * Processes a new connection making it idle or active depending on whether requests are waiting
   * to be sent.
   *
   * <p>A new connection is created when a request needs to be executed; it is possible that the
   * request that triggered the request creation is executed by another connection that was just
   * released, so the new connection may become idle.
   *
   * <p>If a request is waiting to be executed, it will be dequeued and executed by the new
   * connection.
   *
   * @param connection the new connection
   * @param dispatch whether to dispatch the processing to another thread
   */
  protected void process(Connection connection, boolean dispatch) {
    // Ugly cast, but lack of generic reification forces it
    final HttpConnection httpConnection = (HttpConnection) connection;

    final HttpExchange exchange = exchanges.poll();
    if (exchange == null) {
      LOG.debug("{} idle", httpConnection);
      if (!idleConnections.offer(httpConnection)) {
        LOG.debug("{} idle overflow");
        httpConnection.close();
      }
      if (!client.isRunning()) {
        LOG.debug("{} is stopping", client);
        remove(httpConnection);
        httpConnection.close();
      }
    } else {
      final Request request = exchange.getRequest();
      Throwable cause = request.getAbortCause();
      if (cause != null) {
        abort(exchange, cause);
        LOG.debug("Aborted before processing {}: {}", exchange, cause);
      } else {
        LOG.debug("{} active", httpConnection);
        if (!activeConnections.offer(httpConnection)) {
          LOG.warn("{} active overflow");
        }
        if (dispatch) {
          client
              .getExecutor()
              .execute(
                  new Runnable() {
                    @Override
                    public void run() {
                      httpConnection.send(exchange);
                    }
                  });
        } else {
          httpConnection.send(exchange);
        }
      }
    }
  }
Esempio n. 15
0
  @Override
  public boolean startResponse(HttpVersion version, int status, String reason) {
    if (updateState(State.IDLE, State.RECEIVE)) {
      HttpExchange exchange = connection.getExchange();
      // The exchange may be null if it failed concurrently
      if (exchange != null) {
        HttpConversation conversation = exchange.getConversation();
        HttpResponse response = exchange.getResponse();

        String method = exchange.getRequest().method();
        parser.setHeadResponse(HttpMethod.HEAD.is(method) || HttpMethod.CONNECT.is(method));
        response.version(version).status(status).reason(reason);

        // Probe the protocol handlers
        HttpClient client = connection.getHttpClient();
        ProtocolHandler protocolHandler =
            client.findProtocolHandler(exchange.getRequest(), response);
        Response.Listener handlerListener = null;
        if (protocolHandler != null) {
          handlerListener = protocolHandler.getResponseListener();
          LOG.debug("Found protocol handler {}", protocolHandler);
        }
        exchange.getConversation().updateResponseListeners(handlerListener);

        LOG.debug("Receiving {}", response);
        ResponseNotifier notifier = connection.getDestination().getResponseNotifier();
        notifier.notifyBegin(conversation.getResponseListeners(), response);
      }
    }
    return false;
  }
Esempio n. 16
0
 @Override
 public void handle(HttpExchange t) throws IOException {
   if (RemoteUtil.deny(t)) {
     throw new IOException("Access denied");
   }
   String id = RemoteUtil.getId("thumb/", t);
   LOGGER.trace("web thumb req " + id);
   if (id.contains("logo")) {
     RemoteUtil.sendLogo(t);
     return;
   }
   RootFolder root = parent.getRoot(RemoteUtil.userName(t), t);
   if (root == null) {
     LOGGER.debug("weird root in thumb req");
     throw new IOException("Unknown root");
   }
   final DLNAResource r = root.getDLNAResource(id, root.getDefaultRenderer());
   if (r == null) {
     // another error
     LOGGER.debug("media unknown");
     throw new IOException("Bad id");
   }
   InputStream in;
   if (!configuration.isShowCodeThumbs() && !r.isCodeValid(r)) {
     // we shouldn't show the thumbs for coded objects
     // unless the code is entered
     in = r.getGenericThumbnailInputStream(null);
   } else {
     r.checkThumbnail();
     in = r.getThumbnailInputStream();
   }
   Headers hdr = t.getResponseHeaders();
   hdr.add("Content-Type", r.getThumbnailContentType());
   hdr.add("Accept-Ranges", "bytes");
   hdr.add("Connection", "keep-alive");
   t.sendResponseHeaders(200, in.available());
   OutputStream os = t.getResponseBody();
   LOGGER.trace("input is {} output is {}", in, os);
   RemoteUtil.dump(in, os);
 }
Esempio n. 17
0
  @Override
  public boolean content(ByteBuffer buffer) {
    if (updateState(State.RECEIVE, State.RECEIVE)) {
      HttpExchange exchange = connection.getExchange();
      // The exchange may be null if it failed concurrently
      if (exchange != null) {
        HttpConversation conversation = exchange.getConversation();
        HttpResponse response = exchange.getResponse();
        LOG.debug("Content {}: {} bytes", response, buffer.remaining());

        ContentDecoder decoder = this.decoder;
        if (decoder != null) {
          buffer = decoder.decode(buffer);
          LOG.debug("{} {}: {} bytes", decoder, response, buffer.remaining());
        }

        ResponseNotifier notifier = connection.getDestination().getResponseNotifier();
        notifier.notifyContent(conversation.getResponseListeners(), response, buffer);
      }
    }
    return false;
  }
Esempio n. 18
0
  public void handle(HttpExchange t) throws IOException {
    // System.out.println(t.getRequestURI().toString());
    /*
     * InputStream is = t.getRequestBody(); byte[] temp = new
     * byte[is.available()]; is.read(temp); String title=new String(temp);
     */
    String title_str = t.getRequestURI().toString();
    // System.out.println("title_str:" + title_str);
    /*
     * Pattern tit_pat=Pattern.compile("\\/cate_db\\/do\\?t\\=(.*?)\\=");
     * Matcher tit_mat=tit_pat.matcher(title_str); String tt="";
     * while(tit_mat.find()) { tt=tit_mat.group(1);
     * System.out.println("title:"+tt); }
     */
    title_str = title_str.replaceFirst("/cate_tb/do\\?t=", "");
    // System.out.println("title_str:" + title_str);
    String de_title = new String(Base64.decode(title_str));
    System.out.println("de_title:" + de_title);
    String res = "";
    try {
      res = my_ewa.predict_from_seg_line(de_title);
    } catch (Exception e) {
    }
    ;
    System.out.println("res is :" + res);
    // res=res.replace("\001", "$");
    String encode_res = Base64.encodeBytes(res.getBytes());
    encode_res = encode_res.replaceAll("\\s+", "");
    System.out.println("encode_res:" + encode_res);

    String response = encode_res;
    t.sendResponseHeaders(200, response.length());
    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());
    os.close();
  }
Esempio n. 19
0
  protected boolean fail(Throwable failure) {
    HttpExchange exchange = connection.getExchange();
    // In case of a response error, the failure has already been notified
    // and it is possible that a further attempt to read in the receive
    // loop throws an exception that reenters here but without exchange;
    // or, the server could just have timed out the connection.
    if (exchange == null) return false;

    AtomicMarkableReference<Result> completion = exchange.responseComplete(failure);
    if (!completion.isMarked()) return false;

    parser.close();
    decoder = null;

    while (true) {
      State current = state.get();
      if (updateState(current, State.FAILURE)) break;
    }

    exchange.terminateResponse();

    HttpResponse response = exchange.getResponse();
    HttpConversation conversation = exchange.getConversation();
    ResponseNotifier notifier = connection.getDestination().getResponseNotifier();
    notifier.notifyFailure(conversation.getResponseListeners(), response, failure);
    LOG.debug("Failed {} {}", response, failure);

    Result result = completion.getReference();
    if (result != null) {
      connection.complete(exchange, false);

      notifier.notifyComplete(conversation.getResponseListeners(), result);
    }

    return true;
  }
Esempio n. 20
0
    @Override
    public void handle(HttpExchange t) throws IOException {
      LOGGER.debug("file req " + t.getRequestURI());

      String path = t.getRequestURI().getPath();
      String response = null;
      String mime = null;
      int status = 200;

      if (path.contains("crossdomain.xml")) {
        response =
            "<?xml version=\"1.0\"?>"
                + "<!-- http://www.bitsontherun.com/crossdomain.xml -->"
                + "<cross-domain-policy>"
                + "<allow-access-from domain=\"*\" />"
                + "</cross-domain-policy>";
        mime = "text/xml";

      } else if (path.startsWith("/files/log/")) {
        String filename = path.substring(11);
        if (filename.equals("info")) {
          String log = PMS.get().getFrame().getLog();
          log = log.replaceAll("\n", "<br>");
          String fullLink = "<br><a href=\"/files/log/full\">Full log</a><br><br>";
          String x = fullLink + log;
          if (StringUtils.isNotEmpty(log)) {
            x = x + fullLink;
          }
          response = "<html><title>UMS LOG</title><body>" + x + "</body></html>";
        } else {
          File file = parent.getResources().getFile(filename);
          if (file != null) {
            filename = file.getName();
            HashMap<String, Object> vars = new HashMap<>();
            vars.put("title", filename);
            vars.put(
                "brush",
                filename.endsWith("debug.log")
                    ? "debug_log"
                    : filename.endsWith(".log") ? "log" : "conf");
            vars.put("log", RemoteUtil.read(file).replace("<", "&lt;"));
            response = parent.getResources().getTemplate("util/log.html").execute(vars);
          } else {
            status = 404;
          }
        }
        mime = "text/html";

      } else if (parent.getResources().write(path.substring(7), t)) {
        // The resource manager found and sent the file, all done.
        return;

      } else {
        status = 404;
      }

      if (status == 404 && response == null) {
        response = "<html><body>404 - File Not Found: " + path + "</body></html>";
        mime = "text/html";
      }

      RemoteUtil.respond(t, response, status, mime);
    }
Esempio n. 21
0
 public void associate(HttpExchange t, WebRender webRenderer) {
   webRenderer.associateIP(t.getRemoteAddress().getAddress());
   webRenderer.associatePort(t.getRemoteAddress().getPort());
 }
Esempio n. 22
0
  public RootFolder getRoot(String user, boolean create, HttpExchange t) {
    String groupTag = getTag(user);
    String cookie = RemoteUtil.getCookie("UMS", t);
    RootFolder root;
    synchronized (roots) {
      root = roots.get(cookie);
      if (root == null) {
        // Double-check for cookie errors
        WebRender valid = RemoteUtil.matchRenderer(user, t);
        if (valid != null) {
          // A browser of the same type and user is already connected at
          // this ip but for some reason we didn't get a cookie match.
          RootFolder validRoot = valid.getRootFolder();
          // Do a reverse lookup to see if it's been registered
          for (Map.Entry<String, RootFolder> entry : roots.entrySet()) {
            if (entry.getValue() == validRoot) {
              // Found
              root = validRoot;
              cookie = entry.getKey();
              LOGGER.debug(
                  "Allowing browser connection without cookie match: {}: {}",
                  valid.getRendererName(),
                  t.getRemoteAddress().getAddress());
              break;
            }
          }
        }
      }

      if (!create || (root != null)) {
        t.getResponseHeaders().add("Set-Cookie", "UMS=" + cookie + ";Path=/");
        return root;
      }

      ArrayList<String> tag = new ArrayList<>();
      tag.add(user);
      if (!groupTag.equals(user)) {
        tag.add(groupTag);
      }

      tag.add(t.getRemoteAddress().getHostString());
      tag.add("web");
      root = new RootFolder(tag);
      try {
        WebRender render = new WebRender(user);
        root.setDefaultRenderer(render);
        render.setRootFolder(root);
        render.associateIP(t.getRemoteAddress().getAddress());
        render.associatePort(t.getRemoteAddress().getPort());
        if (configuration.useWebSubLang()) {
          render.setSubLang(StringUtils.join(RemoteUtil.getLangs(t), ","));
        }
        //				render.setUA(t.getRequestHeaders().getFirst("User-agent"));
        render.setBrowserInfo(
            RemoteUtil.getCookie("UMSINFO", t), t.getRequestHeaders().getFirst("User-agent"));
        PMS.get().setRendererFound(render);
      } catch (ConfigurationException e) {
        root.setDefaultRenderer(RendererConfiguration.getDefaultConf());
      }
      // root.setDefaultRenderer(RendererConfiguration.getRendererConfigurationByName("web"));
      root.discoverChildren();
      cookie = UUID.randomUUID().toString();
      t.getResponseHeaders().add("Set-Cookie", "UMS=" + cookie + ";Path=/");
      roots.put(cookie, root);
    }
    return root;
  }