001package com.box.sdk;
002
003import java.io.ByteArrayInputStream;
004import java.io.IOException;
005import java.io.InputStream;
006import java.io.OutputStream;
007import java.net.HttpURLConnection;
008import java.net.MalformedURLException;
009import java.net.ProtocolException;
010import java.net.URL;
011import java.security.KeyManagementException;
012import java.security.NoSuchAlgorithmException;
013import java.util.ArrayList;
014import java.util.List;
015import java.util.Map;
016import java.util.logging.Level;
017import java.util.logging.Logger;
018import javax.net.ssl.HttpsURLConnection;
019import javax.net.ssl.SSLContext;
020import javax.net.ssl.SSLParameters;
021
022import com.box.sdk.http.HttpHeaders;
023import com.box.sdk.http.HttpMethod;
024
025
026/**
027 * Used to make HTTP requests to the Box API.
028 *
029 * <p>All requests to the REST API are sent using this class or one of its subclasses. This class wraps {@link
030 * HttpURLConnection} in order to provide a simpler interface that can automatically handle various conditions specific
031 * to Box's API. Requests will be authenticated using a {@link BoxAPIConnection} (if one is provided), so it isn't
032 * necessary to add authorization headers. Requests can also be sent more than once, unlike with HttpURLConnection. If
033 * an error occurs while sending a request, it will be automatically retried (with a back off delay) up to the maximum
034 * number of times set in the BoxAPIConnection.</p>
035 *
036 * <p>Specifying a body for a BoxAPIRequest is done differently than it is with HttpURLConnection. Instead of writing to
037 * an OutputStream, the request is provided an {@link InputStream} which will be read when the {@link #send} method is
038 * called. This makes it easy to retry requests since the stream can automatically reset and reread with each attempt.
039 * If the stream cannot be reset, then a new stream will need to be provided before each call to send. There is also a
040 * convenience method for specifying the body as a String, which simply wraps the String with an InputStream.</p>
041 */
042public class BoxAPIRequest {
043    private static final Logger LOGGER = Logger.getLogger(BoxAPIRequest.class.getName());
044    private static final int BUFFER_SIZE = 8192;
045    private static final int MAX_REDIRECTS = 3;
046
047    private final BoxAPIConnection api;
048    private final List<RequestHeader> headers;
049    private final String method;
050
051    private URL url;
052    private BackoffCounter backoffCounter;
053    private int connectTimeout;
054    private int readTimeout;
055    private InputStream body;
056    private long bodyLength;
057    private Map<String, List<String>> requestProperties;
058    private int numRedirects;
059    private boolean followRedirects = true;
060    private boolean shouldAuthenticate;
061    private SSLContext sslContext;
062
063    /**
064     * Constructs an unauthenticated BoxAPIRequest.
065     * @param  url    the URL of the request.
066     * @param  method the HTTP method of the request.
067     */
068    public BoxAPIRequest(URL url, String method) {
069        this(null, url, method);
070    }
071
072    /**
073     * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection.
074     * @param  api    an API connection for authenticating the request.
075     * @param  url    the URL of the request.
076     * @param  method the HTTP method of the request.
077     */
078    public BoxAPIRequest(BoxAPIConnection api, URL url, String method) {
079        this.api = api;
080        this.url = url;
081        this.method = method;
082        this.headers = new ArrayList<RequestHeader>();
083        if (api != null) {
084            Map<String, String> customHeaders = api.getHeaders();
085            if (customHeaders != null) {
086                for (String header : customHeaders.keySet()) {
087                    this.addHeader(header, customHeaders.get(header));
088                }
089            }
090            this.headers.add(new RequestHeader("X-Box-UA", api.getBoxUAHeader()));
091        }
092        this.backoffCounter = new BackoffCounter(new Time());
093        this.shouldAuthenticate = true;
094        this.connectTimeout = BoxGlobalSettings.getConnectTimeout();
095        this.readTimeout = BoxGlobalSettings.getReadTimeout();
096
097        this.addHeader("Accept-Encoding", "gzip");
098        this.addHeader("Accept-Charset", "utf-8");
099
100        // Setup the SSL context manually to force newer TLS version on legacy Java environments
101        // This is necessary because Java 7 uses TLSv1.0 by default, but the Box API will need
102        // to deprecate this protocol in the future.  To prevent clients from breaking, we must
103        // ensure that they are using TLSv1.1 or greater!
104        SSLContext sc = null;
105        try {
106            sc = SSLContext.getDefault();
107            SSLParameters params = sc.getDefaultSSLParameters();
108            boolean supportsNewTLS = false;
109            for (String protocol : params.getProtocols()) {
110                if (protocol.compareTo("TLSv1") > 0) {
111                    supportsNewTLS = true;
112                    break;
113                }
114            }
115            if (!supportsNewTLS) {
116                // Try to upgrade to a higher TLS version
117                sc = null;
118                sc = SSLContext.getInstance("TLSv1.1");
119                sc.init(null, null, new java.security.SecureRandom());
120                sc = SSLContext.getInstance("TLSv1.2");
121                sc.init(null, null, new java.security.SecureRandom());
122            }
123        } catch (NoSuchAlgorithmException ex) {
124            if (sc == null) {
125                LOGGER.warning("Unable to set up SSL context for HTTPS!  This may result in the inability "
126                        + " to connect to the Box API.");
127            }
128            if (sc != null && sc.getProtocol().equals("TLSv1")) {
129                // Could not find a good version of TLS
130                LOGGER.warning("Using deprecated TLSv1 protocol, which will be deprecated by the Box API!  Upgrade "
131                        + "to a newer version of Java as soon as possible.");
132            }
133        } catch (KeyManagementException ex) {
134
135            LOGGER.warning("Exception when initializing SSL Context!  This may result in the inabilty to connect to "
136                    + "the Box API");
137            sc = null;
138        }
139        this.sslContext = sc;
140    }
141
142    /**
143     * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection.
144     * @param  api    an API connection for authenticating the request.
145     * @param  url the URL of the request.
146     * @param  method the HTTP method of the request.
147     */
148    public BoxAPIRequest(BoxAPIConnection api, URL url, HttpMethod method) {
149        this(api, url, method.name());
150    }
151
152    /**
153     * Constructs an request, using URL and HttpMethod.
154     * @param  url the URL of the request.
155     * @param  method the HTTP method of the request.
156     */
157    public BoxAPIRequest(URL url, HttpMethod method) {
158        this(url, method.name());
159    }
160
161    /**
162     * Adds an HTTP header to this request.
163     * @param key   the header key.
164     * @param value the header value.
165     */
166    public void addHeader(String key, String value) {
167        if ("As-User".equals(key)) {
168            int index = this.headers.indexOf("As-User");
169            if (index > -1) {
170                this.headers.remove(index);
171            }
172        }
173        if (key.equals("X-Box-UA")) {
174            throw new IllegalArgumentException("Altering the X-Box-UA header is not permitted");
175        }
176        this.headers.add(new RequestHeader(key, value));
177    }
178
179    /**
180     * Sets a Connect timeout for this request in milliseconds.
181     * @param timeout the timeout in milliseconds.
182     */
183    public void setConnectTimeout(int timeout) {
184        this.connectTimeout = timeout;
185    }
186
187    /**
188     * Sets a read timeout for this request in milliseconds.
189     * @param timeout the timeout in milliseconds.
190     */
191    public void setReadTimeout(int timeout) {
192        this.readTimeout = timeout;
193    }
194
195  /**
196     * Sets whether or not to follow redirects (i.e. Location header)
197     * @param followRedirects true to follow, false to not follow
198     */
199    public void setFollowRedirects(boolean followRedirects) {
200        this.followRedirects = followRedirects;
201    }
202
203    /**
204     * Gets the stream containing contents of this request's body.
205     *
206     * <p>Note that any bytes that read from the returned stream won't be sent unless the stream is reset back to its
207     * initial position.</p>
208     *
209     * @return an InputStream containing the contents of this request's body.
210     */
211    public InputStream getBody() {
212        return this.body;
213    }
214
215    /**
216     * Sets the request body to the contents of an InputStream.
217     *
218     * <p>The stream must support the {@link InputStream#reset} method if auto-retry is used or if the request needs to
219     * be resent. Otherwise, the body must be manually set before each call to {@link #send}.</p>
220     *
221     * @param stream an InputStream containing the contents of the body.
222     */
223    public void setBody(InputStream stream) {
224        this.body = stream;
225    }
226
227    /**
228     * Sets the request body to the contents of an InputStream.
229     *
230     * <p>Providing the length of the InputStream allows for the progress of the request to be monitored when calling
231     * {@link #send(ProgressListener)}.</p>
232     *
233     * <p> See {@link #setBody(InputStream)} for more information on setting the body of the request.</p>
234     *
235     * @param stream an InputStream containing the contents of the body.
236     * @param length the expected length of the stream.
237     */
238    public void setBody(InputStream stream, long length) {
239        this.bodyLength = length;
240        this.body = stream;
241    }
242
243    /**
244     * Sets the request body to the contents of a String.
245     *
246     * <p>If the contents of the body are large, then it may be more efficient to use an {@link InputStream} instead of
247     * a String. Using a String requires that the entire body be in memory before sending the request.</p>
248     *
249     * @param body a String containing the contents of the body.
250     */
251    public void setBody(String body) {
252        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
253        this.bodyLength = bytes.length;
254        this.body = new ByteArrayInputStream(bytes);
255    }
256
257    /**
258     * Gets the URL from the request.
259     *
260     * @return a URL containing the URL of the request.
261     */
262    public URL getUrl() {
263        return this.url;
264    }
265
266    /**
267     * Gets the http method from the request.
268     *
269     * @return http method
270     */
271    public String getMethod() {
272        return this.method;
273    }
274
275    /**
276     * Get headers as list of RequestHeader objects.
277     * @return headers as list of RequestHeader objects
278     */
279    protected List<RequestHeader> getHeaders() {
280        return this.headers;
281    }
282
283    /**
284     * Sends this request and returns a BoxAPIResponse containing the server's response.
285     *
286     * <p>The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it
287     * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response,
288     * then it can be cast to a {@link BoxJSONResponse} like so:</p>
289     *
290     * <pre>BoxJSONResponse response = (BoxJSONResponse) request.send();</pre>
291     *
292     * <p>If the server returns an error code or if a network error occurs, then the request will be automatically
293     * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException}
294     * will be thrown.</p>
295     *
296     * @throws BoxAPIException if the server returns an error code or if a network error occurs.
297     * @return a {@link BoxAPIResponse} containing the server's response.
298     */
299    public BoxAPIResponse send() {
300        return this.send(null);
301    }
302
303    /**
304     * Sends this request while monitoring its progress and returns a BoxAPIResponse containing the server's response.
305     *
306     * <p>A ProgressListener is generally only useful when the size of the request is known beforehand. If the size is
307     * unknown, then the ProgressListener will be updated for each byte sent, but the total number of bytes will be
308     * reported as 0.</p>
309     *
310     * <p> See {@link #send} for more information on sending requests.</p>
311     *
312     * @param  listener a listener for monitoring the progress of the request.
313     * @throws BoxAPIException if the server returns an error code or if a network error occurs.
314     * @return a {@link BoxAPIResponse} containing the server's response.
315     */
316    public BoxAPIResponse send(ProgressListener listener) {
317        if (this.api == null) {
318            this.backoffCounter.reset(BoxAPIConnection.DEFAULT_MAX_ATTEMPTS);
319        } else {
320            this.backoffCounter.reset(this.api.getMaxRequestAttempts());
321        }
322
323        while (this.backoffCounter.getAttemptsRemaining() > 0) {
324            try {
325                return this.trySend(listener);
326            } catch (BoxAPIException apiException) {
327                if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) {
328                    throw apiException;
329                }
330
331                try {
332                    this.resetBody();
333                } catch (IOException ioException) {
334                    throw apiException;
335                }
336
337                try {
338                    this.backoffCounter.waitBackoff();
339                } catch (InterruptedException interruptedException) {
340                    Thread.currentThread().interrupt();
341                    throw apiException;
342                }
343            }
344        }
345
346        throw new RuntimeException();
347    }
348
349    /**
350     * Returns a String containing the URL, HTTP method, headers and body of this request.
351     * @return a String containing information about this request.
352     */
353    @Override
354    public String toString() {
355        String lineSeparator = System.getProperty("line.separator");
356        StringBuilder builder = new StringBuilder();
357        builder.append("Request");
358        builder.append(lineSeparator);
359        builder.append(this.method);
360        builder.append(' ');
361        builder.append(this.url.toString());
362        builder.append(lineSeparator);
363
364        for (Map.Entry<String, List<String>> entry : this.requestProperties.entrySet()) {
365            List<String> nonEmptyValues = new ArrayList<String>();
366            for (String value : entry.getValue()) {
367                if (value != null && value.trim().length() != 0) {
368                    nonEmptyValues.add(value);
369                }
370            }
371
372            if (nonEmptyValues.size() == 0) {
373                continue;
374            }
375
376            builder.append(entry.getKey());
377            builder.append(": ");
378            for (String value : nonEmptyValues) {
379                builder.append(value);
380                builder.append(", ");
381            }
382
383            builder.delete(builder.length() - 2, builder.length());
384            builder.append(lineSeparator);
385        }
386
387        String bodyString = this.bodyToString();
388        if (bodyString != null) {
389            builder.append(lineSeparator);
390            builder.append(bodyString);
391        }
392
393        return builder.toString().trim();
394    }
395
396    /**
397     * Returns a String representation of this request's body used in {@link #toString}. This method returns
398     * null by default.
399     *
400     * <p>A subclass may want override this method if the body can be converted to a String for logging or debugging
401     * purposes.</p>
402     *
403     * @return a String representation of this request's body.
404     */
405    protected String bodyToString() {
406        return null;
407    }
408
409    /**
410     * Writes the body of this request to an HttpURLConnection.
411     *
412     * <p>Subclasses overriding this method must remember to close the connection's OutputStream after writing.</p>
413     *
414     * @param connection the connection to which the body should be written.
415     * @param listener   an optional listener for monitoring the write progress.
416     * @throws BoxAPIException if an error occurs while writing to the connection.
417     */
418    protected void writeBody(HttpURLConnection connection, ProgressListener listener) {
419        if (this.body == null) {
420            return;
421        }
422
423        connection.setDoOutput(true);
424        try {
425            OutputStream output = connection.getOutputStream();
426            if (listener != null) {
427                output = new ProgressOutputStream(output, listener, this.bodyLength);
428            }
429            int b = this.body.read();
430            while (b != -1) {
431                output.write(b);
432                b = this.body.read();
433            }
434            output.close();
435        } catch (IOException e) {
436            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
437        }
438    }
439
440    /**
441     * Resets the InputStream containing this request's body.
442     *
443     * <p>This method will be called before each attempt to resend the request, giving subclasses an opportunity to
444     * reset any streams that need to be read when sending the body.</p>
445     *
446     * @throws IOException if the stream cannot be reset.
447     */
448    protected void resetBody() throws IOException {
449        if (this.body != null) {
450            this.body.reset();
451        }
452    }
453
454    void setBackoffCounter(BackoffCounter counter) {
455        this.backoffCounter = counter;
456    }
457
458    private BoxAPIResponse trySend(ProgressListener listener) {
459        if (this.api != null) {
460            RequestInterceptor interceptor = this.api.getRequestInterceptor();
461            if (interceptor != null) {
462                BoxAPIResponse response = interceptor.onRequest(this);
463                if (response != null) {
464                    return response;
465                }
466            }
467        }
468
469        HttpURLConnection connection = this.createConnection();
470
471        if (connection instanceof HttpsURLConnection) {
472            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
473
474            if (this.sslContext != null) {
475                httpsConnection.setSSLSocketFactory(this.sslContext.getSocketFactory());
476            }
477        }
478
479        if (this.bodyLength > 0) {
480            connection.setFixedLengthStreamingMode((int) this.bodyLength);
481            connection.setDoOutput(true);
482        }
483
484        if (this.api != null) {
485            if (this.shouldAuthenticate) {
486                connection.addRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + this.api.lockAccessToken());
487            }
488            connection.setRequestProperty("User-Agent", this.api.getUserAgent());
489            if (this.api.getProxy() != null) {
490                if (this.api.getProxyUsername() != null && this.api.getProxyPassword() != null) {
491                    String usernameAndPassword = this.api.getProxyUsername() + ":" + this.api.getProxyPassword();
492                    String encoded = new String(Base64.encode(usernameAndPassword.getBytes()));
493                    connection.addRequestProperty("Proxy-Authorization", "Basic " + encoded);
494                }
495            }
496
497            if (this.api instanceof SharedLinkAPIConnection) {
498                SharedLinkAPIConnection sharedItemAPI = (SharedLinkAPIConnection) this.api;
499                String sharedLink = sharedItemAPI.getSharedLink();
500                String boxAPIValue = "shared_link=" + sharedLink;
501                String sharedLinkPassword = sharedItemAPI.getSharedLinkPassword();
502                if (sharedLinkPassword != null) {
503                    boxAPIValue += "&shared_link_password=" + sharedLinkPassword;
504                }
505                connection.addRequestProperty("BoxApi", boxAPIValue);
506            }
507        }
508
509        this.requestProperties = connection.getRequestProperties();
510
511        int responseCode;
512        try {
513            this.writeBody(connection, listener);
514
515            // Ensure that we're connected in case writeBody() didn't write anything.
516            try {
517                connection.connect();
518            } catch (IOException e) {
519                throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
520            }
521
522            this.logRequest(connection);
523
524            // We need to manually handle redirects by creating a new HttpURLConnection so that connection pooling
525            // happens correctly. There seems to be a bug in Oracle's Java implementation where automatically handled
526            // redirects will not keep the connection alive.
527            try {
528                responseCode = connection.getResponseCode();
529            } catch (IOException e) {
530                throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
531            }
532        } finally {
533            if (this.api != null && this.shouldAuthenticate) {
534                this.api.unlockAccessToken();
535            }
536        }
537
538        if (isResponseRedirect(responseCode)) {
539            return this.handleRedirect(connection, listener);
540        }
541
542        String contentType = connection.getContentType();
543        BoxAPIResponse response;
544        if (contentType == null) {
545            response = new BoxAPIResponse(connection);
546        } else if (contentType.contains("application/json")) {
547            response = new BoxJSONResponse(connection);
548        } else {
549            response = new BoxAPIResponse(connection);
550        }
551
552        return response;
553    }
554
555    private BoxAPIResponse handleRedirect(HttpURLConnection connection, ProgressListener listener) {
556        if (this.numRedirects >= MAX_REDIRECTS) {
557            throw new BoxAPIException("The Box API responded with too many redirects.");
558        }
559        this.numRedirects++;
560
561        // Even though the redirect response won't have a body, we need to read the InputStream so that Java will put
562        // the connection back in the connection pool.
563        try {
564            InputStream stream = connection.getInputStream();
565            byte[] buffer = new byte[8192];
566            int n = stream.read(buffer);
567            while (n != -1) {
568                n = stream.read(buffer);
569            }
570            stream.close();
571        } catch (IOException e) {
572            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
573        }
574
575        String redirect = connection.getHeaderField("Location");
576        try {
577            this.url = new URL(redirect);
578        } catch (MalformedURLException e) {
579            throw new BoxAPIException("The Box API responded with an invalid redirect.", e);
580        }
581
582        if (this.followRedirects) {
583            return this.trySend(listener);
584        } else {
585            BoxRedirectResponse redirectResponse = new BoxRedirectResponse();
586            redirectResponse.setRedirectURL(this.url);
587            return redirectResponse;
588        }
589    }
590
591    private void logRequest(HttpURLConnection connection) {
592        if (LOGGER.isLoggable(Level.FINE)) {
593            LOGGER.log(Level.FINE, this.toString());
594        }
595    }
596
597    private HttpURLConnection createConnection() {
598        HttpURLConnection connection = null;
599
600        try {
601            if (this.api == null || this.api.getProxy() == null) {
602                connection = (HttpURLConnection) this.url.openConnection();
603            } else {
604                connection = (HttpURLConnection) this.url.openConnection(this.api.getProxy());
605            }
606        } catch (IOException e) {
607            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
608        }
609
610        try {
611            connection.setRequestMethod(this.method);
612        } catch (ProtocolException e) {
613            throw new BoxAPIException("Couldn't connect to the Box API because the request's method was invalid.", e);
614        }
615
616        connection.setConnectTimeout(this.connectTimeout);
617        connection.setReadTimeout(this.readTimeout);
618
619        // Don't allow HttpURLConnection to automatically redirect because it messes up the connection pool. See the
620        // trySend(ProgressListener) method for how we handle redirects.
621        connection.setInstanceFollowRedirects(false);
622
623        for (RequestHeader header : this.headers) {
624            connection.addRequestProperty(header.getKey(), header.getValue());
625        }
626
627        return connection;
628    }
629
630    void shouldAuthenticate(boolean shouldAuthenticate) {
631        this.shouldAuthenticate = shouldAuthenticate;
632    }
633
634    private static boolean isResponseRetryable(int responseCode) {
635        return (responseCode >= 500 || responseCode == 429);
636    }
637    private static boolean isResponseRedirect(int responseCode) {
638        return (responseCode == 301 || responseCode == 302);
639    }
640
641    /**
642     * Class for mapping a request header and value.
643     */
644    public final class RequestHeader {
645        private final String key;
646        private final String value;
647
648        /**
649         * Construct a request header from header key and value.
650         * @param key header name
651         * @param value header value
652         */
653        public RequestHeader(String key, String value) {
654            this.key = key;
655            this.value = value;
656        }
657
658        /**
659         * Get header key.
660         * @return http header name
661         */
662        public String getKey() {
663            return this.key;
664        }
665
666        /**
667         * Get header value.
668         * @return http header value
669         */
670        public String getValue() {
671            return this.value;
672        }
673    }
674}