aboutsummaryrefslogtreecommitdiffstats
path: root/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/repository/AddonsListFetcher.java
blob: 088064524609aa0e65807260a09026581887a6ee (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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.sdklib.internal.repository;

import com.android.annotations.VisibleForTesting;
import com.android.annotations.VisibleForTesting.Visibility;
import com.android.sdklib.repository.SdkAddonsListConstants;
import com.android.sdklib.repository.SdkRepoConstants;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLKeyException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

/**
 * Fetches and loads an sdk-addons-list XML.
 * <p/>
 * Such an XML contains a simple list of add-ons site that are to be loaded by default by the
 * SDK Manager. <br/>
 * The XML must conform to the sdk-addons-list-N.xsd. <br/>
 * Constants used in the XML are defined in {@link SdkAddonsListConstants}.
 */
public class AddonsListFetcher {

    public enum SiteType {
        ADDON_SITE,
        SYS_IMG_SITE
    }

    /**
     * An immutable structure representing an add-on site.
     */
    public static class Site {
        private final String mUrl;
        private final String mUiName;
        private final SiteType mType;

        private Site(String url, String uiName, SiteType type) {
            mType = type;
            mUrl = url.trim();
            mUiName = uiName;
        }

        public String getUrl() {
            return mUrl;
        }

        public String getUiName() {
            return mUiName;
        }

        public SiteType getType() {
            return mType;
        }

        /** Returns a debug string representation of this object. Not for user display. */
        @Override
        public String toString() {
            return String.format("<%1$s URL='%2$s' Name='%3$s'>",   //$NON-NLS-1$
                                 mType, mUrl, mUiName);
        }
    }

    /**
     * Fetches the addons list from the given URL.
     *
     * @param url The URL of an XML file resource that conforms to the latest sdk-addons-list-N.xsd.
     *   For the default operation, use {@link SdkAddonsListConstants#URL_ADDON_LIST}.
     *   Cannot be null.
     * @param cache The {@link DownloadCache} instance to use. Cannot be null.
     * @param monitor A monitor to report errors. Cannot be null.
     * @return An array of {@link Site} on success (possibly empty), or null on error.
     */
    public Site[] fetch(String url, DownloadCache cache, ITaskMonitor monitor) {

        url = url == null ? "" : url.trim();

        monitor.setProgressMax(6);
        monitor.setDescription("Fetching %1$s", url);
        monitor.incProgress(1);

        Exception[] exception = new Exception[] { null };
        Boolean[] validatorFound = new Boolean[] { Boolean.FALSE };
        String[] validationError = new String[] { null };
        Document validatedDoc = null;
        String validatedUri = null;

        String[] defaultNames = new String[SdkAddonsListConstants.NS_LATEST_VERSION];
        for (int version = SdkAddonsListConstants.NS_LATEST_VERSION, i = 0;
                version >= 1;
                version--, i++) {
            defaultNames[i] = SdkAddonsListConstants.getDefaultName(version);
        }

        InputStream xml = fetchUrl(url, cache, monitor.createSubMonitor(1), exception);
        if (xml != null) {
            int version = getXmlSchemaVersion(xml);
            if (version == 0) {
                xml = null;
            }
        }

        // If we can't find the latest version, try earlier schema versions.
        if (xml == null && defaultNames.length > 0) {
            ITaskMonitor subMonitor = monitor.createSubMonitor(1);
            subMonitor.setProgressMax(defaultNames.length);

            String baseUrl = url;
            if (!baseUrl.endsWith("/")) {                       //$NON-NLS-1$
                int pos = baseUrl.lastIndexOf('/');
                if (pos > 0) {
                    baseUrl = baseUrl.substring(0, pos + 1);
                }
            }

            for (String name : defaultNames) {
                String newUrl = baseUrl + name;
                if (newUrl.equals(url)) {
                    continue;
                }
                xml = fetchUrl(newUrl, cache, subMonitor.createSubMonitor(1), exception);
                if (xml != null) {
                    int version = getXmlSchemaVersion(xml);
                    if (version == 0) {
                        xml = null;
                    } else {
                        url = newUrl;
                        subMonitor.incProgress(
                                subMonitor.getProgressMax() - subMonitor.getProgress());
                        break;
                    }
                }
            }
        } else {
            monitor.incProgress(1);
        }

        if (xml != null) {
            monitor.setDescription("Validate XML");

            // Explore the XML to find the potential XML schema version
            int version = getXmlSchemaVersion(xml);

            if (version >= 1 && version <= SdkAddonsListConstants.NS_LATEST_VERSION) {
                // This should be a version we can handle. Try to validate it
                // and report any error as invalid XML syntax,

                String uri = validateXml(xml, url, version, validationError, validatorFound);
                if (uri != null) {
                    // Validation was successful
                    validatedDoc = getDocument(xml, monitor);
                    validatedUri = uri;

                }
            } else if (version > SdkAddonsListConstants.NS_LATEST_VERSION) {
                // The schema used is more recent than what is supported by this tool.
                // We don't have an upgrade-path support yet, so simply ignore the document.
                return null;
            }
        }

        // If any exception was handled during the URL fetch, display it now.
        if (exception[0] != null) {
            String reason = null;
            if (exception[0] instanceof FileNotFoundException) {
                // FNF has no useful getMessage, so we need to special handle it.
                reason = "File not found";
            } else if (exception[0] instanceof UnknownHostException &&
                    exception[0].getMessage() != null) {
                // This has no useful getMessage yet could really use one
                reason = String.format("Unknown Host %1$s", exception[0].getMessage());
            } else if (exception[0] instanceof SSLKeyException) {
                // That's a common error and we have a pref for it.
                reason = "HTTPS SSL error. You might want to force download through HTTP in the settings.";
            } else if (exception[0].getMessage() != null) {
                reason = exception[0].getMessage();
            } else {
                // We don't know what's wrong. Let's give the exception class at least.
                reason = String.format("Unknown (%1$s)", exception[0].getClass().getName());
            }

            monitor.logError("Failed to fetch URL %1$s, reason: %2$s", url, reason);
        }

        if (validationError[0] != null) {
            monitor.logError("%s", validationError[0]);  //$NON-NLS-1$
        }

        // Stop here if we failed to validate the XML. We don't want to load it.
        if (validatedDoc == null) {
            return null;
        }

        monitor.incProgress(1);

        Site[] result = null;

        if (xml != null) {
            monitor.setDescription("Parse XML");
            monitor.incProgress(1);
            result = parseAddonsList(validatedDoc, validatedUri, monitor);
        }

        // done
        monitor.incProgress(1);

        return result;
    }

    /**
     * Fetches the document at the given URL and returns it as a stream. Returns
     * null if anything wrong happens. References: <br/>
     * URL Connection:
     *
     * @param urlString The URL to load, as a string.
     * @param monitor {@link ITaskMonitor} related to this URL.
     * @param outException If non null, where to store any exception that
     *            happens during the fetch.
     * @see UrlOpener UrlOpener, which handles all URL logic.
     */
    private InputStream fetchUrl(String urlString,
            DownloadCache cache,
            ITaskMonitor monitor,
            Exception[] outException) {
        try {
            return cache.openCachedUrl(urlString, monitor);
        } catch (Exception e) {
            if (outException != null) {
                outException[0] = e;
            }
        }

        return null;
    }

    /**
     * Manually parses the root element of the XML to extract the schema version
     * at the end of the xmlns:sdk="http://schemas.android.com/sdk/android/addons-list/$N"
     * declaration.
     *
     * @return 1..{@link SdkAddonsListConstants#NS_LATEST_VERSION} for a valid schema version
     *         or 0 if no schema could be found.
     */
    @VisibleForTesting(visibility=Visibility.PRIVATE)
    protected int getXmlSchemaVersion(InputStream xml) {
        if (xml == null) {
            return 0;
        }

        // Get an XML document
        Document doc = null;
        try {
            xml.reset();

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setIgnoringComments(false);
            factory.setValidating(false);

            // Parse the old document using a non namespace aware builder
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();

            // We don't want the default handler which prints errors to stderr.
            builder.setErrorHandler(new ErrorHandler() {
                @Override
                public void warning(SAXParseException e) throws SAXException {
                // pass
                }
                @Override
                public void fatalError(SAXParseException e) throws SAXException {
                    throw e;
                }
                @Override
                public void error(SAXParseException e) throws SAXException {
                    throw e;
                }
            });

            doc = builder.parse(xml);

            // Prepare a new document using a namespace aware builder
            factory.setNamespaceAware(true);
            builder = factory.newDocumentBuilder();

        } catch (Exception e) {
            // Failed to reset XML stream
            // Failed to get builder factor
            // Failed to create XML document builder
            // Failed to parse XML document
            // Failed to read XML document
        }

        if (doc == null) {
            return 0;
        }

        // Check the root element is an XML with at least the following properties:
        // <sdk:sdk-addons-list
        //    xmlns:sdk="http://schemas.android.com/sdk/android/addons-list/$N">
        //
        // Note that we don't have namespace support enabled, we just do it manually.

        Pattern nsPattern = Pattern.compile(SdkAddonsListConstants.NS_PATTERN);

        String prefix = null;
        for (Node child = doc.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                prefix = null;
                String name = child.getNodeName();
                int pos = name.indexOf(':');
                if (pos > 0 && pos < name.length() - 1) {
                    prefix = name.substring(0, pos);
                    name = name.substring(pos + 1);
                }
                if (SdkAddonsListConstants.NODE_SDK_ADDONS_LIST.equals(name)) {
                    NamedNodeMap attrs = child.getAttributes();
                    String xmlns = "xmlns";                                         //$NON-NLS-1$
                    if (prefix != null) {
                        xmlns += ":" + prefix;                                      //$NON-NLS-1$
                    }
                    Node attr = attrs.getNamedItem(xmlns);
                    if (attr != null) {
                        String uri = attr.getNodeValue();
                        if (uri != null) {
                            Matcher m = nsPattern.matcher(uri);
                            if (m.matches()) {
                                String version = m.group(1);
                                try {
                                    return Integer.parseInt(version);
                                } catch (NumberFormatException e) {
                                    return 0;
                                }
                            }
                        }
                    }
                }
            }
        }

        return 0;
    }

    /**
     * Validates this XML against one of the requested SDK Repository schemas.
     * If the XML was correctly validated, returns the schema that worked.
     * If it doesn't validate, returns null and stores the error in outError[0].
     * If we can't find a validator, returns null and set validatorFound[0] to false.
     */
    @VisibleForTesting(visibility=Visibility.PRIVATE)
    protected String validateXml(InputStream xml, String url, int version,
            String[] outError, Boolean[] validatorFound) {

        if (xml == null) {
            return null;
        }

        try {
            Validator validator = getValidator(version);

            if (validator == null) {
                validatorFound[0] = Boolean.FALSE;
                outError[0] = String.format(
                        "XML verification failed for %1$s.\nNo suitable XML Schema Validator could be found in your Java environment. Please consider updating your version of Java.",
                        url);
                return null;
            }

            validatorFound[0] = Boolean.TRUE;

            // Reset the stream if it supports that operation.
            xml.reset();

            // Validation throws a bunch of possible Exceptions on failure.
            validator.validate(new StreamSource(xml));
            return SdkAddonsListConstants.getSchemaUri(version);

        } catch (SAXParseException e) {
            outError[0] = String.format(
                    "XML verification failed for %1$s.\nLine %2$d:%3$d, Error: %4$s",
                    url,
                    e.getLineNumber(),
                    e.getColumnNumber(),
                    e.toString());

        } catch (Exception e) {
            outError[0] = String.format(
                    "XML verification failed for %1$s.\nError: %2$s",
                    url,
                    e.toString());
        }
        return null;
    }

    /**
     * Helper method that returns a validator for our XSD, or null if the current Java
     * implementation can't process XSD schemas.
     *
     * @param version The version of the XML Schema.
     *        See {@link SdkAddonsListConstants#getXsdStream(int)}
     */
    private Validator getValidator(int version) throws SAXException {
        InputStream xsdStream = SdkAddonsListConstants.getXsdStream(version);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        if (factory == null) {
            return null;
        }

        // This may throw a SAX Exception if the schema itself is not a valid XSD
        Schema schema = factory.newSchema(new StreamSource(xsdStream));

        Validator validator = schema == null ? null : schema.newValidator();

        return validator;
    }

    /**
     * Takes an XML document as a string as parameter and returns a DOM for it.
     *
     * On error, returns null and prints a (hopefully) useful message on the monitor.
     */
    @VisibleForTesting(visibility=Visibility.PRIVATE)
    protected Document getDocument(InputStream xml, ITaskMonitor monitor) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setIgnoringComments(true);
            factory.setNamespaceAware(true);

            DocumentBuilder builder = factory.newDocumentBuilder();
            xml.reset();
            Document doc = builder.parse(new InputSource(xml));

            return doc;
        } catch (ParserConfigurationException e) {
            monitor.logError("Failed to create XML document builder");

        } catch (SAXException e) {
            monitor.logError("Failed to parse XML document");

        } catch (IOException e) {
            monitor.logError("Failed to read XML document");
        }

        return null;
    }

    /**
     * Parse all sites defined in the Addaons list XML and returns an array of sites.
     */
    @VisibleForTesting(visibility=Visibility.PRIVATE)
    protected Site[] parseAddonsList(Document doc, String nsUri, ITaskMonitor monitor) {

        String baseUrl = System.getenv("SDK_TEST_BASE_URL");            //$NON-NLS-1$
        if (baseUrl != null) {
            if (baseUrl.length() <= 0 || !baseUrl.endsWith("/")) {      //$NON-NLS-1$
                baseUrl = null;
            }
        }

        Node root = getFirstChild(doc, nsUri, SdkAddonsListConstants.NODE_SDK_ADDONS_LIST);
        if (root != null) {
            ArrayList<Site> sites = new ArrayList<Site>();

            for (Node child = root.getFirstChild();
                 child != null;
                 child = child.getNextSibling()) {
                if (child.getNodeType() == Node.ELEMENT_NODE &&
                        nsUri.equals(child.getNamespaceURI())) {

                    String elementName = child.getLocalName();
                    SiteType type = null;

                    if (SdkAddonsListConstants.NODE_SYS_IMG_SITE.equals(elementName)) {
                        type = SiteType.SYS_IMG_SITE;

                    } else if (SdkAddonsListConstants.NODE_ADDON_SITE.equals(elementName)) {
                        type = SiteType.ADDON_SITE;
                    }

                    // Not an addon-site nor a sys-img-site, don't process this.
                    if (type == null) {
                        continue;
                    }

                    Node url = getFirstChild(child, nsUri, SdkAddonsListConstants.NODE_URL);
                    Node name = getFirstChild(child, nsUri, SdkAddonsListConstants.NODE_NAME);

                    if (name != null && url != null) {
                        String strUrl  = url.getTextContent().trim();
                        String strName = name.getTextContent().trim();

                        if (baseUrl != null &&
                                strUrl.startsWith(SdkRepoConstants.URL_GOOGLE_SDK_SITE)) {
                            strUrl = baseUrl +
                                   strUrl.substring(SdkRepoConstants.URL_GOOGLE_SDK_SITE.length());
                        }

                        if (strUrl.length() > 0 && strName.length() > 0) {
                            sites.add(new Site(strUrl, strName, type));
                        }
                    }
                }
            }

            return sites.toArray(new Site[sites.size()]);
        }

        return null;
    }

    /**
     * Returns the first child element with the given XML local name.
     * If xmlLocalName is null, returns the very first child element.
     */
    private Node getFirstChild(Node node, String nsUri, String xmlLocalName) {

        for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child.getNodeType() == Node.ELEMENT_NODE &&
                    nsUri.equals(child.getNamespaceURI())) {
                if (xmlLocalName == null || child.getLocalName().equals(xmlLocalName)) {
                    return child;
                }
            }
        }

        return null;
    }


}