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