コード例 #1
0
  // Process Request received
  public void processRequest(jain.protocol.ip.sip.SipEvent requestReceivedEvent) {
    Request request = (Request) requestReceivedEvent.getMessage();
    long serverTransactionId = requestReceivedEvent.getTransactionId();
    System.out.println(
        "\n\nRequest received with server transaction id " + serverTransactionId + ":\n" + request);
    try {
      // If request is not an ACK then try to send an OK Response
      if ((!Request.ACK.equals(request.getMethod()))
          && (!Request.REGISTER.equals(request.getMethod()))) {

        String body = request.getBodyAsString();
        getSipProvider().sendResponse(serverTransactionId, Response.OK, body, "application", "sdp");
      }
    } catch (TransactionDoesNotExistException e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
      System.exit(-1);
    } catch (SipParseException e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
      System.exit(-1);
    } catch (SipException e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
      System.exit(-1);
    }
    System.out.println("Completed processing request!");
  }
コード例 #2
0
  void prepareRequest(HttpURLConnection connection, Request request) throws IOException {
    // HttpURLConnection artificially restricts request method
    try {
      connection.setRequestMethod(request.getMethod());
    } catch (ProtocolException e) {
      try {
        methodField.set(connection, request.getMethod());
      } catch (IllegalAccessException e1) {
        throw RetrofitError.unexpectedError(request.getUrl(), e1);
      }
    }

    connection.setDoInput(true);

    for (Header header : request.getHeaders()) {
      connection.addRequestProperty(header.getName(), header.getValue());
    }

    TypedOutput body = request.getBody();
    if (body != null) {
      connection.setDoOutput(true);
      connection.addRequestProperty("Content-Type", body.mimeType());
      long length = body.length();
      if (length != -1) {
        connection.setFixedLengthStreamingMode((int) length);
        connection.addRequestProperty("Content-Length", String.valueOf(length));
      } else {
        connection.setChunkedStreamingMode(CHUNK_SIZE);
      }
      body.writeTo(connection.getOutputStream());
    }
  }
コード例 #3
0
  /**
   * Place to put some hacks if needed on incoming requests.
   *
   * @param event the incoming request event.
   * @return status <code>true</code> if we don't need to process this message, just discard it and
   *     <code>false</code> otherwise.
   */
  private boolean applyNonConformanceHacks(RequestEvent event) {
    Request request = event.getRequest();
    try {
      /*
       * Max-Forwards is required, yet there are UAs which do not
       * place it. SipProvider#getNewServerTransaction(Request)
       * will throw an exception in the case of a missing
       * Max-Forwards header and this method will eventually just
       * log it thus ignoring the whole event.
       */
      if (request.getHeader(MaxForwardsHeader.NAME) == null) {
        // it appears that some buggy providers do send requests
        // with no Max-Forwards headers, as we are at application level
        // and we know there will be no endless loops
        // there is no problem of adding headers and process normally
        // this messages
        MaxForwardsHeader maxForwards =
            SipFactory.getInstance().createHeaderFactory().createMaxForwardsHeader(70);
        request.setHeader(maxForwards);
      }
    } catch (Throwable ex) {
      logger.warn("Cannot apply incoming request modification!", ex);
    }

    try {
      // using asterisk voice mail initial notify for messages
      // is ok, but on the fly received messages their notify comes
      // without subscription-state, so we add it in order to be able to
      // process message.
      if (request.getMethod().equals(Request.NOTIFY)
          && request.getHeader(EventHeader.NAME) != null
          && ((EventHeader) request.getHeader(EventHeader.NAME))
              .getEventType()
              .equals(OperationSetMessageWaitingSipImpl.EVENT_PACKAGE)
          && request.getHeader(SubscriptionStateHeader.NAME) == null) {
        request.addHeader(
            new HeaderFactoryImpl().createSubscriptionStateHeader(SubscriptionStateHeader.ACTIVE));
      }
    } catch (Throwable ex) {
      logger.warn("Cannot apply incoming request modification!", ex);
    }

    try {
      // receiving notify message without subscription state
      // used for keep-alive pings, they have done their job
      // and are no more need. Skip processing them to avoid
      // filling logs with unneeded exceptions.
      if (request.getMethod().equals(Request.NOTIFY)
          && request.getHeader(SubscriptionStateHeader.NAME) == null) {
        return true;
      }
    } catch (Throwable ex) {
      logger.warn("Cannot apply incoming request modification!", ex);
    }

    return false;
  }
コード例 #4
0
ファイル: Shootist.java プロジェクト: ahmedomarjee/jain-sip
  public void processRequest(RequestEvent requestReceivedEvent) {
    Request request = requestReceivedEvent.getRequest();
    ServerTransaction serverTransactionId = requestReceivedEvent.getServerTransaction();

    System.out.println(
        "\n\nRequest "
            + request.getMethod()
            + " received at "
            + sipStack.getStackName()
            + " with server transaction id "
            + serverTransactionId);

    // We are the UAC so the only request we get is the BYE.
    if (request.getMethod().equals(Request.BYE)) processBye(request, serverTransactionId);
  }
コード例 #5
0
 public RequestImpl(Request prototype) {
   if (prototype != null) {
     this.method = prototype.getMethod();
     this.originalUri = prototype.getOriginalURI();
     this.address = prototype.getInetAddress();
     this.localAddress = prototype.getLocalAddress();
     this.headers = new FluentCaseInsensitiveStringsMap(prototype.getHeaders());
     this.cookies = new ArrayList<Cookie>(prototype.getCookies());
     this.byteData = prototype.getByteData();
     this.stringData = prototype.getStringData();
     this.streamData = prototype.getStreamData();
     this.bodyGenerator = prototype.getBodyGenerator();
     this.params =
         (prototype.getParams() == null ? null : new FluentStringsMap(prototype.getParams()));
     this.queryParams =
         (prototype.getQueryParams() == null
             ? null
             : new FluentStringsMap(prototype.getQueryParams()));
     this.parts =
         (prototype.getParts() == null ? null : new ArrayList<Part>(prototype.getParts()));
     this.virtualHost = prototype.getVirtualHost();
     this.length = prototype.getContentLength();
     this.proxyServer = prototype.getProxyServer();
     this.realm = prototype.getRealm();
     this.file = prototype.getFile();
     this.followRedirects =
         prototype.isRedirectOverrideSet() ? prototype.isRedirectEnabled() : null;
     this.requestTimeoutInMs = prototype.getRequestTimeoutInMs();
     this.rangeOffset = prototype.getRangeOffset();
     this.charset = prototype.getBodyEncoding();
     this.useRawUrl = prototype.isUseRawUrl();
     this.connectionPoolKeyStrategy = prototype.getConnectionPoolKeyStrategy();
   }
 }
コード例 #6
0
 private static void addBodyIfPostOrPut(HttpRequest httpRequest, ResponseDefinition response)
     throws UnsupportedEncodingException {
   Request originalRequest = response.getOriginalRequest();
   if (originalRequest.getMethod().isOneOf(PUT, POST)) {
     HttpEntityEnclosingRequest requestWithEntity = (HttpEntityEnclosingRequest) httpRequest;
     requestWithEntity.setEntity(buildEntityFrom(originalRequest));
   }
 }
コード例 #7
0
  /**
   * Creates an invite request using the Tested Implementation and then tests creating a cancel for
   * the same invite request.
   */
  public void testCreateCancel() {
    try {
      Request invite = createTiInviteRequest(null, null, null);
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
      } catch (TransactionUnavailableException exc) {
        throw new TiUnexpectedError(
            "A TransactionUnavailableException was thrown while trying to "
                + "create a new client transaction",
            exc);
      }
      Request cancel = null;
      try {
        cancel = tran.createCancel();
      } catch (SipException ex) {
        ex.printStackTrace();
        fail("Failed to create cancel request!");
      }
      assertEquals(
          "The created request did not have a CANCEL method.", cancel.getMethod(), Request.CANCEL);
      assertEquals(
          "Request-URIs of the original and the cancel request do not match",
          cancel.getRequestURI(),
          invite.getRequestURI());
      assertEquals(
          "Call-IDs of the original and the cancel request do not match",
          cancel.getHeader(CallIdHeader.NAME),
          invite.getHeader(CallIdHeader.NAME));
      assertEquals(
          "ToHeaders of the original and the cancel request do not match",
          cancel.getHeader(ToHeader.NAME),
          invite.getHeader(ToHeader.NAME));
      assertTrue(
          "The CSeqHeader's sequence number of the original and "
              + "the cancel request do not match",
          ((CSeqHeader) cancel.getHeader(CSeqHeader.NAME)).getSequenceNumber()
              == ((CSeqHeader) invite.getHeader(CSeqHeader.NAME)).getSequenceNumber());
      assertEquals(
          "The CSeqHeader's method of the cancel request was not CANCEL",
          ((CSeqHeader) cancel.getHeader(CSeqHeader.NAME)).getMethod(),
          Request.CANCEL);
      assertTrue(
          "There was no ViaHeader in the cancel request",
          cancel.getHeaders(ViaHeader.NAME).hasNext());
      Iterator cancelVias = cancel.getHeaders(ViaHeader.NAME);
      ViaHeader cancelVia = ((ViaHeader) cancelVias.next());
      ViaHeader inviteVia = ((ViaHeader) invite.getHeaders(ViaHeader.NAME).next());
      assertEquals(
          "ViaHeaders of the original and the cancel request do not match!", cancelVia, inviteVia);
      assertFalse("Cancel request had more than one ViaHeader.", cancelVias.hasNext());
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
コード例 #8
0
ファイル: Shootme.java プロジェクト: ahmedomarjee/jain-sip
  public void processRequest(RequestEvent requestEvent) {
    Request request = requestEvent.getRequest();
    ServerTransaction serverTransactionId = requestEvent.getServerTransaction();

    /*
     * System.out.println("\n\nRequest " + request.getMethod() + "
     * received at " + sipStack.getStackName() + " with server
     * transaction id " + serverTransactionId);
     */

    if (request.getMethod().equals(Request.INVITE)) {
      processInvite(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.ACK)) {
      processAck(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.BYE)) {
      processBye(requestEvent, serverTransactionId);
    }
  }
コード例 #9
0
 @Test
 public void testRequestBuilder() {
   Request request = createRequest();
   assertEquals(request.getMethod(), "GET");
   assertEquals(request.getBodyGenerator(), NULL_BODY_GENERATOR);
   assertEquals(request.getUri(), URI.create("http://example.com"));
   assertEquals(
       request.getHeaders(),
       ImmutableListMultimap.of("newheader", "withvalue", "anotherheader", "anothervalue"));
 }
コード例 #10
0
ファイル: CorsEngine.java プロジェクト: ggalmazor/jfry
 public boolean isAllowed(Request request) {
   return isAnyOriginAllowed()
       || request
           .getHeader(ORIGIN_HEADER)
           .map(
               origin ->
                   allowedMethods.contains(request.getMethod())
                       && (isAnyOriginAllowed() || allowedOrigins.contains(origin)))
           .getOrElse(false);
 }
コード例 #11
0
ファイル: SipTPCCallAgent.java プロジェクト: hj91/Openfire
  /**
   * Processes SIP requests. The only request being handled is BYE.
   *
   * @param requestReceivedEvent the event containing the SIP request
   */
  public synchronized void processRequest(RequestEvent requestReceivedEvent) {

    // obtain request and transaction id
    Request request = requestReceivedEvent.getRequest();

    ServerTransaction st = requestReceivedEvent.getServerTransaction();

    if (request.getMethod().equals(Request.BYE)) {
      handleBye(request, st);
    } else if (request.getMethod().equals(Request.INVITE)) {
      /*
       * This is a re-Invite
       */
      handleReInvite(request, st);
    } else if (request.getMethod().equals(Request.ACK)) {
      Logger.println("Call " + cp + " got ACK");
    } else {
      // no other requests should come in other than BYE, INVITE or ACK
      Logger.writeFile("Call " + cp + " ignoring request " + request.getMethod());
    }
  }
コード例 #12
0
ファイル: Shootme.java プロジェクト: jiafu1115/jain-sip-1
  public void processRequest(RequestEvent requestEvent) {
    Request request = requestEvent.getRequest();
    ServerTransaction serverTransactionId = requestEvent.getServerTransaction();

    logger.info(
        "\n\nRequest "
            + request.getMethod()
            + " received at "
            + protocolObjects.sipStack.getStackName()
            + " with server transaction id "
            + serverTransactionId);

    if (request.getMethod().equals(Request.INVITE)) {
      processInvite(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.ACK)) {
      processAck(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.BYE)) {
      processBye(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.CANCEL)) {
      processCancel(requestEvent, serverTransactionId);
    }
  }
コード例 #13
0
ファイル: B2BUA.java プロジェクト: ahmedomarjee/jain-sip
  public void processRequest(RequestEvent requestEvent) {
    Request request = requestEvent.getRequest();
    ServerTransaction serverTransactionId = requestEvent.getServerTransaction();

    System.out.println(
        "\n\nRequest "
            + request.getMethod()
            + " received at "
            + sipStack.getStackName()
            + " with server transaction id "
            + serverTransactionId);

    if (request.getMethod().equals(Request.INVITE)) {
      processInvite(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.ACK)) {
      processAck(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.CANCEL)) {
      processCancel(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.REGISTER)) {
      processRegister(requestEvent, serverTransactionId);
    } else {
      processInDialogRequest(requestEvent, serverTransactionId);
    }
  }
コード例 #14
0
ファイル: LoginPage.java プロジェクト: saces/Sone
 /** {@inheritDoc} */
 @Override
 protected void processTemplate(Request request, Template template) throws RedirectException {
   super.processTemplate(request, template);
   /* get all own identities. */
   List<Sone> localSones = new ArrayList<Sone>(webInterface.getCore().getLocalSones());
   Collections.sort(localSones, Sone.NICE_NAME_COMPARATOR);
   template.set("sones", localSones);
   if (request.getMethod() == Method.POST) {
     String soneId = request.getHttpRequest().getPartAsStringFailsafe("sone-id", 100);
     Sone selectedSone = webInterface.getCore().getLocalSone(soneId, false);
     if (selectedSone != null) {
       setCurrentSone(request.getToadletContext(), selectedSone);
       throw new RedirectException("index.html");
     }
   }
   List<OwnIdentity> ownIdentitiesWithoutSone =
       CreateSonePage.getOwnIdentitiesWithoutSone(webInterface.getCore());
   template.set("identitiesWithoutSone", ownIdentitiesWithoutSone);
 }
コード例 #15
0
  void prepareRequest(HttpURLConnection connection, Request request) throws IOException {
    connection.setRequestMethod(request.getMethod());
    connection.setDoInput(true);

    for (Header header : request.getHeaders()) {
      connection.addRequestProperty(header.getName(), header.getValue());
    }

    TypedOutput body = request.getBody();
    if (body != null) {
      connection.setDoOutput(true);
      connection.addRequestProperty("Content-Type", body.mimeType());
      long length = body.length();
      if (length != -1) {
        connection.setFixedLengthStreamingMode((int) length);
        connection.addRequestProperty("Content-Length", String.valueOf(length));
      } else {
        connection.setChunkedStreamingMode(CHUNK_SIZE);
      }
      body.writeTo(connection.getOutputStream());
    }
  }
コード例 #16
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

    // TODO test for redirect
    // no redirect; process the request

    // create Request, Response objects
    RequestResponseFactory requestResponseFactory = application.getRequestResponseFactory();
    Response response = requestResponseFactory.createResponse(httpServletResponse);
    Request request = requestResponseFactory.createRequest(httpServletRequest, response);

    // create a URI to automatically decode the path
    URI uri = URI.create(httpServletRequest.getRequestURL().toString());
    String requestUri = uri.getPath();
    String requestPath = request.getPath();

    log.trace("The relative path for '{}' is '{}'", requestUri, requestPath);

    // check for ignore path
    if (shouldIgnorePath(requestPath)) {
      log.debug("Ignoring request '{}'", requestPath);
      if (chain != null) {
        chain.doFilter(servletRequest, servletResponse);
      }

      return;
    }

    log.debug("Request {} '{}'", request.getMethod(), requestPath);

    // dispatch route(s)
    routeDispatcher.dispatch(request, response);
  }
コード例 #17
0
ファイル: LockHandler.java プロジェクト: yug64/milton2
  protected void processExistingResource(
      HttpManager manager, Request request, Response response, Resource resource)
      throws NotAuthorizedException {
    if (handlerHelper.isNotCompatible(resource, request.getMethod()) || !isCompatible(resource)) {
      responseHandler.respondMethodNotImplemented(resource, response, request);
      return;
    }
    if (!handlerHelper.checkAuthorisation(manager, resource, request)) {
      responseHandler.respondUnauthorised(resource, response, request);
      return;
    }

    handlerHelper.checkExpects(responseHandler, request, response);

    LockableResource r = (LockableResource) resource;
    LockTimeout timeout = LockTimeout.parseTimeout(request);
    String ifHeader = request.getIfHeader();
    response.setContentTypeHeader(Response.XML);
    if (ifHeader == null || ifHeader.length() == 0) {
      processNewLock(manager, request, response, r, timeout);
    } else {
      processRefresh(manager, request, response, r, timeout, ifHeader);
    }
  }
コード例 #18
0
ファイル: B2BUA.java プロジェクト: ahmedomarjee/jain-sip
  /** Process the any in dialog request - MESSAGE, BYE, INFO, UPDATE. */
  public void processInDialogRequest(
      RequestEvent requestEvent, ServerTransaction serverTransactionId) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    Dialog dialog = requestEvent.getDialog();
    System.out.println("local party = " + dialog.getLocalParty());
    try {
      System.out.println("b2bua:  got a bye sending OK.");
      Response response = messageFactory.createResponse(200, request);
      serverTransactionId.sendResponse(response);
      System.out.println("Dialog State is " + serverTransactionId.getDialog().getState());

      Dialog otherLeg = (Dialog) dialog.getApplicationData();
      Request otherBye = otherLeg.createRequest(request.getMethod());
      ClientTransaction clientTransaction = sipProvider.getNewClientTransaction(otherBye);
      clientTransaction.setApplicationData(serverTransactionId);
      serverTransactionId.setApplicationData(clientTransaction);
      otherLeg.sendRequest(clientTransaction);

    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
コード例 #19
0
ファイル: CorsEngine.java プロジェクト: ggalmazor/jfry
 public boolean isPreflight(Request request) {
   return request.getMethod() == HttpMethod.OPTIONS
       && request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER).isDefined();
 }
コード例 #20
0
ファイル: RedirectionModule.java プロジェクト: aheritier/ws
  /** Invoked by the HTTPClient. */
  public int responsePhase2Handler(Response resp, Request req) throws IOException {
    /* handle various response status codes until satisfied */

    int sts = resp.getStatusCode();
    switch (sts) {
      case 302: // General (temporary) Redirection (handle like 303)

        /*
         * Note we only do this munging for POST and PUT. For GET it's not
         * necessary; for HEAD we probably want to do another HEAD. For all
         * others (i.e. methods from WebDAV, IPP, etc) it's somewhat unclear -
         * servers supporting those should really return a 307 or 303, but some
         * don't (guess who...), so we just don't touch those.
         */
        if (req.getMethod().equals("POST") || req.getMethod().equals("PUT")) {
          if (LOG.isDebugEnabled())
            LOG.debug(
                "Received status: " + sts + " " + resp.getReasonLine() + " - treating as 303");

          sts = 303;
        }

      case 301: // Moved Permanently
      case 303: // See Other (use GET)
      case 307: // Moved Temporarily (we mean it!)
        if (LOG.isDebugEnabled()) LOG.debug("Handling status: " + sts + " " + resp.getReasonLine());

        // the spec says automatic redirection may only be done if
        // the second request is a HEAD or GET.
        if (!req.getMethod().equals("GET") && !req.getMethod().equals("HEAD") && sts != 303) {
          if (LOG.isDebugEnabled())
            LOG.debug("Not redirected because method is neither HEAD nor GET");

          if (sts == 301 && resp.getHeader("Location") != null)
            update_perm_redir_list(req, resLocHdr(resp.getHeader("Location"), req));

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }

      case 305: // Use Proxy
      case 306: // Switch Proxy
        if (sts == 305 || sts == 306) {
          if (LOG.isDebugEnabled())
            LOG.debug("Handling status: " + sts + " " + resp.getReasonLine());
        }

        // Don't accept 305 from a proxy
        if (sts == 305 && req.getConnection().getProxyHost() != null) {
          if (LOG.isDebugEnabled()) LOG.debug("305 ignored because a proxy is already in use");

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }

        /*
         * the level is a primitive way of preventing infinite redirections.
         * RFC-2068 set the max to 5, but RFC-2616 has loosened this. Since some
         * sites (notably M$) need more levels, this is now set to the
         * (arbitrary) value of 15 (god only knows why they need to do even 5
         * redirections...).
         */
        if (level >= 15 || resp.getHeader("Location") == null) {
          if (LOG.isDebugEnabled()) {
            if (level >= 15) LOG.debug("Not redirected because of too many levels of redirection");
            else LOG.debug("Not redirected because no Location header was present");
          }

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }
        level++;

        URI loc = resLocHdr(resp.getHeader("Location"), req);

        HTTPConnection mvd;
        String nres;
        new_con = false;

        if (sts == 305) {
          mvd =
              new HTTPConnection(
                  req.getConnection().getProtocol(),
                  req.getConnection().getHost(),
                  req.getConnection().getPort());
          mvd.setCurrentProxy(loc.getHost(), loc.getPort());
          mvd.setContext(req.getConnection().getContext());
          new_con = true;

          nres = req.getRequestURI();

          /*
           * There was some discussion about this, and especially Foteos
           * Macrides (Lynx) said a 305 should also imply a change to GET (for
           * security reasons) - see the thread starting at
           * http://www.ics.uci.edu/pub/ietf/http/hypermail/1997q4/0351.html
           * However, this is not in the latest draft, but since I agree with
           * Foteos we do it anyway...
           */
          req.setMethod("GET");
          req.setData(null);
          req.setStream(null);
        } else if (sts == 306) {
          // We'll have to wait for Josh to create a new spec here.
          return RSP_CONTINUE;
        } else {
          if (req.getConnection().isCompatibleWith(loc)) {
            mvd = req.getConnection();
            nres = loc.getPathAndQuery();
          } else {
            try {
              mvd = new HTTPConnection(loc);
              nres = loc.getPathAndQuery();
            } catch (ProtocolNotSuppException e) {
              if (req.getConnection().getProxyHost() == null
                  || !loc.getScheme().equalsIgnoreCase("ftp")) return RSP_CONTINUE;

              // We're using a proxy and the protocol is ftp -
              // maybe the proxy will also proxy ftp...
              mvd =
                  new HTTPConnection(
                      "http",
                      req.getConnection().getProxyHost(),
                      req.getConnection().getProxyPort());
              mvd.setCurrentProxy(null, 0);
              nres = loc.toExternalForm();
            }

            mvd.setContext(req.getConnection().getContext());
            new_con = true;
          }

          /*
           * copy query if present in old url but not in new url. This isn't
           * strictly conforming, but some scripts fail to propagate the query
           * properly to the Location header. See comment on line 126. String
           * oquery = Util.getQuery(req.getRequestURI()), nquery =
           * Util.getQuery(nres); if (nquery == null && oquery != null) nres +=
           * "?" + oquery;
           */

          if (sts == 303) {
            // 303 means "use GET"

            if (!req.getMethod().equals("HEAD")) req.setMethod("GET");
            req.setData(null);
            req.setStream(null);
          } else {
            // If they used an output stream then they'll have
            // to do the resend themselves
            if (req.getStream() != null) {
              if (!HTTPConnection.deferStreamed) {
                if (LOG.isDebugEnabled())
                  LOG.debug("Status " + sts + " not handled - request has an output stream");

                return RSP_CONTINUE;
              }

              saved_req = (Request) req.clone();
              deferred_redir_list.put(req.getStream(), this);
              req.getStream().reset();
              resp.setRetryRequest(true);
            }

            if (sts == 301) {
              // update permanent redirection list
              try {
                update_perm_redir_list(req, new URI(loc, nres));
              } catch (ParseException pe) {
                throw new Error(
                    "HTTPClient Internal Error: " + "unexpected exception '" + pe + "'", pe);
              }
            }
          }

          // Adjust Referer, if present
          NVPair[] hdrs = req.getHeaders();
          for (int idx = 0; idx < hdrs.length; idx++)
            if (hdrs[idx].getName().equalsIgnoreCase("Referer")) {
              HTTPConnection con = req.getConnection();
              hdrs[idx] = new NVPair("Referer", con + req.getRequestURI());
              break;
            }
        }

        req.setConnection(mvd);
        req.setRequestURI(nres);

        try {
          resp.getInputStream().close();
        } catch (IOException ioe) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + ioe.getMessage());
          }
        }

        if (sts != 305 && sts != 306) {
          try {
            lastURI = new URI(loc, nres);
          } catch (ParseException pe) {
            if (LOG.isTraceEnabled()) {
              LOG.trace("An exception occurred: " + pe.getMessage());
            }
          }

          if (LOG.isDebugEnabled())
            LOG.debug(
                "Request redirected to "
                    + lastURI.toExternalForm()
                    + " using method "
                    + req.getMethod());
        } else {
          if (LOG.isDebugEnabled())
            LOG.debug(
                "Resending request using "
                    + "proxy "
                    + mvd.getProxyHost()
                    + ":"
                    + mvd.getProxyPort());
        }

        if (req.getStream() != null) return RSP_CONTINUE;
        else if (new_con) return RSP_NEWCON_REQ;
        else return RSP_REQUEST;

      default:
        return RSP_CONTINUE;
    }
  }
コード例 #21
0
  /**
   * Normally sets the path and a few attributes that the JSPs are likely to need. Also verifies the
   * login information. If necessary, just redirects to the login page.
   *
   * @param target
   * @param request
   * @param httpServletResponse
   * @param secured
   * @return true if the request is already handled so the .jsp shouldn't get called
   * @throws Exception
   */
  private boolean prepareForJspGet(
      String target, Request request, HttpServletResponse httpServletResponse, boolean secured)
      throws Exception {

    LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request);

    LOG.info(
        String.format(
            "hndl - %s ; %s; %s ; %s",
            target,
            request.getPathInfo(),
            request.getMethod(),
            secured ? "secured" : "not secured"));

    String path = request.getUri().getDecodedPath();

    boolean redirectToLogin = path.equals(PATH_LOGOUT);
    LoginInfo loginInfo = null;
    if (sessionInfo.isNull()) {
      redirectToLogin = true;
      LOG.info("Null session info. Logging in again.");
    } else {
      loginInfo =
          loginInfoDb.get(
              sessionInfo.browserId,
              sessionInfo.sessionId); // ttt2 use a cache, to avoid going to DB
      if (loginInfo == null || loginInfo.expiresOn < System.currentTimeMillis()) {
        LOG.info("Session has expired. Logging in again. Info: " + loginInfo);
        redirectToLogin = true;
      }
    }

    if (!path.equals(PATH_LOGIN) && !path.equals(PATH_SIGNUP) && !path.equals(PATH_ERROR)) {

      if (redirectToLogin) {
        // ttt2 perhaps store URI, to return to it after login
        logOut(sessionInfo.browserId);
        addLoginParams(request, loginInfo);
        httpServletResponse.sendRedirect(PATH_LOGIN);
        return true;
      }

      User user = userDb.get(loginInfo.userId);
      if (user == null) {
        WebUtils.redirectToError("Unknown user", request, httpServletResponse);
        return true;
      }
      if (!user.active) {
        WebUtils.redirectToError("Account is not active", request, httpServletResponse);
        return true;
      }
      request.setAttribute(VAR_FEED_DB, feedDb);
      request.setAttribute(VAR_USER_DB, userDb);
      request.setAttribute(VAR_ARTICLE_DB, articleDb);
      request.setAttribute(VAR_READ_ARTICLES_COLL_DB, readArticlesCollDb);

      request.setAttribute(VAR_USER, user);
      request.setAttribute(VAR_LOGIN_INFO, loginInfo);

      MultiMap<String> params = new MultiMap<>();
      params.put(PARAM_PATH, path);
      request.setParameters(params);
    }

    if (path.equals(PATH_LOGIN)) {
      addLoginParams(request, loginInfo);
    }
    return false;
  }
コード例 #22
0
  /** Tests creating of ACK requests. */
  public void testCreateAck() {
    try {
      // 1. Create and send the original request

      Request invite = createTiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
        eventCollector.collectRequestEvent(riSipProvider);
        tran.sendRequest();
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        if (receivedRequestEvent == null || receivedRequestEvent.getRequest() == null)
          throw new TiUnexpectedError("The sent request was not received by the RI!");
      } catch (TooManyListenersException ex) {
        throw new TckInternalError(
            "A TooManyListenersException was thrown while trying to add "
                + "a SipListener to an RI SipProvider.",
            ex);
      } catch (SipException ex) {
        throw new TiUnexpectedError("The TI failed to send the request!", ex);
      }
      Request receivedRequest = receivedRequestEvent.getRequest();
      // 2. Create and send the response
      Response ok = null;
      try {
        ok = riMessageFactory.createResponse(Response.OK, receivedRequest);
      } catch (ParseException ex) {
        throw new TckInternalError("Failed to create an OK response!", ex);
      }
      // Send the response using the RI and collect using TI
      try {
        eventCollector.collectResponseEvent(tiSipProvider);
      } catch (TooManyListenersException ex) {
        throw new TiUnexpectedError("Error while trying to add riSipProvider");
      }
      try {
        riSipProvider.sendResponse(ok);
      } catch (SipException ex) {
        throw new TckInternalError("Could not send back the response", ex);
      }
      waitForMessage();
      ResponseEvent responseEvent = eventCollector.extractCollectedResponseEvent();
      // 3. Now let's create the ack
      if (responseEvent == null || responseEvent.getResponse() == null)
        throw new TiUnexpectedError("The TI failed to receive the response!");
      if (responseEvent.getClientTransaction() != tran)
        throw new TiUnexpectedError(
            "The TI has associated a new ClientTransaction to a response "
                + "instead of using existing one!");
      Request ack = null;
      try {
        ack = tran.createAck();
      } catch (SipException ex) {
        ex.printStackTrace();
        fail("A SipException was thrown while creating an ack request");
      }
      assertNotNull("ClientTransaction.createAck returned null!", ack);
      assertEquals(
          "The created request did not have a CANCEL method.", ack.getMethod(), Request.ACK);
      assertEquals(
          "Request-URIs of the original and the ack request do not match",
          ack.getRequestURI(),
          invite.getRequestURI());
      assertEquals(
          "Call-IDs of the original and the ack request do not match",
          ack.getHeader(CallIdHeader.NAME),
          invite.getHeader(CallIdHeader.NAME));
      assertEquals(
          "ToHeaders of the original and the ack request do not match",
          ack.getHeader(ToHeader.NAME),
          invite.getHeader(ToHeader.NAME));
      assertTrue(
          "The CSeqHeader's sequence number of the original and " + "the ack request do not match",
          ((CSeqHeader) ack.getHeader(CSeqHeader.NAME)).getSequenceNumber()
              == ((CSeqHeader) invite.getHeader(CSeqHeader.NAME)).getSequenceNumber());
      assertEquals(
          "The CSeqHeader's method of the ack request was not ACK",
          ((CSeqHeader) ack.getHeader(CSeqHeader.NAME)).getMethod(),
          Request.ACK);
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
コード例 #23
0
 @Override
 public String getRequestMethod() {
   return request.getMethod().getName();
 }
コード例 #24
0
  /**
   * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one of our "candidate
   * recipient" listeners.
   *
   * @param event the event received for a <tt>SipProvider</tt>.
   */
  public void processRequest(RequestEvent event) {
    try {
      Request request = event.getRequest();
      if (logger.isTraceEnabled()) logger.trace("received request: " + request.getMethod());

      /*
       * Create the transaction if it doesn't exist yet. If it is a
       * dialog-creating request, the dialog will also be automatically
       * created by the stack.
       */
      if (event.getServerTransaction() == null) {
        try {
          // apply some hacks if needed on incoming request
          // to be compliant with some servers/clients
          // if needed stop further processing.
          if (applyNonConformanceHacks(event)) return;

          SipProvider source = (SipProvider) event.getSource();
          ServerTransaction transaction = source.getNewServerTransaction(request);

          /*
           * Update the event, otherwise getServerTransaction() and
           * getDialog() will still return their previous value.
           */
          event = new RequestEvent(source, transaction, transaction.getDialog(), request);
        } catch (SipException ex) {
          logger.error(
              "couldn't create transaction, please report "
                  + "this to [email protected]",
              ex);
        }
      }

      ProtocolProviderServiceSipImpl service = getServiceData(event.getServerTransaction());
      if (service != null) {
        service.processRequest(event);
      } else {
        service = findTargetFor(request);
        if (service == null) {
          logger.error("couldn't find a ProtocolProviderServiceSipImpl " + "to dispatch to");
          if (event.getServerTransaction() != null) event.getServerTransaction().terminate();
        } else {

          /*
           * Mark the dialog for the dispatching of later in-dialog
           * requests. If there is no dialog, we need to mark the
           * request to dispatch a possible timeout when sending the
           * response.
           */
          Object container = event.getDialog();
          if (container == null) container = request;
          SipApplicationData.setApplicationData(container, SipApplicationData.KEY_SERVICE, service);

          service.processRequest(event);
        }
      }
    } catch (Throwable exc) {

      /*
       * Any exception thrown within our code should be caught here so
       * that we could log it rather than interrupt stack activity with
       * it.
       */
      this.logApplicationException(DialogTerminatedEvent.class, exc);

      // Unfortunately, death can hardly be ignored.
      if (exc instanceof ThreadDeath) throw (ThreadDeath) exc;
    }
  }
コード例 #25
0
ファイル: ConfigHeaders.java プロジェクト: vincentlao/jitsi
  /**
   * Attach any custom headers pre configured for the account. Added only to message Requests. The
   * header account properties are of form: ConfigHeader.N.Name=HeaderName
   * ConfigHeader.N.Value=HeaderValue ConfigHeader.N.Method=SIP_MethodName (optional) Where N is the
   * index of the header, multiple custom headers can be added. Name is the header name to use and
   * Value is its value. The optional property is whether to use a specific request method to attach
   * headers to or if missing we will attach it to all requests.
   *
   * @param message the message that we'd like to attach custom headers to.
   * @param protocolProvider the protocol provider to check for configured custom headers.
   */
  static void attachConfigHeaders(
      Message message, ProtocolProviderServiceSipImpl protocolProvider) {
    if (message instanceof Response) return;

    Request request = (Request) message;

    Map<String, String> props = protocolProvider.getAccountID().getAccountProperties();

    Map<String, Map<String, String>> headers = new HashMap<String, Map<String, String>>();

    // parse the properties into the map where the index is the key
    for (Map.Entry<String, String> entry : props.entrySet()) {
      String pName = entry.getKey();
      String prefStr = entry.getValue();
      String name;
      String ix;

      if (!pName.startsWith(ACC_PROPERTY_CONFIG_HEADER) || prefStr == null) continue;

      prefStr = prefStr.trim();

      if (pName.contains(".")) {
        pName = pName.replaceAll(ACC_PROPERTY_CONFIG_HEADER + ".", "");
        name = pName.substring(pName.lastIndexOf('.') + 1).trim();

        if (!pName.contains(".")) continue;

        ix = pName.substring(0, pName.lastIndexOf('.')).trim();
      } else continue;

      Map<String, String> headerValues = headers.get(ix);

      if (headerValues == null) {
        headerValues = new HashMap<String, String>();
        headers.put(ix, headerValues);
      }

      headerValues.put(name, prefStr);
    }

    // process the found custom headers
    for (Map<String, String> headerValues : headers.values()) {
      String method = headerValues.get(ACC_PROPERTY_CONFIG_HEADER_METHOD);

      // if there is a method setting and is different from
      // current request method skip this header
      // if any of the required properties are missing skip (Name & Value)
      if ((method != null && !request.getMethod().equalsIgnoreCase(method))
          || !headerValues.containsKey(ACC_PROPERTY_CONFIG_HEADER_NAME)
          || !headerValues.containsKey(ACC_PROPERTY_CONFIG_HEADER_VALUE)) continue;

      try {
        String name = headerValues.get(ACC_PROPERTY_CONFIG_HEADER_NAME);
        String value = processParams(headerValues.get(ACC_PROPERTY_CONFIG_HEADER_VALUE), request);

        Header h = request.getHeader(name);

        // makes possible overriding already created headers which
        // are not custom one
        // RouteHeader is used by ProxyRouter/DefaultRouter and we
        // cannot use it as custom header if we want to add it
        if ((h != null && !(h instanceof CustomHeader)) || name.equals(SIPHeaderNames.ROUTE)) {
          request.setHeader(protocolProvider.getHeaderFactory().createHeader(name, value));
        } else request.addHeader(new CustomHeaderList(name, value));
      } catch (Exception e) {
        logger.error("Cannot create custom header", e);
      }
    }
  }
コード例 #26
0
ファイル: RetryModule.java プロジェクト: hotydjer/Jarsync
  /** Invoked by the HTTPClient. */
  public void responsePhase1Handler(Response resp, RoRequest roreq)
      throws IOException, ModuleException {
    try {
      resp.getStatusCode();
    } catch (RetryException re) {
      Log.write(Log.MODS, "RtryM: Caught RetryException");

      boolean got_lock = false;

      try {
        synchronized (re.first) {
          got_lock = true;

          // initialize idempotent sequence checking
          IdempotentSequence seq = new IdempotentSequence();
          for (RetryException e = re.first; e != null; e = e.next) seq.add(e.request);

          for (RetryException e = re.first; e != null; e = e.next) {
            Log.write(Log.MODS, "RtryM: handling exception ", e);

            Request req = e.request;
            HTTPConnection con = req.getConnection();

            /* Don't retry if either the sequence is not idempotent
             * (Sec 8.1.4 and 9.1.2), or we've already retried enough
             * times, or the headers have been read and parsed
             * already
             */
            if (!seq.isIdempotent(req)
                || (con.ServProtVersKnown
                    && con.ServerProtocolVersion >= HTTP_1_1
                    && req.num_retries > 0)
                || ((!con.ServProtVersKnown || con.ServerProtocolVersion <= HTTP_1_0)
                    && req.num_retries > 4)
                || e.response.got_headers) {
              e.first = null;
              continue;
            }

            /**
             * if an output stream was used (i.e. we don't have the data to resend) then delegate
             * the responsibility for resending to the application.
             */
            if (req.getStream() != null) {
              if (HTTPConnection.deferStreamed) {
                req.getStream().reset();
                e.response.setRetryRequest(true);
              }
              e.first = null;
              continue;
            }

            /* If we have an entity then setup either the entity-delay
             * or the Expect header
             */
            if (req.getData() != null && e.conn_reset) {
              if (con.ServProtVersKnown && con.ServerProtocolVersion >= HTTP_1_1)
                addToken(req, "Expect", "100-continue");
              else req.delay_entity = 5000L << req.num_retries;
            }

            /* If the next request in line has an entity and we're
             * talking to an HTTP/1.0 server then close the socket
             * after this request. This is so that the available()
             * call (to watch for an error response from the server)
             * will work correctly.
             */
            if (e.next != null
                && e.next.request.getData() != null
                && (!con.ServProtVersKnown || con.ServerProtocolVersion < HTTP_1_1)
                && e.conn_reset) {
              addToken(req, "Connection", "close");
            }

            /* If this an HTTP/1.1 server then don't pipeline retries.
             * The problem is that if the server for some reason
             * decides not to use persistent connections and it does
             * not do a correct shutdown of the connection, then the
             * response will be ReSeT. If we did pipeline then we
             * would keep falling into this trap indefinitely.
             *
             * Note that for HTTP/1.0 servers, if they don't support
             * keep-alives then the normal code will already handle
             * this accordingly and won't pipe over the same
             * connection.
             */
            if (con.ServProtVersKnown && con.ServerProtocolVersion >= HTTP_1_1 && e.conn_reset) {
              req.dont_pipeline = true;
            }
            // The above is too risky - for moment let's be safe
            // and never pipeline retried request at all.
            req.dont_pipeline = true;

            // now resend the request

            Log.write(
                Log.MODS,
                "RtryM: Retrying request '" + req.getMethod() + " " + req.getRequestURI() + "'");

            if (e.conn_reset) req.num_retries++;
            e.response.http_resp.set(req, con.sendRequest(req, e.response.timeout));
            e.exception = null;
            e.first = null;
          }
        }
      } catch (NullPointerException npe) {
        if (got_lock) throw npe;
      } catch (ParseException pe) {
        throw new IOException(pe.getMessage());
      }

      if (re.exception != null) throw re.exception;

      re.restart = true;
      throw re;
    }
  }
コード例 #27
0
  /* ------------------------------------------------------------ */
  protected void handleRequest() throws IOException {
    boolean error = false;

    String threadName = null;
    try {
      if (LOG.isDebugEnabled()) {
        threadName = Thread.currentThread().getName();
        Thread.currentThread().setName(threadName + " - " + _uri);
      }

      // Loop here to handle async request redispatches.
      // The loop is controlled by the call to async.unhandle in the
      // finally block below.  If call is from a non-blocking connector,
      // then the unhandle will return false only if an async dispatch has
      // already happened when unhandle is called.   For a blocking connector,
      // the wait for the asynchronous dispatch or timeout actually happens
      // within the call to unhandle().

      final Server server = _server;
      boolean handling = _request._async.handling() && server != null && server.isRunning();
      while (handling) {
        _request.setHandled(false);

        String info = null;
        try {
          _uri.getPort();
          info = URIUtil.canonicalPath(_uri.getDecodedPath());
          if (info == null && !_request.getMethod().equals(HttpMethods.CONNECT))
            throw new HttpException(400);
          _request.setPathInfo(info);

          if (_out != null) _out.reopen();

          if (_request._async.isInitial()) {
            _request.setDispatcherType(DispatcherType.REQUEST);
            _connector.customize(_endp, _request);
            server.handle(this);
          } else {
            _request.setDispatcherType(DispatcherType.ASYNC);
            server.handleAsync(this);
          }
        } catch (ContinuationThrowable e) {
          LOG.ignore(e);
        } catch (EofException e) {
          LOG.debug(e);
          error = true;
          _request.setHandled(true);
        } catch (RuntimeIOException e) {
          LOG.debug(e);
          error = true;
          _request.setHandled(true);
        } catch (HttpException e) {
          LOG.debug(e);
          error = true;
          _request.setHandled(true);
          _response.sendError(e.getStatus(), e.getReason());
        } catch (Throwable e) {
          if (e instanceof ThreadDeath) throw (ThreadDeath) e;

          LOG.warn(String.valueOf(_uri), e);
          error = true;
          _request.setHandled(true);
          _generator.sendError(info == null ? 400 : 500, null, null, true);
        } finally {
          handling = !_request._async.unhandle() && server.isRunning() && _server != null;
        }
      }
    } finally {
      if (threadName != null) Thread.currentThread().setName(threadName);

      if (_request._async.isUncompleted()) {
        _request._async.doComplete();

        if (_expect100Continue) {
          LOG.debug("100 continues not sent");
          // We didn't send 100 continues, but the latest interpretation
          // of the spec (see httpbis) is that the client will either
          // send the body anyway, or close.  So we no longer need to
          // do anything special here other than make the connection not persistent
          _expect100Continue = false;
          if (!_response.isCommitted()) _generator.setPersistent(false);
        }

        if (_endp.isOpen()) {
          if (error) {
            _endp.shutdownOutput();
            _generator.setPersistent(false);
            if (!_generator.isComplete()) _response.complete();
          } else {
            if (!_response.isCommitted() && !_request.isHandled())
              _response.sendError(HttpServletResponse.SC_NOT_FOUND);
            _response.complete();
            if (_generator.isPersistent()) _connector.persist(_endp);
          }
        } else {
          _response.complete();
        }

        _request.setHandled(true);
      }
    }
  }
コード例 #28
0
  @Override
  public void doHandle(
      String target,
      Request request,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse)
      throws IOException, ServletException {

    LOG.info("handling " + target);

    // !!! doHandle() is called twice for a request when using redirectiion, first time with
    // request.getPathInfo()
    // set to the URI and target set to the path, then with request.getPathInfo() set to null and
    // target set to the .jsp
    try {
      // request.setHandled(true);
      boolean secured;
      if (request.getScheme().equals("https")) {
        secured = true;
      } else if (request.getScheme().equals("http")) {
        secured = false;
      } else {
        httpServletResponse
            .getWriter()
            .println(
                String.format(
                    "<h1>Unknown scheme %s at %s</h1>",
                    request.getScheme(), request.getUri().getDecodedPath()));
        return;
      }

      if (request.getMethod().equals("GET")) {
        if (isInJar || target.endsWith(".jsp")) {
          // !!! when not in jar there's no need to do anything about params if it's not a .jsp,
          // as this will get called again for the corresponding .jsp
          if (prepareForJspGet(target, request, httpServletResponse, secured)) {
            return;
          }
        }
        if (target.startsWith(PATH_OPEN_ARTICLE)) {
          handleOpenArticle(request, httpServletResponse, target);
          return;
        }
        super.doHandle(target, request, httpServletRequest, httpServletResponse);
        LOG.info("handling of " + target + " went to super");

        // httpServletResponse.setDateHeader("Date", System.currentTimeMillis());     //ttt2 review
        // these, probably not use
        // httpServletResponse.setDateHeader("Expires", System.currentTimeMillis() + 60000);

        return;
      }

      if (request.getMethod().equals("POST")) {
        if (request.getUri().getDecodedPath().equals(PATH_LOGIN)) {
          handleLoginPost(request, httpServletResponse, secured);
        } else if (request.getUri().getDecodedPath().equals(PATH_SIGNUP)) {
          handleSignupPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_CHANGE_PASSWORD)) {
          handleChangePasswordPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_UPDATE_FEED_LIST)) {
          handleUpdateFeedListPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_ADD_FEED)) {
          handleAddFeedPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_REMOVE_FEED)) {
          handleRemoveFeedPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_CHANGE_SETTINGS)) {
          handleChangeSettingsPost(request, httpServletResponse);
        }
      }

      /*{ // for tests only;
          httpServletResponse.getWriter().println(String.format("<h1>Unable to process request %s</h1>",
                  request.getUri().getDecodedPath()));
          request.setHandled(true);
      }*/
    } catch (Exception e) {
      LOG.error("Error processing request", e);
      try {
        // redirectToError(e.toString(), request, httpServletResponse); //!!! redirectToError leads
        // to infinite loop, probably related to
        // the fact that we get 2 calls for a regular request when redirecting
        httpServletResponse
            .getWriter()
            .println(
                String.format(
                    "<h1>Unable to process request %s</h1>", // ttt1 generate some HTML
                    request.getUri().getDecodedPath()));
        request.setHandled(true);
      } catch (Exception e1) {
        LOG.error("Error redirecting", e1);
      }
    }
  }
コード例 #29
0
  /**
   * Check the response and answer true if authentication succeeds. We are making simplifying
   * assumptions here and assuming that the password is available to us for computation of the MD5
   * hash. We also dont cache authentications so that the user has to authenticate on each
   * registration.
   *
   * @param user is the username
   * @param authHeader is the Authroization header from the SIP request.
   * @param requestLine is the SIP Request line from the SIP request.
   * @exception SIPAuthenticationException is thrown when authentication fails or message is bad
   */
  public boolean doAuthenticate(String user, AuthorizationHeader authHeader, Request request) {
    String realm = authHeader.getRealm();
    String username = authHeader.getUsername();
    URI requestURI = request.getRequestURI();

    if (username == null) {
      ProxyDebug.println(
          "DEBUG, DigestAuthenticateMethod, doAuthenticate(): "
              + "WARNING: userName parameter not set in the header received!!!");
      username = user;
    }
    if (realm == null) {
      ProxyDebug.println(
          "DEBUG, DigestAuthenticateMethod, doAuthenticate(): "
              + "WARNING: realm parameter not set in the header received!!! WE use the default one");
      realm = DEFAULT_REALM;
    }

    ProxyDebug.println(
        "DEBUG, DigestAuthenticateMethod, doAuthenticate(): "
            + "Trying to authenticate user: "******" for "
            + " the realm: "
            + realm);

    String password = (String) passwordTable.get(username + "@" + realm);
    if (password == null) {
      ProxyDebug.println(
          "DEBUG, DigestAuthenticateMethod, doAuthenticate(): "
              + "ERROR: password not found for the user: "******"@"
              + realm);
      return false;
    }

    String nonce = authHeader.getNonce();
    // If there is a URI parameter in the Authorization header,
    // then use it.
    URI uri = authHeader.getURI();
    // There must be a URI parameter in the authorization header.
    if (uri == null) {
      ProxyDebug.println(
          "DEBUG, DigestAuthenticateMethod, doAuthenticate(): "
              + "ERROR: uri paramater not set in the header received!");
      return false;
    }

    ProxyDebug.println(
        "DEBUG, DigestAuthenticationMethod, doAuthenticate(), username:"******"!");
    ProxyDebug.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), realm:" + realm + "!");
    ProxyDebug.println(
        "DEBUG, DigestAuthenticationMethod, doAuthenticate(), password:"******"!");
    ProxyDebug.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), uri:" + uri + "!");
    ProxyDebug.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), nonce:" + nonce + "!");
    ProxyDebug.println(
        "DEBUG, DigestAuthenticationMethod, doAuthenticate(), method:" + request.getMethod() + "!");

    String A1 = username + ":" + realm + ":" + password;
    String A2 = request.getMethod().toUpperCase() + ":" + uri.toString();
    byte mdbytes[] = messageDigest.digest(A1.getBytes());
    String HA1 = ProxyUtilities.toHexString(mdbytes);

    ProxyDebug.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), HA1:" + HA1 + "!");
    mdbytes = messageDigest.digest(A2.getBytes());
    String HA2 = ProxyUtilities.toHexString(mdbytes);
    ProxyDebug.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), HA2:" + HA2 + "!");
    String cnonce = authHeader.getCNonce();
    String KD = HA1 + ":" + nonce;
    if (cnonce != null) {
      KD += ":" + cnonce;
    }
    KD += ":" + HA2;
    mdbytes = messageDigest.digest(KD.getBytes());
    String mdString = ProxyUtilities.toHexString(mdbytes);
    String response = authHeader.getResponse();
    ProxyDebug.println(
        "DEBUG, DigestAuthenticateMethod, doAuthenticate(): "
            + "we have to compare his response: "
            + response
            + " with our computed"
            + " response: "
            + mdString);

    int res = (mdString.compareTo(response));
    if (res == 0) {
      ProxyDebug.println(
          "DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "User authenticated...");
    } else {
      ProxyDebug.println(
          "DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "User not authenticated...");
    }

    return res == 0;
  }
コード例 #30
0
 private static boolean isFormAvailable(Request request, TypedData body) {
   HttpMethod method = request.getMethod();
   return body.getContentType().isForm() && (method.isPost() || method.isPut());
 }