1/*
2 * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package sun.net.www.protocol.http;
27
28import java.net.URL;
29import java.net.URI;
30import java.net.URISyntaxException;
31import java.net.PasswordAuthentication;
32import java.io.IOException;
33import java.io.OutputStream;
34import java.util.Base64;
35import java.util.Objects;
36import sun.net.www.HeaderParser;
37
38/**
39 * BasicAuthentication: Encapsulate an http server authentication using
40 * the "basic" scheme.
41 *
42 * @author Bill Foote
43 */
44
45
46class BasicAuthentication extends AuthenticationInfo {
47
48    private static final long serialVersionUID = 100L;
49
50    /** The authentication string for this host, port, and realm.  This is
51        a simple BASE64 encoding of "login:password".    */
52    String auth;
53
54    /**
55     * Create a BasicAuthentication
56     */
57    public BasicAuthentication(boolean isProxy, String host, int port,
58                               String realm, PasswordAuthentication pw,
59                               String authenticatorKey) {
60        super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
61              AuthScheme.BASIC, host, port, realm,
62              Objects.requireNonNull(authenticatorKey));
63        String plain = pw.getUserName() + ":";
64        byte[] nameBytes = null;
65        try {
66            nameBytes = plain.getBytes("ISO-8859-1");
67        } catch (java.io.UnsupportedEncodingException uee) {
68            assert false;
69        }
70
71        // get password bytes
72        char[] passwd = pw.getPassword();
73        byte[] passwdBytes = new byte[passwd.length];
74        for (int i=0; i<passwd.length; i++)
75            passwdBytes[i] = (byte)passwd[i];
76
77        // concatenate user name and password bytes and encode them
78        byte[] concat = new byte[nameBytes.length + passwdBytes.length];
79        System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
80        System.arraycopy(passwdBytes, 0, concat, nameBytes.length,
81                         passwdBytes.length);
82        this.auth = "Basic " + Base64.getEncoder().encodeToString(concat);
83        this.pw = pw;
84    }
85
86    /**
87     * Create a BasicAuthentication
88     */
89    public BasicAuthentication(boolean isProxy, String host, int port,
90                               String realm, String auth,
91                               String authenticatorKey) {
92        super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
93              AuthScheme.BASIC, host, port, realm,
94              Objects.requireNonNull(authenticatorKey));
95        this.auth = "Basic " + auth;
96    }
97
98    /**
99     * Create a BasicAuthentication
100     */
101    public BasicAuthentication(boolean isProxy, URL url, String realm,
102                               PasswordAuthentication pw,
103                               String authenticatorKey) {
104        super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
105              AuthScheme.BASIC, url, realm,
106              Objects.requireNonNull(authenticatorKey));
107        String plain = pw.getUserName() + ":";
108        byte[] nameBytes = null;
109        try {
110            nameBytes = plain.getBytes("ISO-8859-1");
111        } catch (java.io.UnsupportedEncodingException uee) {
112            assert false;
113        }
114
115        // get password bytes
116        char[] passwd = pw.getPassword();
117        byte[] passwdBytes = new byte[passwd.length];
118        for (int i=0; i<passwd.length; i++)
119            passwdBytes[i] = (byte)passwd[i];
120
121        // concatenate user name and password bytes and encode them
122        byte[] concat = new byte[nameBytes.length + passwdBytes.length];
123        System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
124        System.arraycopy(passwdBytes, 0, concat, nameBytes.length,
125                         passwdBytes.length);
126        this.auth = "Basic " + Base64.getEncoder().encodeToString(concat);
127        this.pw = pw;
128    }
129
130    /**
131     * Create a BasicAuthentication
132     */
133    public BasicAuthentication(boolean isProxy, URL url, String realm,
134                               String auth, String authenticatorKey) {
135        super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
136              AuthScheme.BASIC, url, realm,
137              Objects.requireNonNull(authenticatorKey));
138        this.auth = "Basic " + auth;
139    }
140
141    /**
142     * @return true if this authentication supports preemptive authorization
143     */
144    @Override
145    public boolean supportsPreemptiveAuthorization() {
146        return true;
147    }
148
149    /**
150     * Set header(s) on the given connection. This will only be called for
151     * definitive (i.e. non-preemptive) authorization.
152     * @param conn The connection to apply the header(s) to
153     * @param p A source of header values for this connection, if needed.
154     * @param raw The raw header values for this connection, if needed.
155     * @return true if all goes well, false if no headers were set.
156     */
157    @Override
158    public boolean setHeaders(HttpURLConnection conn, HeaderParser p, String raw) {
159        conn.setAuthenticationProperty(getHeaderName(), getHeaderValue(null,null));
160        return true;
161    }
162
163    /**
164     * @return the value of the HTTP header this authentication wants set
165     */
166    @Override
167    public String getHeaderValue(URL url, String method) {
168        /* For Basic the authorization string does not depend on the request URL
169         * or the request method
170         */
171        return auth;
172    }
173
174    /**
175     * For Basic Authentication, the security parameters can never be stale.
176     * In other words there is no possibility to reuse the credentials.
177     * They are always either valid or invalid.
178     */
179    @Override
180    public boolean isAuthorizationStale (String header) {
181        return false;
182    }
183
184    /**
185     * @return the common root path between npath and path.
186     * This is used to detect when we have an authentication for two
187     * paths and the root of th authentication space is the common root.
188     */
189
190    static String getRootPath(String npath, String opath) {
191        int index = 0;
192        int toindex;
193
194        /* Must normalize so we don't get confused by ../ and ./ segments */
195        try {
196            npath = new URI (npath).normalize().getPath();
197            opath = new URI (opath).normalize().getPath();
198        } catch (URISyntaxException e) {
199            /* ignore error and use the old value */
200        }
201
202        while (index < opath.length()) {
203            toindex = opath.indexOf('/', index+1);
204            if (toindex != -1 && opath.regionMatches(0, npath, 0, toindex+1))
205                index = toindex;
206            else
207                return opath.substring(0, index+1);
208        }
209        /*should not reach here. If we do simply return npath*/
210        return npath;
211    }
212}
213