Skip to content
This repository has been archived by the owner on Sep 1, 2022. It is now read-only.

Commit

Permalink
Fix for Github issue #272
Browse files Browse the repository at this point in the history
The problem was that java.net.URI and java.net.URL
could not parse url strings that were based on
backslash escape rather than %xx escape.
The General Rule is this:
1. any url given to e.g. HTTPSession or HTTPMethod
   or HTTPFactory is assumed to be the url
   that is wanted on the server side.
2. #1 means that, again as a general rule, urlstrings
   given to those classes should not be %xx escaped
   unless that is what you want on the server side.
3. The key to understand is that
   a. those classes will internally %xx encode the url string they are
      given even if the url string already is %xx encoded.
   b. on the server side, the %xx encoding will be performed
      on the incoming url string. This means that the %xx encoded
      string you originally sent is the one given to the servlet.
Bottom line: do not do %xx encoding yourself unless your server side
code is expected to see a %xx encoded url.

Anyway, the fix is to create a procedure -- HTTPUtil.parseToURI() --
that can properly create a java.net.URI object from a backslash
escaped url string. Any time you need to create a URI object,
you should do so using that procedure.
  • Loading branch information
DennisHeimbigner committed Nov 5, 2015
1 parent e97632c commit 2d2b597
Show file tree
Hide file tree
Showing 10 changed files with 299 additions and 53 deletions.
14 changes: 8 additions & 6 deletions cdm-test/src/test/java/ucar/nc2/util/net/TestFormBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,10 @@ public class TestFormBuilder extends UnitTestCommon

static final boolean DEBUG = false;

static final int ECHOPORT = 4444;
static final String ECHOURL = "http://localhost:" + ECHOPORT;
static final int SIMPLEECHOPORT = 4444;
static final int MULTIECHOPORT = 4445;
static final String SIMPLEECHOURL = "http://localhost:" + SIMPLEECHOPORT;
static final String MULTIECHOURL = "http://localhost:" + MULTIECHOPORT;

// Field values to use
static final String DESCRIPTIONENTRY = "TestFormBuilder";
Expand Down Expand Up @@ -116,8 +118,8 @@ public TestFormBuilder()
HttpEntity content = builder.build();
String body = null;
try (
EchoService echo = new EchoService(ECHOPORT).startecho();
HTTPMethod postMethod = HTTPFactory.Post(ECHOURL)
EchoService echo = new EchoService(SIMPLEECHOPORT).startecho();
HTTPMethod postMethod = HTTPFactory.Post(SIMPLEECHOURL)
) {
postMethod.setRequestContent(content);
postMethod.execute();
Expand Down Expand Up @@ -158,8 +160,8 @@ public TestFormBuilder()
HttpEntity content = builder.build();
String body = null;
try (
EchoService echo = new EchoService(ECHOPORT).startecho();
HTTPMethod postMethod = HTTPFactory.Post(ECHOURL)
EchoService echo = new EchoService(MULTIECHOPORT).startecho();
HTTPMethod postMethod = HTTPFactory.Post(MULTIECHOURL)
) {
postMethod.setRequestContent(content);
postMethod.execute();
Expand Down
209 changes: 209 additions & 0 deletions cdm-test/src/test/java/ucar/nc2/util/net/TestURIParse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/*
* Copyright (c) 1998 - 2012. University Corporation for Atmospheric Research/Unidata
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
*
* Access and use of this software shall impose the following obligations
* and understandings on the user. The user is granted the right, without
* any fee or cost, to use, copy, modify, alter, enhance and distribute
* this software, and any derivative works thereof, and its supporting
* documentation for any purpose whatsoever, provided that this entire
* notice appears in all copies of the software, derivative works and
* supporting documentation. Further, UCAR requests that the user credit
* UCAR/Unidata in any publications that result from the use of this
* software or in any product that includes this software. The names UCAR
* and/or Unidata, however, may not be used in any advertising or publicity
* to endorse or promote any products or commercial entity unless specific
* written permission is obtained from UCAR/Unidata. The user also
* understands that UCAR/Unidata is not obligated to provide the user with
* any support, consulting, training or assistance of any kind with regard
* to the use, operation and performance of this software nor to provide
* the user with any updates, revisions, new versions or "bug fixes."
*
* THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
*/

package ucar.nc2.util.net;

import org.junit.Assert;
import org.junit.Test;
import ucar.httpservices.HTTPFactory;
import ucar.httpservices.HTTPMethod;
import ucar.httpservices.HTTPUtil;
import ucar.nc2.util.UnitTestCommon;

import java.net.URI;
import java.net.URISyntaxException;

/**
* Test HTTPUtil.parseToURI on a variety of input cases.
*/

public class TestURIParse extends UnitTestCommon
{
static public boolean DEBUG = false;
static public boolean DOCARON = false;

static final String CARON = "http://localhost:8081/thredds/cdmremote/scanCdmUnitTests/formats/hdf5/grid_1_3d_xyz_aug.h5?req=data&var=HDFEOS_INFORMATION/StructMetadata\\.0";

static final String[] filetests = {};

static final String[] httptests = {
"http://ucar.edu:8081/dts/test\\/fake\\.01",
CARON,
};

//////////////////////////////////////////////////

// Define the test sets

int passcount = 0;
int xfailcount = 0;
int failcount = 0;
boolean verbose = true;
boolean pass = false;

String datadir = null;
String threddsroot = null;

public TestURIParse()
{
setTitle("HTTPUtil.parseToURI tests");
}

@Test
public void
testParse() throws Exception
{
pass = true;
for(int i = 0; i < httptests.length; i++) {
boolean passthis = true;
URI uri = null;
try {
uri = HTTPUtil.parseToURI(httptests[i]);
} catch (URISyntaxException use) {
System.err.println("Parse error: " + use.getMessage());
if(DEBUG) use.printStackTrace(System.err);
uri = null;
passthis = false;
}
String raw = dumpraw(uri);
if(DEBUG) System.err.printf("raw= |%s|%n", raw);
System.err.printf("Test A: "
+ "input :: actual%n"
+ "\t |%s|%n"
+ "\t:: |%s|%n",
httptests[i],dump(uri));
if(!httptests[i].equals(dump(uri))) {
passthis = false;
}
// Second test is for idempotence of %xx form.
try {
uri = HTTPUtil.parseToURI(raw);
} catch (URISyntaxException use) {
System.err.println("Parse error: " + use.getMessage());
if(DEBUG) use.printStackTrace(System.err);
uri = null;
passthis = false;
}
System.err.printf("Test B: "
+ "input :: actual%n"
+ "\t |%s|%n"
+ "\t:: |%s|%n",
raw,dumpraw(uri));
if(!raw.equals(dumpraw(uri))) {
passthis = false;
}
System.err.println(passthis ? "Pass" : "Fail");
if(!passthis) pass = false;
}
Assert.assertTrue("TestMisc.testURX", pass);
}

// Temporary to test Caron's case specifically
@Test
public void
testCaron()
{
if(!DOCARON) return;
try {
try (HTTPMethod m = HTTPFactory.Get(CARON)) {
int code = m.execute();
Assert.assertTrue("Unexpected return code: " + code, code == 200);
}
} catch (Exception use) {
use.printStackTrace();
Assert.assertTrue("URISyntaxException", false);
}
}


static protected boolean
uriCompare(URI uri1, URI uri2)
{
boolean ok = true;
ok = ok && uriPartCompare(uri1.getScheme(), uri2.getScheme());
ok = ok && uriPartCompare(uri1.getHost(), uri2.getHost());
ok = ok && (uri1.getPort() == uri2.getPort());
ok = ok && uriPartCompare(uri1.getPath(), uri2.getPath());
ok = ok && uriPartCompare(uri1.getQuery(), uri2.getQuery());
ok = ok && uriPartCompare(uri1.getFragment(), uri2.getFragment());
return ok;
}

static protected boolean
uriCompareRaw(URI uri1, URI uri2)
{
boolean ok = true;
ok = ok && uriPartCompare(uri1.getScheme(), uri2.getScheme());
ok = ok && uriPartCompare(uri1.getHost(), uri2.getHost());
ok = ok && (uri1.getPort() == uri2.getPort());
ok = ok && uriPartCompare(uri1.getRawPath(), uri2.getRawPath());
ok = ok && uriPartCompare(uri1.getRawQuery(), uri2.getRawQuery());
ok = ok && uriPartCompare(uri1.getRawFragment(), uri2.getRawFragment());
return ok;
}

static protected boolean
uriPartCompare(String s1, String s2)
{
if(s1 == s2) return true;
if(s1 == null || s2 == null) return false;
return (s1.equals(s2));
}

static protected String
dump(URI uri)
{
StringBuilder buf = new StringBuilder();
buf.append(uri.getScheme()).append("://");
buf.append(uri.getHost());
if(uri.getPort() >= 0) buf.append(':').append(uri.getPort());
if(uri.getPath() != null) buf.append(uri.getPath());
if(uri.getQuery() != null) buf.append('?').append(uri.getQuery());
if(uri.getFragment() != null) buf.append('#').append(uri.getFragment());
return buf.toString();
}

static protected String
dumpraw(URI uri)
{
StringBuilder buf = new StringBuilder();
buf.append(uri.getScheme()).append("://");
buf.append(uri.getHost());
if(uri.getPort() >= 0) buf.append(':').append(uri.getPort());
if(uri.getRawPath() != null) buf.append(uri.getRawPath());
if(uri.getRawQuery() != null) buf.append('?').append(uri.getRawQuery());
if(uri.getRawFragment() != null) buf.append('#').append(uri.getRawFragment());
return buf.toString();
}


}
7 changes: 4 additions & 3 deletions dap4/d4shared/src/main/java/dap4/dap4shared/HttpDSP.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.apache.http.HttpStatus;
import ucar.httpservices.HTTPFactory;
import ucar.httpservices.HTTPMethod;
import ucar.httpservices.HTTPUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
Expand Down Expand Up @@ -175,11 +176,11 @@ public String getPath()
callServer(String methodurl)
throws DapException
{
URL url;
URI uri;

try {
url = new URL(methodurl);
} catch (MalformedURLException mue) {
uri = HTTPUtil.parseToURI(methodurl);
} catch (URISyntaxException mue) {
throw new DapException("Malformed url: " + methodurl);
}

Expand Down
3 changes: 2 additions & 1 deletion dap4/d4shared/src/main/java/dap4/dap4shared/XURI.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import dap4.core.util.DapUtil;
import dap4.core.util.Escape;
import org.apache.http.NameValuePair;
import ucar.httpservices.HTTPUtil;

import java.net.*;
import java.nio.charset.Charset;
Expand Down Expand Up @@ -112,7 +113,7 @@ public XURI(String path)
// Note that if the path has a drive letter, this parse
// will treat it as the host; fix below
try {
this.url = new URI(this.trueurl);
this.url = HTTPUtil.parseToURI(this.trueurl);
} catch (URISyntaxException mue) {
throw new URISyntaxException(this.trueurl, mue.getMessage());
}
Expand Down
9 changes: 6 additions & 3 deletions dap4/d4tests/src/test/java/dap4/test/DapTestCommon.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.EnumSet;
Expand All @@ -32,6 +34,7 @@
import thredds.server.dap4.Dap4Controller;
import ucar.httpservices.HTTPFactory;
import ucar.httpservices.HTTPMethod;
import ucar.httpservices.HTTPUtil;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.unidata.test.util.TestDir;

Expand Down Expand Up @@ -106,12 +109,12 @@ public Mocker(String servletname, String url, DapTestCommon parent)
* Instead, it requires the user to so do.
*/
protected void setup()
throws MalformedURLException
throws URISyntaxException
{
this.req.setCharacterEncoding("UTF-8");
this.req.setServletPath("/" + this.servletname);
URL url = new URL(this.url);
this.req.setProtocol(url.getProtocol());
URI url = HTTPUtil.parseToURI(this.url);
this.req.setProtocol(url.getScheme());
this.req.setQueryString(url.getQuery());
this.req.setServerName(url.getHost());
this.req.setServerPort(url.getPort());
Expand Down
8 changes: 4 additions & 4 deletions httpservices/src/main/java/ucar/httpservices/Escape.java
Original file line number Diff line number Diff line change
Expand Up @@ -213,15 +213,15 @@ public static String escapeURL(String surl)
query = m.group(4);
fragment = m.group(5);
} else {// faster, but may not work quite right
URL u = null;
try {u = new URL(surl);} catch (MalformedURLException e) {
URI u = null;
try {u = HTTPUtil.parseToURI(surl);} catch (URISyntaxException e) {
return null;
}
protocol = u.getProtocol();
protocol = u.getScheme();
authority = u.getAuthority();
path = u.getPath();
query = u.getQuery();
fragment = u.getRef();
fragment = u.getFragment();
}
// Reassemble
StringBuilder url = new StringBuilder();
Expand Down
17 changes: 9 additions & 8 deletions httpservices/src/main/java/ucar/httpservices/HTTPAuthUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,16 +69,17 @@ abstract public class HTTPAuthUtil
//////////////////////////////////////////////////
// URL Decomposition

/*
static URI decompose(String suri)
throws HTTPException
{
try {
URI uri = new URI(suri);
URI uri = HTTPUtil.parseToURI(suri);
return uri;
} catch (URISyntaxException use) {
throw new HTTPException("HTTPAuthUtil: illegal url: " + suri);
}
}
} */

/**
* Create an AuthScope from a URL; pull out any principal
Expand All @@ -95,15 +96,15 @@ static URI decompose(String suri)
if(surl == null)
throw new HTTPException("Null argument");
try {
URI uri = HTTPAuthUtil.decompose(surl);
URI uri = HTTPUtil.parseToURI(surl);
AuthScope scope = new AuthScope(uri.getHost(),
uri.getPort(),
HTTPAuthUtil.makerealm(uri.toURL()),
authscheme);
return scope;
} catch (IllegalArgumentException e) {
return null;
} catch (MalformedURLException mue) {
} catch (URISyntaxException | MalformedURLException mue) {
throw new HTTPException(mue);
}
}
Expand All @@ -115,8 +116,8 @@ static URI decompose(String suri)
return urlToScope(surl, ANY_SCHEME);
}

static public URL
scopeToURL(AuthScope scope)
static public URI
scopeToURI(AuthScope scope)
throws HTTPException
{
try {
Expand All @@ -127,9 +128,9 @@ else if(scheme.equals(HTTPAuthSchemes.SSL))
scheme = "https";
else
scheme = "http";
URL url = new URL(scheme, scope.getHost(), scope.getPort(), "");
URI url = new URI(scheme, null, scope.getHost(), scope.getPort(), "",null,null);
return url;
} catch (MalformedURLException mue) {
} catch (URISyntaxException mue) {
throw new HTTPException(mue);
}
}
Expand Down
Loading

0 comments on commit 2d2b597

Please sign in to comment.