Ejemplo n.º 1
0
 @Override
 public void validate(final Cookie cookie, final CookieOrigin origin)
     throws MalformedCookieException {
   Args.notNull(cookie, "Cookie");
   Args.notNull(origin, "Cookie origin");
   super.validate(cookie, adjustEffectiveHost(origin));
 }
Ejemplo n.º 2
0
 private static final byte[] toByteArray(
     final HttpEntity entity, int maxContent, MutableBoolean trimmed) throws IOException {
   Args.notNull(entity, "Entity");
   final InputStream instream = entity.getContent();
   if (instream == null) {
     return null;
   }
   try {
     Args.check(
         entity.getContentLength() <= Integer.MAX_VALUE,
         "HTTP entity too large to be buffered in memory");
     int i = (int) entity.getContentLength();
     if (i < 0) {
       i = 4096;
     }
     final ByteArrayBuffer buffer = new ByteArrayBuffer(i);
     final byte[] tmp = new byte[4096];
     int l;
     int total = 0;
     while ((l = instream.read(tmp)) != -1) {
       // check whether we need to trim
       if (maxContent != -1 && total + l > maxContent) {
         buffer.append(tmp, 0, maxContent - total);
         trimmed.setValue(true);
         break;
       }
       buffer.append(tmp, 0, l);
       total += l;
     }
     return buffer.toByteArray();
   } finally {
     instream.close();
   }
 }
Ejemplo n.º 3
0
  /**
   * Produces basic authorization header for the given set of {@link Credentials}.
   *
   * @param credentials The set of credentials to be used for authentication
   * @param request The request being authenticated
   * @throws org.apache.http.auth.InvalidCredentialsException if authentication credentials are not
   *     valid or not applicable for this authentication scheme
   * @throws AuthenticationException if authorization string cannot be generated due to an
   *     authentication failure
   * @return a basic authorization string
   */
  @Override
  public Header authenticate(
      final Credentials credentials, final HttpRequest request, final HttpContext context)
      throws AuthenticationException {

    Args.notNull(credentials, "Credentials");
    Args.notNull(request, "HTTP request");
    final StringBuilder tmp = new StringBuilder();
    tmp.append(credentials.getUserPrincipal().getName());
    tmp.append(":");
    tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());

    final Base64 base64codec = new Base64(0);
    final byte[] base64password =
        base64codec.encode(EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)));

    final CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (isProxy()) {
      buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
      buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Basic ");
    buffer.append(base64password, 0, base64password.length);

    return new BufferedHeader(buffer);
  }
Ejemplo n.º 4
0
  /**
   * Returns a basic {@code Authorization} header value for the given {@link Credentials} and
   * charset.
   *
   * @param credentials The credentials to encode.
   * @param charset The charset to use for encoding the credentials
   * @return a basic authorization header
   * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}.
   */
  @Deprecated
  public static Header authenticate(
      final Credentials credentials, final String charset, final boolean proxy) {
    Args.notNull(credentials, "Credentials");
    Args.notNull(charset, "charset");

    final StringBuilder tmp = new StringBuilder();
    tmp.append(credentials.getUserPrincipal().getName());
    tmp.append(":");
    tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());

    final byte[] base64password =
        Base64.encodeBase64(EncodingUtils.getBytes(tmp.toString(), charset), false);

    final CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (proxy) {
      buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
      buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Basic ");
    buffer.append(base64password, 0, base64password.length);

    return new BufferedHeader(buffer);
  }
 @Override
 public void connect(
     final HttpClientConnection managedConn,
     final HttpRoute route,
     final int connectTimeout,
     final HttpContext context)
     throws IOException {
   Args.notNull(managedConn, "Managed Connection");
   Args.notNull(route, "HTTP route");
   final ManagedHttpClientConnection conn;
   synchronized (managedConn) {
     final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn);
     conn = entry.getConnection();
   }
   final HttpHost host;
   if (route.getProxyHost() != null) {
     host = route.getProxyHost();
   } else {
     host = route.getTargetHost();
   }
   final InetSocketAddress localAddress = route.getLocalSocketAddress();
   SocketConfig socketConfig = this.configData.getSocketConfig(host);
   if (socketConfig == null) {
     socketConfig = this.configData.getDefaultSocketConfig();
   }
   if (socketConfig == null) {
     socketConfig = SocketConfig.DEFAULT;
   }
   this.connectionOperator.connect(
       conn, host, localAddress, connectTimeout, socketConfig, context);
 }
Ejemplo n.º 6
0
  @Override
  public void produceData(final IOSession iosession, final ClientState sessionState)
      throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();

    String myHelo = heloName;
    if (myHelo == null) {
      myHelo = AddressUtils.resolveLocalDomain(iosession.getLocalAddress());
    }
    switch (this.codecState) {
      case EHLO_READY:
        SMTPCommand ehlo = new SMTPCommand("EHLO", myHelo);
        this.writer.write(ehlo, buf);
        this.codecState = CodecState.EHLO_RESPONSE_EXPECTED;
        break;
      case HELO_READY:
        SMTPCommand helo = new SMTPCommand("HELO", myHelo);
        this.writer.write(helo, buf);
        this.codecState = CodecState.HELO_RESPONSE_EXPECTED;
        break;
    }

    if (buf.hasData()) {
      buf.flush(iosession.channel());
    }
    if (!buf.hasData()) {
      iosession.clearEvent(SelectionKey.OP_WRITE);
    }
  }
  /**
   * Instantiate builder. Throws an IllegalArgumentException if either the uri or client are null.
   *
   * @param uri uri of the resource this request is being made to
   * @param client the client
   */
  protected RequestBuilder(final URI uri, final FcrepoClient client) {
    Args.notNull(uri, "uri");
    Args.notNull(client, "client");

    this.targetUri = uri;
    this.client = client;
    this.request = createRequest();
  }
Ejemplo n.º 8
0
 public final HttpHost getHopTarget(final int hop) {
   Args.notNegative(hop, "Hop index");
   final int hopcount = getHopCount();
   Args.check(hop < hopcount, "Hop index exceeds tracked route length");
   if (hop < hopcount - 1) {
     return this.proxyChain.get(hop);
   } else {
     return this.targetHost;
   }
 }
Ejemplo n.º 9
0
 @Override
 public List<Cookie> parse(final Header header, final CookieOrigin origin)
     throws MalformedCookieException {
   Args.notNull(header, "Header");
   Args.notNull(origin, "Cookie origin");
   if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE2)) {
     throw new MalformedCookieException("Unrecognized cookie header '" + header.toString() + "'");
   }
   final HeaderElement[] elems = header.getElements();
   return createCookies(elems, adjustEffectiveHost(origin));
 }
 @Override
 public void routeComplete(
     final HttpClientConnection managedConn, final HttpRoute route, final HttpContext context)
     throws IOException {
   Args.notNull(managedConn, "Managed Connection");
   Args.notNull(route, "HTTP route");
   synchronized (managedConn) {
     final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn);
     entry.markRouteComplete();
   }
 }
 public PipeliningReceiveEnvelopCodec(
     final SMTPBuffers iobuffers, final ProtocolHandler<ServerState> commandHandler) {
   super();
   Args.notNull(iobuffers, "IO buffers");
   Args.notNull(commandHandler, "Command handler");
   this.iobuffers = iobuffers;
   this.commandHandler = commandHandler;
   this.parser = new SMTPCommandParser();
   this.writer = new SMTPReplyWriter(true);
   this.pendingActions = new LinkedList<Action<ServerState>>();
   this.completed = false;
 }
 @Override
 public void upgrade(
     final HttpClientConnection managedConn, final HttpRoute route, final HttpContext context)
     throws IOException {
   Args.notNull(managedConn, "Managed Connection");
   Args.notNull(route, "HTTP route");
   final ManagedHttpClientConnection conn;
   synchronized (managedConn) {
     final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn);
     conn = entry.getConnection();
   }
   this.connectionOperator.upgrade(conn, route.getTargetHost(), context);
 }
  public void update(
      final Socket sock, final HttpHost target, final boolean secure, final HttpParams params)
      throws IOException {

    assertOpen();
    Args.notNull(target, "Target host");
    Args.notNull(params, "Parameters");

    if (sock != null) {
      this.socket = sock;
      bind(sock, params);
    }
    targetHost = target;
    connSecure = secure;
  }
Ejemplo n.º 14
0
  private synchronized int readPlain(final ByteBuffer dst) {
    Args.notNull(dst, "Byte buffer");
    if (this.inPlain.hasData()) {
      // Acquire buffer
      ByteBuffer inPlainBuf = this.inPlain.acquire();

      // Perform opertaions
      inPlainBuf.flip();
      final int n = Math.min(inPlainBuf.remaining(), dst.remaining());
      for (int i = 0; i < n; i++) {
        dst.put(inPlainBuf.get());
      }
      inPlainBuf.compact();

      // Release if empty
      if (inPlainBuf.position() == 0) {
        this.inPlain.release();
        inPlainBuf = null;
      }
      return n;
    } else {
      if (this.endOfStream) {
        return -1;
      } else {
        return 0;
      }
    }
  }
Ejemplo n.º 15
0
 public void writeTo(OutputStream outputStream) throws IOException {
   Args.notNull(outputStream, "Output stream");
   InputStream inputStream = this.content;
   try {
     byte[] bArr = new byte[AnalyticAttribute.ATTRIBUTE_VALUE_MAX_LENGTH];
     if (this.length < 0) {
       while (true) {
         int read = inputStream.read(bArr);
         if (read == -1) {
           break;
         }
         outputStream.write(bArr, 0, read);
       }
     } else {
       long j = this.length;
       while (j > 0) {
         int read2 =
             inputStream.read(
                 bArr, 0, (int) Math.min(PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM, j));
         if (read2 == -1) {
           break;
         }
         outputStream.write(bArr, 0, read2);
         j -= (long) read2;
       }
     }
     inputStream.close();
   } catch (Throwable th) {
     inputStream.close();
   }
 }
Ejemplo n.º 16
0
 /**
  * Allocates buffer of the given size using the given allocator.
  *
  * @param buffersize the buffer size.
  * @param allocator allocator to be used to allocate {@link ByteBuffer}s.
  */
 public ExpandableBuffer(final int buffersize, final ByteBufferAllocator allocator) {
   super();
   Args.notNull(allocator, "ByteBuffer allocator");
   this.allocator = allocator;
   this.buffer = allocator.allocate(buffersize);
   this.mode = INPUT_MODE;
 }
 public long determineLength(HttpMessage httpMessage) throws HttpException {
   Args.notNull(httpMessage, "HTTP message");
   Header firstHeader = httpMessage.getFirstHeader(HTTP.TRANSFER_ENCODING);
   if (firstHeader != null) {
     String value = firstHeader.getValue();
     if (HTTP.CHUNK_CODING.equalsIgnoreCase(value)) {
       if (!httpMessage.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) {
         return -2;
       }
       throw new ProtocolException(
           "Chunked transfer encoding not allowed for " + httpMessage.getProtocolVersion());
     } else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(value)) {
       return -1;
     } else {
       throw new ProtocolException("Unsupported transfer encoding: " + value);
     }
   }
   firstHeader = httpMessage.getFirstHeader(HTTP.CONTENT_LEN);
   if (firstHeader == null) {
     return (long) this.implicitLen;
   }
   String value2 = firstHeader.getValue();
   try {
     long parseLong = Long.parseLong(value2);
     if (parseLong >= 0) {
       return parseLong;
     }
     throw new ProtocolException("Negative content length: " + value2);
   } catch (NumberFormatException e) {
     throw new ProtocolException("Invalid content length: " + value2);
   }
 }
Ejemplo n.º 18
0
  private synchronized int writePlain(final ByteBuffer src) throws SSLException {
    Args.notNull(src, "Byte buffer");
    if (this.status != ACTIVE) {
      return -1;
    }
    if (this.outPlain.hasData()) {
      // Acquire buffers
      ByteBuffer outPlainBuf = this.outPlain.acquire();
      final ByteBuffer outEncryptedBuf = this.outEncrypted.acquire();

      // Perform operations
      outPlainBuf.flip();
      doWrap(outPlainBuf, outEncryptedBuf);
      outPlainBuf.compact();

      // Release outPlain if empty
      if (outPlainBuf.position() == 0) {
        this.outPlain.release();
        outPlainBuf = null;
      }
    }
    if (!this.outPlain.hasData()) {
      final ByteBuffer outEncryptedBuf = this.outEncrypted.acquire();
      final SSLEngineResult result = doWrap(src, outEncryptedBuf);
      if (result.getStatus() == Status.CLOSED) {
        this.status = CLOSED;
      }
      return result.bytesConsumed();
    } else {
      return 0;
    }
  }
Ejemplo n.º 19
0
  public HttpService(
      HttpProcessor var1,
      ConnectionReuseStrategy var2,
      HttpResponseFactory var3,
      HttpRequestHandlerMapper var4,
      HttpExpectationVerifier var5) {
    this.params = null;
    this.processor = null;
    this.handlerMapper = null;
    this.connStrategy = null;
    this.responseFactory = null;
    this.expectationVerifier = null;
    this.processor = (HttpProcessor) Args.notNull(var1, "HTTP processor");
    if (var2 == null) {
      var2 = DefaultConnectionReuseStrategy.INSTANCE;
    }

    this.connStrategy = (ConnectionReuseStrategy) var2;
    if (var3 == null) {
      var3 = DefaultHttpResponseFactory.INSTANCE;
    }

    this.responseFactory = (HttpResponseFactory) var3;
    this.handlerMapper = var4;
    this.expectationVerifier = var5;
  }
Ejemplo n.º 20
0
 public InputStreamEntity(InputStream inputStream, long j, ContentType contentType) {
   this.content = (InputStream) Args.notNull(inputStream, "Source input stream");
   this.length = j;
   if (contentType != null) {
     setContentType(contentType.toString());
   }
 }
 public static CodingErrorAction getUnmappableInputAction(HttpParams paramHttpParams) {
   Args.notNull(paramHttpParams, "HTTP parameters");
   paramHttpParams = paramHttpParams.getParameter("http.unmappable.input.action");
   if (paramHttpParams == null) {
     return CodingErrorAction.REPORT;
   }
   return (CodingErrorAction) paramHttpParams;
 }
 public static ProtocolVersion getVersion(HttpParams paramHttpParams) {
   Args.notNull(paramHttpParams, "HTTP parameters");
   paramHttpParams = paramHttpParams.getParameter("http.protocol.version");
   if (paramHttpParams == null) {
     return HttpVersion.HTTP_1_1;
   }
   return (ProtocolVersion) paramHttpParams;
 }
Ejemplo n.º 23
0
 /**
  * Returns lookup interface for maximum number of connections allowed per route.
  *
  * @param params HTTP parameters
  * @return lookup interface for maximum number of connections allowed per route.
  */
 public static ConnPerRoute getMaxConnectionsPerRoute(final HttpParams params) {
   Args.notNull(params, "HTTP parameters");
   ConnPerRoute connPerRoute = (ConnPerRoute) params.getParameter(MAX_CONNECTIONS_PER_ROUTE);
   if (connPerRoute == null) {
     connPerRoute = DEFAULT_CONN_PER_ROUTE;
   }
   return connPerRoute;
 }
  @Override
  public void produceData(final IOSession iosession, final ServerState sessionState)
      throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();

    synchronized (sessionState) {
      if (this.actionFuture != null) {
        SMTPReply reply = getReply(this.actionFuture);
        this.actionFuture = null;
        this.writer.write(reply, buf);
      }

      if (this.actionFuture == null) {
        while (!this.pendingActions.isEmpty()) {
          Action<ServerState> action = this.pendingActions.remove();
          Future<SMTPReply> future =
              action.execute(sessionState, new OutputTrigger<SMTPReply>(sessionState, iosession));
          if (future.isDone()) {
            SMTPReply reply = getReply(future);
            this.writer.write(reply, buf);
          } else {
            this.actionFuture = future;
            break;
          }
        }
      }

      if (buf.hasData()) {
        buf.flush(iosession.channel());
      }
      if (!buf.hasData()) {
        if (sessionState.getDataType() != null) {
          this.completed = true;
        }
        if (sessionState.isTerminated()) {
          iosession.close();
        } else {
          iosession.clearEvent(SelectionKey.OP_WRITE);
        }
      }
    }
  }
 public static String getHttpElementCharset(HttpParams paramHttpParams) {
   Args.notNull(paramHttpParams, "HTTP parameters");
   String str = (String) paramHttpParams.getParameter("http.protocol.element-charset");
   paramHttpParams = str;
   if (str == null) {
     paramHttpParams = HTTP.DEF_PROTOCOL_CHARSET.name();
   }
   return paramHttpParams;
 }
Ejemplo n.º 26
0
 public static SocketConfig.Builder copy(final SocketConfig config) {
   Args.notNull(config, "Socket config");
   return new Builder()
       .setSoTimeout(config.getSoTimeout())
       .setSoReuseAddress(config.isSoReuseAddress())
       .setSoLinger(config.getSoLinger())
       .setSoKeepAlive(config.isSoKeepAlive())
       .setTcpNoDelay(config.isTcpNoDelay());
 }
Ejemplo n.º 27
0
 /**
  * Creates a StringEntityHC4 with the specified content, MIME type and charset
  *
  * @param string content to be used. Not {@code null}.
  * @param mimeType MIME type to be used. May be {@code null}, in which case the default is {@link
  *     HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain"
  * @param charset character set to be used. May be {@code null}, in which case the default is
  *     {@link HTTP#DEFAULT_CONTENT_CHARSET} i.e. "ISO-8859-1"
  * @throws UnsupportedEncodingException If the named charset is not supported.
  * @since 4.1
  * @throws IllegalArgumentException if the string parameter is null
  * @deprecated (4.1.3) use {@link #StringEntityHC4(String, ContentType)}
  */
 @Deprecated
 public StringEntityHC4(final String string, final String mimeType, final String charset)
     throws UnsupportedEncodingException {
   super();
   Args.notNull(string, "Source string");
   final String mt = mimeType != null ? mimeType : HTTP.PLAIN_TEXT_TYPE;
   final String cs = charset != null ? charset : HTTP.DEFAULT_CONTENT_CHARSET;
   this.content = string.getBytes(cs);
   setContentType(mt + HTTP.CHARSET_PARAM + cs);
 }
Ejemplo n.º 28
0
 /**
  * Creates a new route through a proxy. When using this constructor, the <code>proxy</code> MUST
  * be given. For convenience, it is assumed that a secure connection will be layered over a tunnel
  * through the proxy.
  *
  * @param target the host to which to route
  * @param local the local address to route from, or <code>null</code> for the default
  * @param proxy the proxy to use
  * @param secure <code>true</code> if the route is (to be) secure, <code>false</code> otherwise
  */
 public HttpRoute(
     final HttpHost target, final InetAddress local, final HttpHost proxy, final boolean secure) {
   this(
       target,
       local,
       Collections.singletonList(Args.notNull(proxy, "Proxy host")),
       secure,
       secure ? TunnelType.TUNNELLED : TunnelType.PLAIN,
       secure ? LayerType.LAYERED : LayerType.PLAIN);
 }
 /**
  * Creates a new simple connection manager.
  *
  * @param schreg the scheme registry
  */
 public SingleClientConnManager(final SchemeRegistry schreg) {
   Args.notNull(schreg, "Scheme registry");
   this.schemeRegistry = schreg;
   this.connOperator = createConnectionOperator(schreg);
   this.uniquePoolEntry = new PoolEntry();
   this.managedConn = null;
   this.lastReleaseTime = -1L;
   this.alwaysShutDown = false; // @@@ from params? as argument?
   this.isShutDown = false;
 }
 /**
  * @deprecated (4.3) use {@link DefaultHttpResponseParser#DefaultHttpResponseParser(
  *     SessionInputBuffer, LineParser, HttpResponseFactory, MessageConstraints)}
  */
 @Deprecated
 public DefaultHttpResponseParser(
     final SessionInputBuffer buffer,
     final LineParser parser,
     final HttpResponseFactory responseFactory,
     final HttpParams params) {
   super(buffer, parser, params);
   Args.notNull(responseFactory, "Response factory");
   this.responseFactory = responseFactory;
   this.lineBuf = new CharArrayBuffer(128);
 }