Welcome to mirror list, hosted at ThFree Co, Russian Federation.

HttpConnectionManager.java « network « utils « arduino « cc « src « arduino-core - github.com/arduino/Arduino.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: acb754d505545f0fa8d380f19fa0debed36dbd15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*
 * This file is part of Arduino.
 *
 * Copyright 2019 Arduino LLC (http://www.arduino.cc/)
 *
 * Arduino is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As a special exception, you may use this file as part of a free software
 * library without restriction.  Specifically, if other files instantiate
 * templates or use macros or inline functions from this file, or you compile
 * this file and link it with other files to produce an executable, this
 * file does not by itself cause the resulting executable to be covered by
 * the GNU General Public License.  This exception does not however
 * invalidate any other reasons why the executable file might be covered by
 * the GNU General Public License.
 */

package cc.arduino.utils.network;

import cc.arduino.net.CustomProxySelector;
import org.apache.commons.codec.binary.Base64;
import processing.app.BaseNoGui;
import processing.app.PreferencesData;

import javax.script.ScriptException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.UUID;
import java.util.function.Consumer;

public class HttpConnectionManager {
  private static final String userAgent;
  private static final int connectTimeout;
  private static final int maxRedirectNumber;
  private final URL requestURL;
  private final String id;


  static {
    final String defaultUserAgent = String.format(
      "ArduinoIDE/%s (%s; %s; %s; %s) Java/%s (%s)",
      BaseNoGui.VERSION_NAME,
      System.getProperty("os.name"),
      System.getProperty("os.version"),
      System.getProperty("os.arch"),
      System.getProperty("user.language"),
      System.getProperty("java.version"),
      System.getProperty("java.vendor")
    );
    userAgent = PreferencesData.get("http.user_agent", defaultUserAgent);
    int connectTimeoutFromConfig = 5000;
    try {
      connectTimeoutFromConfig = PreferencesData.getInteger("http.connection_timeout_ms", 5000);
    } catch (NumberFormatException e) {
      System.err.println("Error parsing http.connection_timeout_ms config: " + e.getMessage());
    }
    connectTimeout = connectTimeoutFromConfig;
    // Set by default 20 max redirect to follow
    int maxRedirectNumberConfig = 20;
    try {
      maxRedirectNumberConfig = PreferencesData.getInteger("http.max_redirect_number", 20);
    } catch (NumberFormatException e) {
      System.err.println("Error parsing http.max_redirect_number config: " + e.getMessage());
    }
    maxRedirectNumber = maxRedirectNumberConfig;
  }

  public HttpConnectionManager(URL requestURL) {
    this.requestURL = requestURL;
    if (requestURL.getHost().endsWith("arduino.cc")) {
      final String idString = PreferencesData.get("update.id", "0");
      id = Long.toString(Long.parseLong(idString));
    } else {
      id = null;
    }

  }

  public HttpURLConnection makeConnection(Consumer<HttpURLConnection> beforeConnection)
    throws IOException, NoSuchMethodException, ScriptException, URISyntaxException {
    return makeConnection(this.requestURL, 0, beforeConnection);
  }


  public HttpURLConnection makeConnection()
    throws IOException, NoSuchMethodException, ScriptException, URISyntaxException {
    return makeConnection(this.requestURL, 0, (c) -> {
    });
  }

  private HttpURLConnection makeConnection(URL requestURL, int movedTimes,
                                           Consumer<HttpURLConnection> beforeConnection) throws IOException, URISyntaxException, ScriptException, NoSuchMethodException {
    if (movedTimes > maxRedirectNumber) {
      throw new IOException("Too many redirect " + requestURL);
    }

    Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(requestURL.toURI());

    final String requestId = UUID.randomUUID().toString().toUpperCase().replace("-", "").substring(0, 16);
    HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(proxy);

    // see https://github.com/arduino/Arduino/issues/10264
    // Workaround for https://bugs.openjdk.java.net/browse/JDK-8163921
    connection.setRequestProperty("Accept", "*/*");

    connection.setRequestProperty("User-agent", userAgent);
    connection.setRequestProperty("X-Request-ID", requestId);
    if (id != null) {
      connection.setRequestProperty("X-ID", id);
    }
    if (requestURL.getUserInfo() != null) {
      String auth = "Basic " + new String(
        new Base64().encode(requestURL.getUserInfo().getBytes()));
      connection.setRequestProperty("Authorization", auth);
    }

    int initialSize = 0;
    connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
    connection.setConnectTimeout(connectTimeout);
    beforeConnection.accept(connection);

    // Connect
    connection.connect();
    int resp = connection.getResponseCode();

    if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) {
      URL newUrl = new URL(connection.getHeaderField("Location"));
      return this.makeConnection(newUrl, movedTimes + 1, beforeConnection);
    }

    return connection;
  }

}