1 /*
   2  * Copyright 1997-2003 Sun Microsystems, Inc.  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.  Sun designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22  * CA 95054 USA or visit www.sun.com if you need additional information or
  23  * have any questions.
  24  */
  25 
  26 package sun.net.www.protocol.http;
  27 
  28 import java.net.URL;
  29 import java.net.URI;
  30 import java.net.URISyntaxException;
  31 import java.net.PasswordAuthentication;
  32 import sun.net.www.HeaderParser;
  33 
  34 
  35 /**
  36  * BasicAuthentication: Encapsulate an http server authentication using
  37  * the "basic" scheme.
  38  *
  39  * @author Bill Foote
  40  */
  41 
  42 
  43 class BasicAuthentication extends AuthenticationInfo {
  44 
  45     private static final long serialVersionUID = 100L;
  46 
  47     /** The authentication string for this host, port, and realm.  This is
  48         a simple BASE64 encoding of "login:password".    */
  49     String auth;
  50 
  51     /**
  52      * Create a BasicAuthentication
  53      */
  54     public BasicAuthentication(boolean isProxy, String host, int port,
  55                                String realm, PasswordAuthentication pw) {
  56         super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
  57               AuthScheme.BASIC, host, port, realm);
  58         String plain = pw.getUserName() + ":";
  59         byte[] nameBytes = null;
  60         try {
  61             nameBytes = plain.getBytes("ISO-8859-1");
  62         } catch (java.io.UnsupportedEncodingException uee) {
  63             assert false;
  64         }
  65 
  66         // get password bytes
  67         char[] passwd = pw.getPassword();
  68         byte[] passwdBytes = new byte[passwd.length];
  69         for (int i=0; i<passwd.length; i++)
  70             passwdBytes[i] = (byte)passwd[i];
  71 
  72         // concatenate user name and password bytes and encode them
  73         byte[] concat = new byte[nameBytes.length + passwdBytes.length];
  74         System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
  75         System.arraycopy(passwdBytes, 0, concat, nameBytes.length,
  76                          passwdBytes.length);
  77         this.auth = "Basic " + (new sun.misc.BASE64Encoder()).encode(concat);
  78         this.pw = pw;
  79     }
  80 
  81     /**
  82      * Create a BasicAuthentication
  83      */
  84     public BasicAuthentication(boolean isProxy, String host, int port,
  85                                String realm, String auth) {
  86         super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
  87               AuthScheme.BASIC, host, port, realm);
  88         this.auth = "Basic " + auth;
  89     }
  90 
  91     /**
  92      * Create a BasicAuthentication
  93      */
  94     public BasicAuthentication(boolean isProxy, URL url, String realm,
  95                                    PasswordAuthentication pw) {
  96         super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
  97               AuthScheme.BASIC, url, realm);
  98         String plain = pw.getUserName() + ":";
  99         byte[] nameBytes = null;
 100         try {
 101             nameBytes = plain.getBytes("ISO-8859-1");
 102         } catch (java.io.UnsupportedEncodingException uee) {
 103             assert false;
 104         }
 105 
 106         // get password bytes
 107         char[] passwd = pw.getPassword();
 108         byte[] passwdBytes = new byte[passwd.length];
 109         for (int i=0; i<passwd.length; i++)
 110             passwdBytes[i] = (byte)passwd[i];
 111 
 112         // concatenate user name and password bytes and encode them
 113         byte[] concat = new byte[nameBytes.length + passwdBytes.length];
 114         System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
 115         System.arraycopy(passwdBytes, 0, concat, nameBytes.length,
 116                          passwdBytes.length);
 117         this.auth = "Basic " + (new sun.misc.BASE64Encoder()).encode(concat);
 118         this.pw = pw;
 119     }
 120 
 121     /**
 122      * Create a BasicAuthentication
 123      */
 124     public BasicAuthentication(boolean isProxy, URL url, String realm,
 125                                    String auth) {
 126         super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
 127               AuthScheme.BASIC, url, realm);
 128         this.auth = "Basic " + auth;
 129     }
 130 
 131     /**
 132      * @return true if this authentication supports preemptive authorization
 133      */
 134     @Override
 135     public boolean supportsPreemptiveAuthorization() {
 136         return true;
 137     }
 138 
 139     /**
 140      * Set header(s) on the given connection. This will only be called for
 141      * definitive (i.e. non-preemptive) authorization.
 142      * @param conn The connection to apply the header(s) to
 143      * @param p A source of header values for this connection, if needed.
 144      * @param raw The raw header values for this connection, if needed.
 145      * @return true if all goes well, false if no headers were set.
 146      */
 147     @Override
 148     public boolean setHeaders(HttpURLConnection conn, HeaderParser p, String raw) {
 149         conn.setAuthenticationProperty(getHeaderName(), getHeaderValue(null,null));
 150         return true;
 151     }
 152 
 153     /**
 154      * @return the value of the HTTP header this authentication wants set
 155      */
 156     @Override
 157     public String getHeaderValue(URL url, String method) {
 158         /* For Basic the authorization string does not depend on the request URL
 159          * or the request method
 160          */
 161         return auth;
 162     }
 163 
 164     /**
 165      * For Basic Authentication, the security parameters can never be stale.
 166      * In other words there is no possibility to reuse the credentials.
 167      * They are always either valid or invalid.
 168      */
 169     @Override
 170     public boolean isAuthorizationStale (String header) {
 171         return false;
 172     }
 173 
 174     /**
 175      * @return the common root path between npath and path.
 176      * This is used to detect when we have an authentication for two
 177      * paths and the root of th authentication space is the common root.
 178      */
 179 
 180     static String getRootPath(String npath, String opath) {
 181         int index = 0;
 182         int toindex;
 183 
 184         /* Must normalize so we don't get confused by ../ and ./ segments */
 185         try {
 186             npath = new URI (npath).normalize().getPath();
 187             opath = new URI (opath).normalize().getPath();
 188         } catch (URISyntaxException e) {
 189             /* ignore error and use the old value */
 190         }
 191 
 192         while (index < opath.length()) {
 193             toindex = opath.indexOf('/', index+1);
 194             if (toindex != -1 && opath.regionMatches(0, npath, 0, toindex+1))
 195                 index = toindex;
 196             else
 197                 return opath.substring(0, index+1);
 198         }
 199         /*should not reach here. If we do simply return npath*/
 200         return npath;
 201     }
 202 
 203 }