Esempio n. 1
0
 public void skipData(HTTPRequest request) throws IOException {
   if (hasToCloseConnection(request.getResponseHeader())) {
     return;
   }
   InputStream is = createInputStream(request.getResponseHeader(), getInputStream());
   while (is.skip(2048) > 0) ;
 }
Esempio n. 2
0
 /**
  * This method creates an event vector based on a given request object.
  *
  * @param request The HttpRequest object.
  * @return A Vector containing the events
  */
 private Vector createEventVector(HTTPRequest request) {
   Vector eventVector = new Vector();
   if (request.getQueryValue("mauiEvent") != null) {
     eventVector = StringUtilities.split(".", request.getQueryValue("mauiEvent"));
   }
   return eventVector;
 }
  /**
   * Test
   *
   * @throws Exception Any exception
   */
  @Test
  public void createHTTPRequestTest() throws Exception {
    File file = File.createTempFile("text_junit", ".txt");
    file.deleteOnExit();
    IOHelper.writeTextFile("TEST_DATA", file);
    FaxJob faxJob = new FaxJobImpl();
    faxJob.setFilePath(file.getPath());
    faxJob.setTargetName("TEST_TARGET_NAME");
    HTTPRequest output =
        this.converter.createHTTPRequest(
            this.faxClientSpi,
            FaxActionType.SUBMIT_FAX_JOB,
            FaxJob2HTTPRequestConverterConfigurationConstants.SUBMIT_FAX_JOB_TEMPLATE_PROPERTY_KEY,
            faxJob);

    file.delete();

    Assert.assertNotNull(output);
    Assert.assertEquals("TEST_TARGET_NAME", output.getResource());
    Assert.assertEquals(
        "param1=value1&param2=value2&target.name=TEST_TARGET_NAME", output.getParametersText());
    Assert.assertEquals(
        "submit\ntarget.address=\ntarget.name=TEST_TARGET_NAME\nsender.name=\nsender.fax.number=\nsender.email=\nCONTENT:\nTEST_DATA",
        output.getContentAsString());
  }
  @Override
  public void onPrepareReception(PortReceiver receiver) throws BufferUnderflowException {
    request.clear();
    response.clear();

    do {
      if (state == STATE_BEGIN) {
        String line = receiver.getLine(Charset.defaultCharset());
        String parts[] = line.split("\\s+");

        if (parts.length != 3) {
          // Invalid request
          error("Invalid Request");
          return;
        } else if (!request.validateMethod(parts[0])) {
          error("Unrecognized verb " + parts[0]);
          return;
        } else {
          request.setRequestURI(parts[1]);
          request.version = (parts[2]);
          state = receiver.markState(STATE_HEADER);
        }
      }

      if (state == STATE_HEADER) {
        String line = receiver.getLine(Charset.defaultCharset());
        if (line.isEmpty()) {
          state = receiver.markState(STATE_BODY_VALIDATION);
        } else {
          int p = line.indexOf(':');
          if (p > 0) {
            String name = line.substring(0, p).trim();
            String value = line.substring(p + 1).trim();

            request.processHeader(name, value);
          }
        }
      }

      if (state == STATE_BODY_VALIDATION) {
        if (request.contentLength >= 0) {
          receiver.setLimit(request.contentLength);
        } else if (request.isChunked) {
          int chunkLength = Integer.parseInt(receiver.getLine(Charset.defaultCharset()), 16);
          if (chunkLength == 0) {
            receiver.getLine(Charset.defaultCharset());
            state = receiver.markState(STATE_BEGIN);
          } else {
            receiver.setLimit(chunkLength);
          }
        }
        state = receiver.markState(STATE_BODY);
        break;
      }
    } while (true);
  }
 public void addRequestInfo(String ip, HTTPRequest request) {
   Client client = getClientByIp(ip);
   client.addRequest(request);
   request.setClient(client);
   request.fixTimeSpent();
   requests.add(request);
   boolean isNewRequest = uniqueRequests.add(request);
   if (request.existsRedirect()) {
     Integer count = isNewRequest ? 1 : uniqueRedirects.get(request) + 1;
     uniqueRedirects.put(request, count);
   }
 }
Esempio n. 6
0
 public SVNErrorMessage readData(
     HTTPRequest request, String method, String path, DefaultHandler handler) throws IOException {
   InputStream is = null;
   SpoolFile tmpFile = null;
   SVNErrorMessage err = null;
   try {
     if (myIsSpoolResponse || myIsSpoolAll) {
       OutputStream dst = null;
       try {
         tmpFile = new SpoolFile(mySpoolDirectory);
         dst = tmpFile.openForWriting();
         dst = new SVNCancellableOutputStream(dst, myRepository.getCanceller());
         // this will exhaust http stream anyway.
         err = readData(request, dst);
         SVNFileUtil.closeFile(dst);
         dst = null;
         if (err != null) {
           return err;
         }
         // this stream always have to be closed.
         is = tmpFile.openForReading();
         is = myRepository.getDebugLog().createLogStream(SVNLogType.NETWORK, is);
       } finally {
         SVNFileUtil.closeFile(dst);
       }
     } else {
       is = createInputStream(request.getResponseHeader(), getInputStream());
     }
     // this will not close is stream.
     err = readData(is, method, path, handler);
   } catch (IOException e) {
     throw e;
   } finally {
     if (myIsSpoolResponse || myIsSpoolAll) {
       // always close spooled stream.
       SVNFileUtil.closeFile(is);
     } else if (err == null && !hasToCloseConnection(request.getResponseHeader())) {
       // exhaust stream if connection is not about to be closed.
       SVNFileUtil.closeFile(is);
     }
     if (tmpFile != null) {
       try {
         tmpFile.delete();
       } catch (SVNException e) {
         throw new IOException(e.getMessage());
       }
     }
     myIsSpoolResponse = false;
   }
   return err;
 }
  @Test
  public void testResolvePUTWithNoHeaders() throws IOException {
    HTTPRequest request = new HTTPRequest(URI.create("http://dummy/uri/123"), HTTPMethod.PUT);
    final Payload payload = mock(Payload.class);
    request = request.payload(payload);
    when(payload.getMimeType()).thenReturn(new MIMEType("text/plain"));
    final HttpMethod method = mock(PostMethod.class);
    HTTPClientResponseResolver resolver =
        createResponseResolver(method, Status.valueOf(200), new Header[0]);

    HTTPResponse response = resolver.resolve(request);
    assertNotNull(response);
    assertEquals(200, response.getStatus().getCode());
    assertEquals(0, response.getHeaders().size());
  }
Esempio n. 8
0
 @Override
 public boolean hasHandle(HTTPRequest request) {
   if (request.reply().equals("POST") && this.isStatus()) {
     return true;
   }
   return false;
 }
Esempio n. 9
0
 public SVNErrorMessage readData(HTTPRequest request, OutputStream dst) throws IOException {
   InputStream stream = createInputStream(request.getResponseHeader(), getInputStream());
   byte[] buffer = getBuffer();
   boolean willCloseConnection = false;
   try {
     while (true) {
       int count = stream.read(buffer);
       if (count < 0) {
         break;
       }
       if (dst != null) {
         dst.write(buffer, 0, count);
       }
     }
   } catch (IOException e) {
     willCloseConnection = true;
     if (e instanceof IOExceptionWrapper) {
       IOExceptionWrapper wrappedException = (IOExceptionWrapper) e;
       return wrappedException.getOriginalException().getErrorMessage();
     }
     if (e.getCause() instanceof SVNException) {
       return ((SVNException) e.getCause()).getErrorMessage();
     }
     throw e;
   } finally {
     if (!willCloseConnection) {
       SVNFileUtil.closeFile(stream);
     }
     myRepository.getDebugLog().flushStream(stream);
   }
   return null;
 }
Esempio n. 10
0
  /**
   * This method takes care of some special generic Maui events. It should be called before the Maui
   * application handles the event.
   *
   * @param mauiApp Reference to the MauiApplication associated with the events
   * @param eventVector The same event vector that is passed to the Maui app.
   * @param paramHash Hashtable of HTTP parameters
   * @param response The HTTPResponse object which will be sent back to the client
   */
  private void processEvent(
      MauiApplication mauiApp,
      Vector eventVector,
      Hashtable paramHash,
      HTTPRequest request,
      HTTPResponse response) {
    boolean passEventToMauiApp = true;

    try {
      if (eventVector != null && !eventVector.isEmpty()) {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Component events
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        String componentID = (String) eventVector.lastElement();

        // If there are parentheses...
        if (componentID.startsWith("(") && componentID.endsWith(")")) {
          // ... strip them off!
          componentID = componentID.substring(1, componentID.length() - 1);
        }

        //
        //	Strip off prefix - some wml browsers don't like variables that begin with a digit
        //
        if (componentID.startsWith("IDz")) {
          componentID = componentID.substring(3);
        }
        {
          System.err.println("componentID: " + componentID);
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Pass events to Maui application
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // Check for a content-type override
        String contentType = null;
        {
          if ((contentType = request.getQueryValue("contentType")) != null) {
            response.setContentType(contentType);
          } else {
            response.setContentType("x-wap.wml");
          }
        }
        response.setContent(mauiApp.render().getBytes());
      } else {
        response.setContentType("text/vnd.wap.wml");
        response.setContent(mauiApp.render().getBytes());
      }
    } catch (Exception e) {
      response.setContentType(getBaseContentType());
      response.setContent((generateExceptionMessage(e)).getBytes());
      e.printStackTrace(System.err);
    }
  }
Esempio n. 11
0
 @Override
 public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) {
   final String last = httpReq.getUrlParameter("ROOM");
   if (last == null) return " @break@";
   if (last.length() > 0) {
     final Room R = MUDGrinder.getRoomObject(httpReq, last);
     if (R != null) return clearWebMacros(R.roomID());
   }
   return "";
 }
Esempio n. 12
0
  @Override
  public String runMacro(HTTPRequest httpReq, String parm) {
    final java.util.Map<String, String> parms = parseParms(parm);
    boolean finalCondition = false;
    for (String key : parms.keySet()) {
      if (key.length() == 0) continue;
      final String equals = parms.get(key);
      boolean not = false;
      boolean thisCondition = true;
      boolean startswith = false;
      boolean inside = false;
      boolean endswith = false;
      if (key.startsWith("||")) key = key.substring(2);
      if (key.startsWith("<")) {
        startswith = true;
        key = key.substring(1);
      }
      if (key.startsWith(">")) {
        endswith = true;
        key = key.substring(1);
      }
      if (key.startsWith("*")) {
        inside = true;
        key = key.substring(1);
      }

      if (key.startsWith("!")) {
        key = key.substring(1);
        not = true;
      }
      final String check = httpReq.getUrlParameter(key);
      if (not) {
        if ((check == null) && (equals.length() == 0)) thisCondition = false;
        else if (check == null) thisCondition = true;
        else if (startswith) thisCondition = !check.startsWith(equals);
        else if (endswith) thisCondition = !check.endsWith(equals);
        else if (inside) thisCondition = !(check.indexOf(equals) >= 0);
        else if (!check.equalsIgnoreCase(equals)) thisCondition = true;
        else thisCondition = false;
      } else {
        if ((check == null) && (equals.length() == 0)) thisCondition = true;
        else if (check == null) thisCondition = false;
        else if (startswith) thisCondition = check.startsWith(equals);
        else if (endswith) thisCondition = check.endsWith(equals);
        else if (inside) thisCondition = (check.indexOf(equals) >= 0);
        else if (!check.equalsIgnoreCase(equals)) thisCondition = false;
        else thisCondition = true;
      }
      finalCondition = finalCondition || thisCondition;
    }
    if (finalCondition) return "true";
    return "false";
  }
Esempio n. 13
0
  private boolean singleRequest() throws IOException {
    boolean doContinue = true;
    String requestString = clientSocket.getRequest(timeOutMilliseconds);
    HTTPResponse response;
    try {
      HTTPRequest request = HTTPRequestParser.parseRequest(requestString);

      if (request.doCloseAfterResponse()) {
        doContinue = false;
      }

      response = factory.getResponse(request);
    } catch (MalformedRequestException e) {
      response = factory.getBadResponse();
      doContinue = false;
    }

    response.writeResponse(clientSocket, doContinue);

    return doContinue;
  }
Esempio n. 14
0
 private void finishResponse(HTTPRequest request) {
   if (myOutputStream != null) {
     try {
       myOutputStream.flush();
     } catch (IOException ex) {
     }
   }
   HTTPHeader header = request != null ? request.getResponseHeader() : null;
   if (hasToCloseConnection(header)) {
     close();
   }
 }
 @Override
 public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) {
   final java.util.Map<String, String> parms = parseParms(parm);
   final String last = httpReq.getUrlParameter("GOVERNMENT");
   if (parms.containsKey("RESET")) {
     if (last != null) httpReq.removeUrlParameter("GOVERNMENT");
     return "";
   }
   int lastID = -1;
   for (final ClanGovernment G : CMLib.clans().getStockGovernments()) {
     if ((last == null)
         || ((last.length() > 0) && (CMath.s_int(last) == lastID) && (G.getID() != lastID))) {
       httpReq.addFakeUrlParameter("GOVERNMENT", Integer.toString(G.getID()));
       return "";
     }
     lastID = G.getID();
   }
   httpReq.addFakeUrlParameter("GOVERNMENT", "");
   if (parms.containsKey("EMPTYOK")) return "<!--EMPTY-->";
   return " @break@";
 }
Esempio n. 16
0
 @Override
 public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) {
   final String last = httpReq.getUrlParameter("GOVERNMENT");
   if (last == null) return " @break@";
   if (last.length() > 0) {
     if (CMath.isInteger(last)) {
       final ClanGovernment G = CMLib.clans().getStockGovernment(CMath.s_int(last));
       if (G != null) return clearWebMacros(Integer.toString(G.getID()));
     }
     return clearWebMacros(last);
   }
   return "";
 }
Esempio n. 17
0
  public void readHeader(HTTPRequest request) throws IOException {
    InputStream is =
        myRepository.getDebugLog().createLogStream(SVNLogType.NETWORK, getInputStream());

    try {
      // may throw EOF exception.
      HTTPStatus status = HTTPParser.parseStatus(is, myCharset);
      HTTPHeader header = HTTPHeader.parseHeader(is, myCharset);
      request.setStatus(status);
      request.setResponseHeader(header);
    } catch (ParseException e) {
      // in case of parse exception:
      // try to read remaining and log it.
      String line = HTTPParser.readLine(is, myCharset);
      while (line != null && line.length() > 0) {
        line = HTTPParser.readLine(is, myCharset);
      }

      throw new IOException(e.getMessage());
    } finally {
      myRepository.getDebugLog().flushStream(is);
    }
  }
Esempio n. 18
0
  public String postFile(URLFetchService us, List<PostObj> postobjlist) throws Exception {
    int index;

    Gson gson;
    String linkID;
    List<String> linkList;
    HTTPRequest req;
    String param;

    gson = new Gson();

    linkID = createUID();
    linkList = new ArrayList<String>();
    for (index = 0; index < postobjlist.size(); index++) {
      linkList.add(postobjlist.get(index).filelink);
    }

    param =
        URLEncoder.encode("postlist", "UTF-8")
            + "="
            + URLEncoder.encode(gson.toJson(postobjlist), "UTF-8")
            + '&'
            + URLEncoder.encode("linkid", "UTF-8")
            + "="
            + URLEncoder.encode(linkID, "UTF-8")
            + '&'
            + URLEncoder.encode("linklist", "UTF-8")
            + "="
            + URLEncoder.encode(gson.toJson(linkList), "UTF-8");
    req =
        new HTTPRequest(
            new URL("http://tnfshmoe.appspot.com/postdf89ksfxsyx9sfdex09usdjksd"), HTTPMethod.POST);
    req.setPayload(param.getBytes());
    us.fetch(req);

    return linkID;
  }
Esempio n. 19
0
  public UserId determineUserId(String code) throws IOException {
    Map<String, String> parameters = Maps.newHashMap();
    parameters.put("code", code);
    parameters.put("client_id", clientId);
    parameters.put("client_secret", clientSecret);
    parameters.put("redirect_uri", uriBuilder.forPath(OAuthCallbackServlet.PATH).toString());
    parameters.put("grant_type", "authorization_code");

    HTTPRequest fetchRequest =
        new HTTPRequest(new URL("https://accounts.google.com/o/oauth2/token"), HTTPMethod.POST);
    fetchRequest.setPayload(buildKeyValueString(parameters, true).getBytes());
    HTTPResponse response = urlFetchService.fetch(fetchRequest);
    JsonObject object = jsonParser.parse(new String(response.getContent())).getAsJsonObject();
    String access_token = object.get("access_token").getAsString();

    HTTPRequest secondRequest =
        new HTTPRequest(new URL("https://www.googleapis.com/oauth2/v1/userinfo"));
    secondRequest.addHeader(
        new HTTPHeader("Authorization", String.format("Bearer %s", access_token)));
    response = urlFetchService.fetch(secondRequest);
    object = jsonParser.parse(new String(response.getContent())).getAsJsonObject();

    return UserId.fromString(object.get("id").getAsString());
  }
Esempio n. 20
0
 @Override
 public CacheItem get(HTTPRequest request) {
   Connection connection = getConnection();
   PreparedStatement statement = null;
   try {
     statement = connection.prepareStatement("select * from response where uri = ?");
     statement.setString(1, request.getRequestURI().toString());
     ResultSet rs = statement.executeQuery();
     while (rs.next()) {
       CacheItemHolder holder = mapper.mapRow(rs, connection);
       if (holder.getVary().matches(request)) {
         return holder.getCacheItem();
       }
     }
   } catch (SQLException e) {
     throw new DataAccessException(e);
   } finally {
     JdbcUtil.close(statement);
   }
   return null;
 }
Esempio n. 21
0
 /**
  * This method creates a parameter hashtables based on a given request object.
  *
  * @param request The HttpServletRequest object.
  * @return A Hashtable containing the HTTP parameter key/value pairs
  */
 private Hashtable createParamHash(HTTPRequest request) {
   return request.getQueries();
 }
Esempio n. 22
0
  @Override
  public String runMacro(HTTPRequest httpReq, String parm) {
    final java.util.Map<String, String> parms = parseParms(parm);
    final String last = httpReq.getUrlParameter("JOURNAL");
    if (last == null) return " @break@";
    boolean securityOverride = false;
    if ((Thread.currentThread() instanceof CWThread)
        && CMath.s_bool(((CWThread) Thread.currentThread()).getConfig().getMiscProp("ADMIN"))
        && parms.containsKey("ALLFORUMJOURNALS")) securityOverride = true;

    final MOB M = Authenticate.getAuthenticatedMob(httpReq);
    if ((!securityOverride)
        && (CMLib.journals().isArchonJournalName(last))
        && ((M == null) || (!CMSecurity.isASysOp(M)))) return " @break@";

    final Clan setClan = CMLib.clans().getClan(httpReq.getUrlParameter("CLAN"));
    final JournalsLibrary.ForumJournal journal = CMLib.journals().getForumJournal(last, setClan);
    if (journal == null) return " @break@";

    final StringBuffer str = new StringBuffer("");
    if (parms.containsKey("ISSMTPFORWARD")) {
      @SuppressWarnings("unchecked")
      final TreeMap<String, JournalsLibrary.SMTPJournal> set =
          (TreeMap<String, JournalsLibrary.SMTPJournal>)
              Resources.getResource("SYSTEM_SMTP_JOURNALS");
      final JournalsLibrary.SMTPJournal entry =
          (set != null) ? set.get(last.toUpperCase().trim()) : null;
      final String email =
          ((M != null) && (M.playerStats() != null) && (M.playerStats().getEmail() != null))
              ? M.playerStats().getEmail()
              : "";
      str.append(
              ((entry != null) && (email.length() > 0)) ? Boolean.toString(entry.forward) : "false")
          .append(", ");
    }

    if (parms.containsKey("ISSMTPSUBSCRIBER")) {
      final Map<String, List<String>> lists =
          Resources.getCachedMultiLists("mailinglists.txt", true);
      final List<String> mylist = lists.get(last);
      str.append(
              ((mylist != null) && (M != null))
                  ? Boolean.toString(mylist.contains(M.Name()))
                  : "false")
          .append(", ");
    }

    if (parms.containsKey("SMTPADDRESS")) {
      @SuppressWarnings("unchecked")
      final TreeMap<String, JournalsLibrary.SMTPJournal> set =
          (TreeMap<String, JournalsLibrary.SMTPJournal>)
              Resources.getResource("SYSTEM_SMTP_JOURNALS");
      final JournalsLibrary.SMTPJournal entry =
          (set != null) ? set.get(last.toUpperCase().trim()) : null;
      if ((entry != null) && (entry.forward)) {
        str.append(entry.name.replace(' ', '_') + "@" + CMProps.getVar(CMProps.Str.MUDDOMAIN))
            .append(", ");
      }
    }

    if (parms.containsKey("CANADMIN") || parms.containsKey("ISADMIN"))
      str.append("" + journal.authorizationCheck(M, ForumJournalFlags.ADMIN)).append(", ");

    if (parms.containsKey("CANPOST"))
      str.append("" + journal.authorizationCheck(M, ForumJournalFlags.POST)).append(", ");

    if (parms.containsKey("CANREAD"))
      str.append("" + journal.authorizationCheck(M, ForumJournalFlags.READ)).append(", ");

    if (parms.containsKey("CANREPLY"))
      str.append("" + journal.authorizationCheck(M, ForumJournalFlags.REPLY)).append(", ");

    if (parms.containsKey("ADMINMASK")) str.append("" + journal.adminMask()).append(", ");

    if (parms.containsKey("READMASK")) str.append("" + journal.readMask()).append(", ");

    if (parms.containsKey("POSTMASK")) str.append("" + journal.postMask()).append(", ");

    if (parms.containsKey("REPLYMASK")) str.append("" + journal.replyMask()).append(", ");

    if (parms.containsKey("ID")) str.append("" + journal.NAME()).append(", ");

    if (parms.containsKey("NAME")) str.append("" + journal.NAME()).append(", ");

    if (parms.containsKey("EXPIRE")) str.append("").append(", ");

    final JournalsLibrary.JournalSummaryStats stats = CMLib.journals().getJournalStats(journal);
    if (stats == null) return " @break@";

    if (parms.containsKey("POSTS")) str.append("" + stats.posts).append(", ");

    if (parms.containsKey("THREADS")) str.append("" + stats.threads).append(", ");

    if (parms.containsKey("SHORTDESC")) str.append("" + stats.shortIntro).append(", ");

    if (parms.containsKey("LONGDESC")) str.append("" + stats.longIntro).append(", ");

    if (parms.containsKey("IMAGEPATH")) {
      if ((stats.imagePath == null) || (stats.imagePath.trim().length() == 0))
        str.append(L("images/lilcm.jpg")).append(", ");
      else str.append("" + stats.threads).append(", ");
    }

    String strstr = str.toString();
    if (strstr.endsWith(", ")) strstr = strstr.substring(0, strstr.length() - 2);
    return clearWebMacros(strstr);
  }
Esempio n. 23
0
  public HTTPStatus request(
      String method,
      String path,
      HTTPHeader header,
      InputStream body,
      int ok1,
      int ok2,
      OutputStream dst,
      DefaultHandler handler,
      SVNErrorMessage context)
      throws SVNException {
    if ("".equals(path) || path == null) {
      path = "/";
    }

    // 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception.
    HTTPSSLKeyManager keyManager =
        myKeyManager == null && myRepository.getAuthenticationManager() != null
            ? createKeyManager()
            : myKeyManager;
    TrustManager trustManager =
        myTrustManager == null && myRepository.getAuthenticationManager() != null
            ? myRepository.getAuthenticationManager().getTrustManager(myRepository.getLocation())
            : myTrustManager;

    String sslRealm =
        "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">";
    SVNAuthentication httpAuth = myLastValidAuth;
    boolean isAuthForced =
        myRepository.getAuthenticationManager() != null
            ? myRepository.getAuthenticationManager().isAuthenticationForced()
            : false;
    if (httpAuth == null && isAuthForced) {
      httpAuth =
          myRepository
              .getAuthenticationManager()
              .getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null);
      myChallengeCredentials =
          new HTTPBasicAuthentication((SVNPasswordAuthentication) httpAuth, myCharset);
    }
    String realm = null;

    // 2. create request instance.
    HTTPRequest request = new HTTPRequest(myCharset);
    request.setConnection(this);
    request.setKeepAlive(true);
    request.setRequestBody(body);
    request.setResponseHandler(handler);
    request.setResponseStream(dst);

    SVNErrorMessage err = null;
    boolean ntlmAuthIsRequired = false;
    boolean ntlmProxyAuthIsRequired = false;
    boolean negoAuthIsRequired = false;
    int authAttempts = 0;
    while (true) {
      HTTPStatus status = null;
      if (System.currentTimeMillis() >= myNextRequestTimeout) {
        SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "Keep-Alive timeout detected");
        close();
      }
      int retryCount = 1;
      try {
        err = null;
        String httpAuthResponse = null;
        String proxyAuthResponse = null;
        while (retryCount >= 0) {
          connect(keyManager, trustManager);
          request.reset();
          request.setProxied(myIsProxied);
          request.setSecured(myIsSecured);
          if (myProxyAuthentication != null
              && (ntlmProxyAuthIsRequired
                  || !"NTLM".equals(myProxyAuthentication.getAuthenticationScheme()))) {
            if (proxyAuthResponse == null) {
              request.initCredentials(myProxyAuthentication, method, path);
              proxyAuthResponse = myProxyAuthentication.authenticate();
            }
            request.setProxyAuthentication(proxyAuthResponse);
          }

          if (myChallengeCredentials != null
              && (ntlmAuthIsRequired
                  || negoAuthIsRequired
                  || ((!"NTLM".equals(myChallengeCredentials.getAuthenticationScheme()))
                          && !"Negotiate".equals(myChallengeCredentials.getAuthenticationScheme()))
                      && httpAuth != null)) {
            if (httpAuthResponse == null) {
              request.initCredentials(myChallengeCredentials, method, path);
              httpAuthResponse = myChallengeCredentials.authenticate();
            }
            request.setAuthentication(httpAuthResponse);
          }

          try {
            request.dispatch(method, path, header, ok1, ok2, context);
            break;
          } catch (EOFException pe) {
            // retry, EOF always means closed connection.
            if (retryCount > 0) {
              close();
              continue;
            }
            throw (IOException) new IOException(pe.getMessage()).initCause(pe);
          } finally {
            retryCount--;
          }
        }
        myNextRequestTimeout = request.getNextRequestTimeout();
        status = request.getStatus();
      } catch (SSLHandshakeException ssl) {
        myRepository.getDebugLog().logFine(SVNLogType.NETWORK, ssl);
        close();
        if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) {
          SVNErrorManager.cancel(ssl.getCause().getMessage(), SVNLogType.NETWORK);
        }
        SVNErrorMessage sslErr =
            SVNErrorMessage.create(
                SVNErrorCode.RA_NOT_AUTHORIZED,
                "SSL handshake failed: ''{0}''",
                new Object[] {ssl.getMessage()},
                SVNErrorMessage.TYPE_ERROR,
                ssl);
        if (keyManager != null) {
          keyManager.acknowledgeAndClearAuthentication(sslErr);
        }
        err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl);
        // continue; http://svnkit.com/tracker/view.php?id=301 - Kohsuke
      } catch (IOException e) {
        myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
        if (e instanceof SocketTimeoutException) {
          err =
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  "timed out waiting for server",
                  null,
                  SVNErrorMessage.TYPE_ERROR,
                  e);
        } else if (e instanceof UnknownHostException) {
          err =
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  "unknown host",
                  null,
                  SVNErrorMessage.TYPE_ERROR,
                  e);
        } else if (e instanceof ConnectException) {
          err =
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  "connection refused by the server",
                  null,
                  SVNErrorMessage.TYPE_ERROR,
                  e);
        } else if (e instanceof SVNCancellableOutputStream.IOCancelException) {
          SVNErrorManager.cancel(e.getMessage(), SVNLogType.NETWORK);
        } else if (e instanceof SSLException) {
          err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
        } else {
          err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
        }
      } catch (SVNException e) {
        myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
        // force connection close on SVNException
        // (could be thrown by user's auth manager methods).
        close();
        throw e;
      } finally {
        finishResponse(request);
      }

      if (err != null) {
        close();
        break;
      }

      if (keyManager != null) {
        myKeyManager = keyManager;
        myTrustManager = trustManager;
        keyManager.acknowledgeAndClearAuthentication(null);
      }

      if (status.getCode() == HttpURLConnection.HTTP_FORBIDDEN) {
        myLastValidAuth = null;
        close();
        err = request.getErrorMessage();
      } else if (myIsProxied && status.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) {
        Collection proxyAuthHeaders =
            request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER);
        try {
          myProxyAuthentication =
              HTTPAuthentication.parseAuthParameters(
                  proxyAuthHeaders, myProxyAuthentication, myCharset);
        } catch (SVNException svne) {
          myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne);
          err = svne.getErrorMessage();
          break;
        }

        if (myProxyAuthentication instanceof HTTPNTLMAuthentication) {
          ntlmProxyAuthIsRequired = true;
          HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication) myProxyAuthentication;
          if (ntlmProxyAuth.isInType3State()) {
            continue;
          }
        }

        err =
            SVNErrorMessage.create(
                SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed");
        SVNURL location = myRepository.getLocation();
        ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
        ISVNProxyManager proxyManager =
            authManager != null ? authManager.getProxyManager(location) : null;
        if (proxyManager != null) {
          proxyManager.acknowledgeProxyContext(false, err);
        }
        close();

        break;
      } else if (status.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        authAttempts++; // how many times did we try?

        Collection authHeaderValues =
            request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER);
        if (authHeaderValues == null || authHeaderValues.size() == 0) {
          err = request.getErrorMessage();
          status.setError(
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  err.getMessageTemplate(),
                  err.getRelatedObjects()));
          if ("LOCK".equalsIgnoreCase(method)) {
            status
                .getError()
                .setChildErrorMessage(
                    SVNErrorMessage.create(
                        SVNErrorCode.UNSUPPORTED_FEATURE,
                        "Probably you are trying to lock file in repository that only allows anonymous access"));
          }
          SVNErrorManager.error(status.getError(), SVNLogType.NETWORK);
          return status;
        }

        // we should work around a situation when a server
        // does not support Basic authentication while we're
        // forcing it, credentials should not be immediately
        // thrown away
        boolean skip = false;
        isAuthForced =
            myRepository.getAuthenticationManager() != null
                ? myRepository.getAuthenticationManager().isAuthenticationForced()
                : false;
        if (isAuthForced) {
          if (httpAuth != null
              && myChallengeCredentials != null
              && !HTTPAuthentication.isSchemeSupportedByServer(
                  myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) {
            skip = true;
          }
        }

        try {
          myChallengeCredentials =
              HTTPAuthentication.parseAuthParameters(
                  authHeaderValues, myChallengeCredentials, myCharset);
        } catch (SVNException svne) {
          err = svne.getErrorMessage();
          break;
        }

        myChallengeCredentials.setChallengeParameter("methodname", method);
        myChallengeCredentials.setChallengeParameter("uri", path);

        if (skip) {
          close();
          continue;
        }

        HTTPNTLMAuthentication ntlmAuth = null;
        HTTPNegotiateAuthentication negoAuth = null;
        if (myChallengeCredentials instanceof HTTPNTLMAuthentication) {
          ntlmAuthIsRequired = true;
          ntlmAuth = (HTTPNTLMAuthentication) myChallengeCredentials;
          if (ntlmAuth.isInType3State()) {
            continue;
          }
        } else if (myChallengeCredentials instanceof HTTPDigestAuthentication) {
          // continue (retry once) if previous request was acceppted?
          if (myLastValidAuth != null) {
            myLastValidAuth = null;
            continue;
          }
        } else if (myChallengeCredentials instanceof HTTPNegotiateAuthentication) {
          negoAuthIsRequired = true;
          negoAuth = (HTTPNegotiateAuthentication) myChallengeCredentials;
          if (negoAuth.isStarted()) {
            continue;
          }
        }

        myLastValidAuth = null;

        if (ntlmAuth != null && ntlmAuth.isNative() && authAttempts == 1) {
          /*
           * if this is the first time we get HTTP_UNAUTHORIZED, NTLM is the target auth scheme
           * and JNA is available, we should try a native auth mechanism first without calling
           * auth providers.
           */
          continue;
        }

        if (negoAuth != null) {
          continue;
        }

        ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
        if (authManager == null) {
          err = request.getErrorMessage();
          break;
        }

        realm = myChallengeCredentials.getChallengeParameter("realm");
        realm = realm == null ? "" : " " + realm;
        realm =
            "<"
                + myHost.getProtocol()
                + "://"
                + myHost.getHost()
                + ":"
                + myHost.getPort()
                + ">"
                + realm;

        if (httpAuth == null) {
          httpAuth =
              authManager.getFirstAuthentication(
                  ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
        } else {
          authManager.acknowledgeAuthentication(
              false,
              ISVNAuthenticationManager.PASSWORD,
              realm,
              request.getErrorMessage(),
              httpAuth);
          httpAuth =
              authManager.getNextAuthentication(
                  ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
        }

        if (httpAuth == null) {
          err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, "HTTP authorization cancelled");
          break;
        }
        if (httpAuth != null) {
          myChallengeCredentials.setCredentials((SVNPasswordAuthentication) httpAuth);
        }
        continue;
      } else if (status.getCode() == HttpURLConnection.HTTP_MOVED_PERM
          || status.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
        close();
        String newLocation =
            request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER);
        if (newLocation == null) {
          err = request.getErrorMessage();
          break;
        }
        int hostIndex = newLocation.indexOf("://");
        if (hostIndex > 0) {
          hostIndex += 3;
          hostIndex = newLocation.indexOf("/", hostIndex);
        }
        if (hostIndex > 0 && hostIndex < newLocation.length()) {
          String newPath = newLocation.substring(hostIndex);
          if (newPath.endsWith("/")
              && !newPath.endsWith("//")
              && !path.endsWith("/")
              && newPath.substring(0, newPath.length() - 1).equals(path)) {
            path += "//";
            continue;
          }
        }
        err = request.getErrorMessage();
      } else if (request.getErrorMessage() != null) {
        err = request.getErrorMessage();
      } else {
        ntlmProxyAuthIsRequired = false;
        ntlmAuthIsRequired = false;
        negoAuthIsRequired = false;
      }

      if (err != null) {
        break;
      }

      if (myIsProxied) {
        SVNURL location = myRepository.getLocation();
        ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
        ISVNProxyManager proxyManager =
            authManager != null ? authManager.getProxyManager(location) : null;
        if (proxyManager != null) {
          proxyManager.acknowledgeProxyContext(true, null);
        }
      }

      if (httpAuth != null && realm != null && myRepository.getAuthenticationManager() != null) {
        myRepository
            .getAuthenticationManager()
            .acknowledgeAuthentication(
                true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth);
      }
      if (trustManager != null && myRepository.getAuthenticationManager() != null) {
        myRepository.getAuthenticationManager().acknowledgeTrustManager(trustManager);
      }

      if (httpAuth != null) {
        myLastValidAuth = httpAuth;
      }

      status.setHeader(request.getResponseHeader());
      return status;
    }
    // force close on error that was not processed before.
    // these are errors that has no relation to http status (processing error or cancellation).
    close();
    if (err != null
        && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY
        && err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) {
      SVNErrorManager.error(err, SVNLogType.NETWORK);
    }
    // err2 is another default context...
    //        myRepository.getDebugLog().info(err.getMessage());
    myRepository.getDebugLog().logFine(SVNLogType.NETWORK, new Exception(err.getMessage()));
    SVNErrorMessage err2 =
        SVNErrorMessage.create(
            SVNErrorCode.RA_DAV_REQUEST_FAILED,
            "{0} request failed on ''{1}''",
            new Object[] {method, path},
            err.getType(),
            err.getCause());
    SVNErrorManager.error(err, err2, SVNLogType.NETWORK);
    return null;
  }
Esempio n. 24
0
  private void connect(HTTPSSLKeyManager keyManager, TrustManager trustManager)
      throws IOException, SVNException {
    SVNURL location = myRepository.getLocation();

    if (mySocket == null || SVNSocketFactory.isSocketStale(mySocket)) {
      close();
      String host = location.getHost();
      int port = location.getPort();

      ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
      ISVNProxyManager proxyAuth =
          authManager != null ? authManager.getProxyManager(location) : null;
      int connectTimeout = authManager != null ? authManager.getConnectTimeout(myRepository) : 0;
      int readTimeout =
          authManager != null ? authManager.getReadTimeout(myRepository) : DEFAULT_HTTP_TIMEOUT;
      if (readTimeout < 0) {
        readTimeout = DEFAULT_HTTP_TIMEOUT;
      }
      if (proxyAuth != null && proxyAuth.getProxyHost() != null) {
        myRepository
            .getDebugLog()
            .logFine(
                SVNLogType.NETWORK,
                "Using proxy " + proxyAuth.getProxyHost() + " (secured=" + myIsSecured + ")");
        mySocket =
            SVNSocketFactory.createPlainSocket(
                proxyAuth.getProxyHost(), proxyAuth.getProxyPort(), connectTimeout, readTimeout);
        if (myProxyAuthentication == null) {
          myProxyAuthentication =
              new HTTPBasicAuthentication(
                  proxyAuth.getProxyUserName(), proxyAuth.getProxyPassword(), myCharset);
        }
        myIsProxied = true;
        if (myIsSecured) {
          HTTPRequest connectRequest = new HTTPRequest(myCharset);
          connectRequest.setConnection(this);
          connectRequest.initCredentials(myProxyAuthentication, "CONNECT", host + ":" + port);
          connectRequest.setProxyAuthentication(myProxyAuthentication.authenticate());
          connectRequest.setForceProxyAuth(true);
          connectRequest.dispatch("CONNECT", host + ":" + port, null, 0, 0, null);
          HTTPStatus status = connectRequest.getStatus();
          if (status.getCode() == HttpURLConnection.HTTP_OK) {
            myInputStream = null;
            myOutputStream = null;
            mySocket =
                SVNSocketFactory.createSSLSocket(
                    keyManager != null ? new KeyManager[] {keyManager} : new KeyManager[0],
                    trustManager,
                    host,
                    port,
                    mySocket,
                    readTimeout);
            proxyAuth.acknowledgeProxyContext(true, null);
            return;
          }
          SVNURL proxyURL =
              SVNURL.parseURIEncoded(
                  "http://" + proxyAuth.getProxyHost() + ":" + proxyAuth.getProxyPort());
          SVNErrorMessage err =
              SVNErrorMessage.create(
                  SVNErrorCode.RA_DAV_REQUEST_FAILED,
                  "{0} request failed on ''{1}''",
                  new Object[] {"CONNECT", proxyURL});
          proxyAuth.acknowledgeProxyContext(false, err);
          SVNErrorManager.error(err, connectRequest.getErrorMessage(), SVNLogType.NETWORK);
        }
      } else {
        myIsProxied = false;
        myProxyAuthentication = null;
        mySocket =
            myIsSecured
                ? SVNSocketFactory.createSSLSocket(
                    keyManager != null ? new KeyManager[] {keyManager} : new KeyManager[0],
                    trustManager,
                    host,
                    port,
                    connectTimeout,
                    readTimeout)
                : SVNSocketFactory.createPlainSocket(host, port, connectTimeout, readTimeout);
      }
    }
  }