pax_global_header00006660000000000000000000000064124111605720014511gustar00rootroot0000000000000052 comment=e4fc74e6012f74aa31ac87c1a798f8858bba8498 JGlobus-JGlobus-Release-2.1.0/000077500000000000000000000000001241116057200157775ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/.gitignore000066400000000000000000000002241241116057200177650ustar00rootroot00000000000000target test-output *.iml *.rej *.diff *.orig .idea .project .classpath .settings .idea~ .project~ .classpath~ .settings~ .gitignore~ *.java~ *.xml~ JGlobus-JGlobus-Release-2.1.0/LICENSE000066400000000000000000000261371241116057200170150ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. JGlobus-JGlobus-Release-2.1.0/README.textile000066400000000000000000000045721241116057200203440ustar00rootroot00000000000000 *********** * JGlobus * *********** https://github.com/jglobus/JGlobus/ The JGlobus project aims to provide the base portions of the Globus ecosystem for the Java language. The notable JARs part of the JGlobus project include: - jsse / ssl-proxies: A GSI-enabled Java trustmanager. - GSS: A secure sockets layer based on GSI from Globus. - MyProxy: Support for the MyProxy server. - GridFTP: Client-side GridFTP support. - ssl-proxies-tomcat: Utility functions for integrating the GSI-enabled trustmanager into a Tomcat container. - axis: Axis 1.4 support for the GSI-enabled trustmanager. ***************** * Release Notes * ***************** JGlobus 2.0.5 Release Notes - This is the first release from github and distributed through Maven central, as opposed to globus.org - This release addresses compatibility and performance issues with the IGTF CA bundle. - Several forward-ports of bugs reported by dCache.org. In particular, a larger set of RDN are supported. - CRLs are properly cached and reloaded, essential for running JGlobus as a trustmanager of a Java container. jGlobus 2.0.4 Core Release Notes - This release addresses internal security vulnerabilities that were identified in internal reviews in collaboration with the MyProxy team at NCSA. - GSS Tomcat support was moved into its own Maven project. jGlobus 2.0.3 Core Release Notes - caGrid changes introduced in 2.0.2 were backed-out due to incompabilities discovered between those changes and the changes GSSContextImpl. jGlobus 2.0.2 Core Release Notes - Password fix to GSSContextImpl.java and additional contributions from caGrid. jGlobus 2.0.1 Core Release Notes - jGlobus 2.0.1 Core (download) is a bug-fix release that addresses an issue with signature verification. - This issue was discovered and addresses by Jonathan Siwek at NCSA. Details of this fix can be found at https://github.com/jglobus/JGlobus/pull/10. jGlobus 2.0.0 All Release Notes - jGlobus 2.0.0 (download) replaces the use of pureTLS, as was used in jGlobus 1.x, with JSSE. While this resulted in minor changes to the GSI API, the GRAM and GridFTP packages remain unchanged from jGlobus 1.X. - A secondary goal was to drop or deprecated packages that are not strictly related to the use of Globus Toolkit. This includes, for example, the removal of the MDS package, as MDS is no longer supported in Globus Toolkit 5.X. - jGlobus now requires Java 1.5 or higher. JGlobus-JGlobus-Release-2.1.0/axis/000077500000000000000000000000001241116057200167435ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/pom.xml000066400000000000000000000025601241116057200202630ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 axisg Apache AXIS support for JGlobus axis axis axis axis-jaxrpc ${project.groupId} gss ${project.version} commons-httpclient commons-httpclient javax.servlet servlet-api junit junit test JGlobus-JGlobus-Release-2.1.0/axis/src/000077500000000000000000000000001241116057200175325ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/000077500000000000000000000000001241116057200204565ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/000077500000000000000000000000001241116057200213775ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/000077500000000000000000000000001241116057200221665ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/000077500000000000000000000000001241116057200234615ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/000077500000000000000000000000001241116057200244255ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/example/000077500000000000000000000000001241116057200260605ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/example/Client.java000066400000000000000000000064561241116057200301540ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.example; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; import org.apache.axis.configuration.SimpleProvider; import org.apache.axis.utils.Options; import org.apache.axis.SimpleTargetedChain; import org.apache.axis.transport.http.HTTPSender; import org.globus.axis.transport.HTTPSSender; import org.globus.axis.transport.GSIHTTPSender; import org.globus.axis.gsi.GSIConstants; import org.globus.axis.util.Util; import org.globus.gsi.gssapi.auth.SelfAuthorization; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.rpc.ParameterMode; public class Client { public static void main(String [] args) { Util.registerTransport(); try { Options options = new Options(args); String endpointURL = options.getURL(); String textToSend; args = options.getRemainingArgs(); if ((args == null) || (args.length < 1)) { textToSend = ""; } else { textToSend = args[0]; } // these transport handlers would normally // be configured in client-config.wsdd file SimpleProvider provider = new SimpleProvider(); SimpleTargetedChain c = null; c = new SimpleTargetedChain(new GSIHTTPSender()); provider.deployTransport("httpg", c); c = new SimpleTargetedChain(new HTTPSSender()); provider.deployTransport("https", c); c = new SimpleTargetedChain(new HTTPSender()); provider.deployTransport("http", c); // only necessary becuase of Options.getURL() // re-initializes Call settings Util.reregisterTransport(); Service service = new Service(provider); Call call = (Call) service.createCall(); // set globus credentials /* call.setProperty(GSIConstants.GSI_CREDENTIALS, cred); */ // sets authorization type call.setProperty(GSIConstants.GSI_AUTHORIZATION, SelfAuthorization.getInstance()); // sets gsi mode call.setProperty(GSIConstants.GSI_MODE, GSIConstants.GSI_MODE_LIMITED_DELEG); call.setTargetEndpointAddress( new URL(endpointURL) ); call.setOperationName(new QName("MyService", "serviceMethod")); call.addParameter( "arg1", XMLType.XSD_STRING, ParameterMode.IN); call.setReturnType( XMLType.XSD_STRING ); String ret = (String) call.invoke( new Object[] { textToSend } ); System.out.println("Service response : " + ret); } catch (Exception e) { e.printStackTrace(); } } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/example/MyService.jws000066400000000000000000000044761241116057200305260ustar00rootroot00000000000000/* This file is licensed under the terms of the Globus Toolkit Public License, found at http://www.globus.org/toolkit/download/license.html. */ import javax.servlet.http.HttpServletRequest; import org.apache.axis.MessageContext; import org.apache.axis.transport.http.HTTPConstants; import org.globus.axis.util.Util; import org.globus.axis.gsi.GSIConstants; import org.globus.axis.handler.CredentialHandler; import org.ietf.jgss.GSSCredential; public class MyService { public String serviceMethod(String arg) { MessageContext ctx = MessageContext.getCurrentContext(); setUpEnv(ctx); GSSCredential cred = (GSSCredential)ctx.getProperty(GSIConstants.GSI_CREDENTIALS); System.out.println("MyService called with arg : " + arg); System.out.println("Delegated credentials : " + cred); StringBuffer buf = new StringBuffer(); buf.append("User '").append(ctx.getProperty(GSIConstants.GSI_USER_DN)); buf.append("' authorized locally as '"); buf.append(ctx.getProperty(GSIConstants.GSI_AUTH_USERNAME)); buf.append("' sent the following message: "); buf.append(arg); return buf.toString(); } /** * This is just for testing purposes. These properties are set automatically * if CredentialHandler is deployed in server-config.wsdd file. */ private void setUpEnv(MessageContext msgContext) { Object tmp = msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); if ((tmp == null) || !(tmp instanceof HttpServletRequest)) { return; } HttpServletRequest req = (HttpServletRequest)tmp; // if httpg is access protocol in servlet engine, axis // will not set the TRANS_URL property correctly. // this is a workaround for that problem String url = req.getRequestURL().toString(); tmp = msgContext.getProperty(MessageContext.TRANS_URL); if (tmp == null && url != null) { msgContext.setProperty(MessageContext.TRANS_URL, url); } tmp = req.getAttribute(GSIConstants.GSI_CREDENTIALS); if (tmp != null) { msgContext.setProperty(GSIConstants.GSI_CREDENTIALS, tmp); } tmp = req.getAttribute(GSIConstants.GSI_AUTH_USERNAME); if (tmp != null) { msgContext.setProperty(GSIConstants.GSI_AUTH_USERNAME, tmp); } tmp = req.getAttribute(GSIConstants.GSI_USER_DN); if (tmp != null) { msgContext.setProperty(GSIConstants.GSI_USER_DN, tmp); } } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/example/README.txt000066400000000000000000000022551241116057200275620ustar00rootroot00000000000000I. Configure HTTPG Connector as described in TOMCAT_INSTALL.TXT II. Deploy Axis on Tomcat Please look at the Axis Installation Guide for details. For normal use please install the CredentialHandler as described below. For testing purposes of the MyService example this step is not necessary. Modify the server-config.wsdd and add CredentialHandler handler to the section of the block, e.g.: ... ... III. Deploy MyService to Axis Copy MyService.jws file to Tomcat's webapps/axis/ directory. IV. Connect to MyService To run the client (assuming MyService is deployed on Tomcat server) type: java org.globus.axis.example.Client -l httpg://127.0.0.1:8443/axis/MyService.jws "hello" Note: you must specify the 'httpg' as the url protocol. Add all jar files inside lib/ and build/ to the classpath. Also include all jar files in Axis lib/ directory and xerces.jar (xerces.jar can be found in Tomcat's common/lib directory. JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/gsi/000077500000000000000000000000001241116057200252075ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/gsi/GSIConstants.java000066400000000000000000000030701241116057200303710ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.gsi; public interface GSIConstants extends org.globus.gsi.GSIConstants { public static final String GSI_CREDENTIALS = "org.globus.gsi.credentials", GSI_AUTHORIZATION = "org.globus.gsi.authorization", GSI_MODE = "org.globus.gsi.mode", GSI_AUTH_USERNAME = "org.globus.gsi.authorized.user.name", GSI_USER_DN = "org.globus.gsi.authorized.user.dn", GSI_ANONYMOUS = "org.globus.gsi.anonymous", GSI_CONTEXT = "org.globus.gsi.context"; /* this is just a hack for now * something more type safe will be * much better */ public static final String /* behaves just like a regular ssl socket */ GSI_MODE_SSL = "ssl", /* send no delegation character */ GSI_MODE_NO_DELEG = "gsi", /* performs full delegation */ GSI_MODE_FULL_DELEG = "gsifull", /* performs limited delegation - default */ GSI_MODE_LIMITED_DELEG = "gsilimited"; } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/handler/000077500000000000000000000000001241116057200260425ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/handler/CredentialHandler.java000066400000000000000000000103461241116057200322610ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.handler; import javax.servlet.http.HttpServletRequest; import javax.security.auth.Subject; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.transport.http.HTTPConstants; import org.globus.axis.gsi.GSIConstants; import org.globus.gsi.gssapi.jaas.GlobusPrincipal; import org.globus.gsi.gssapi.jaas.UserNamePrincipal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSException; /** * Axis server-side request handler. To be used only in when deployed in * Tomcat. */ public class CredentialHandler extends BasicHandler { private static Log log = LogFactory.getLog(CredentialHandler.class.getName()); // must match the PEER_SUBJECT in security code private static final String CALLER_SUBJECT = "callerSubject"; public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: invoke"); Object tmp = msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); if ((tmp == null) || !(tmp instanceof HttpServletRequest)) { return; } HttpServletRequest req = (HttpServletRequest)tmp; // if httpg is access protocol in servlet engine, axis // will not set the TRANS_URL property correctly. // this is a workaround for that problem String url = req.getRequestURL().toString(); tmp = msgContext.getProperty(MessageContext.TRANS_URL); if (tmp == null && url != null) { msgContext.setProperty(MessageContext.TRANS_URL, url); } Subject subject = getSubject(msgContext); // USER_DN is set by both HTTPS/HTTPG valves tmp = req.getAttribute(GSIConstants.GSI_USER_DN); if (tmp != null) { msgContext.setProperty(GSIConstants.GSI_USER_DN, tmp); subject.getPrincipals().add(new GlobusPrincipal((String)tmp)); } // GSI_CONTEXT is set by HTTPS valve only tmp = req.getAttribute(GSIConstants.GSI_CONTEXT); if (tmp != null) { msgContext.setProperty(GSIConstants.GSI_CONTEXT, tmp); GSSContext ctx = (GSSContext)tmp; try { if (ctx.getDelegCred() != null) { subject.getPrivateCredentials().add(ctx.getDelegCred()); } } catch (GSSException e) { log.warn("Unable to obtain delegated credentials", e); } } // GSI_CREDENTIALS is set only by HTTPG valve tmp = req.getAttribute(GSIConstants.GSI_CREDENTIALS); if (tmp != null) { log.debug("Delegation performed. Setting credentials property."); msgContext.setProperty(GSIConstants.GSI_CREDENTIALS, tmp); subject.getPrivateCredentials().add(tmp); } else { log.debug("Delegation not performed. Not setting credentials property."); } // GSI_AUTH_USERNAM is set only by HTTPG Valve tmp = req.getAttribute(GSIConstants.GSI_AUTH_USERNAME); if (tmp != null) { msgContext.setProperty(GSIConstants.GSI_AUTH_USERNAME, tmp); subject.getPrincipals().add(new UserNamePrincipal((String)tmp)); } log.debug("Exit: invoke"); } protected Subject getSubject(MessageContext msgCtx) { Subject subject = (Subject)msgCtx.getProperty(CALLER_SUBJECT); if (subject == null) { subject = new Subject(); msgCtx.setProperty(CALLER_SUBJECT, subject); } return subject; } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/000077500000000000000000000000001241116057200264615ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/GSIHTTPSender.java000066400000000000000000000131371241116057200316140ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.transport; import java.io.IOException; import org.apache.axis.MessageContext; import org.apache.axis.components.net.BooleanHolder; import org.apache.axis.transport.http.SocketHolder; import org.apache.axis.transport.http.HTTPSender; import org.gridforum.jgss.ExtendedGSSContext; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; import org.globus.axis.util.Util; import org.globus.gsi.GSIConstants; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.GSSAuthorization; import org.globus.gsi.gssapi.auth.HostAuthorization; /** * This is meant to be used on a SOAP Client to call a SOAP server. *
This code is based on Axis HTTPSender.java code. */ public class GSIHTTPSender extends HTTPSender { protected void getSocket(SocketHolder sockHolder, MessageContext msgContext, String protocol, String host, int port, int timeout, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception { if (!protocol.equalsIgnoreCase("httpg")) { throw new IOException("Invalid protocol"); } GSSCredential cred = null; Authorization auth = null; String mode = null; auth = (Authorization)Util.getProperty(msgContext, GSIHTTPTransport.GSI_AUTHORIZATION); mode = (String)Util.getProperty(msgContext, GSIHTTPTransport.GSI_MODE); if (auth == null) { auth = HostAuthorization.getInstance(); } if (mode == null) { mode = GSIHTTPTransport.GSI_MODE_NO_DELEG; } GSSManager manager = ExtendedGSSManager.getInstance(); ExtendedGSSContext context = null; Boolean anonymous = (Boolean) Util.getProperty( msgContext, GSIHTTPTransport.GSI_ANONYMOUS); if (anonymous != null && anonymous.equals(Boolean.TRUE)) { GSSName name = manager.createName((String)null, (Oid)null); cred = manager.createCredential( name, GSSCredential.DEFAULT_LIFETIME, (Oid)null, GSSCredential.INITIATE_ONLY); } else { cred = (GSSCredential)Util.getProperty( msgContext, GSIHTTPTransport.GSI_CREDENTIALS); } GSSName expectedName = null; if (auth instanceof GSSAuthorization) { GSSAuthorization gssAuth = (GSSAuthorization)auth; expectedName = gssAuth.getExpectedName(cred, host); } context = (ExtendedGSSContext)manager.createContext(expectedName, GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); if (mode.equalsIgnoreCase(GSIHTTPTransport.GSI_MODE_LIMITED_DELEG)) { context.requestCredDeleg(true); context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_LIMITED); } else if (mode.equalsIgnoreCase(GSIHTTPTransport.GSI_MODE_FULL_DELEG)) { context.requestCredDeleg(true); context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_FULL); } else if (mode.equalsIgnoreCase(GSIHTTPTransport.GSI_MODE_NO_DELEG)) { context.requestCredDeleg(false); } else if (mode.equalsIgnoreCase(GSIHTTPTransport.GSI_MODE_SSL)) { context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); } else { throw new Exception("Invalid GSI MODE: " + mode); } TrustedCertificates trustedCerts = (TrustedCertificates)Util.getProperty(msgContext, GSIHTTPTransport .TRUSTED_CERTIFICATES); if (trustedCerts != null) { context.setOption(GSSConstants.TRUSTED_CERTIFICATES, trustedCerts); } Boolean authzRequiredWithDelegation = (Boolean)Util.getProperty(msgContext, GSIConstants .AUTHZ_REQUIRED_WITH_DELEGATION); if (authzRequiredWithDelegation != null) { context.setOption(GSSConstants.AUTHZ_REQUIRED_WITH_DELEGATION, authzRequiredWithDelegation); } GssSocketFactory factory = GssSocketFactory.getDefault(); int lport = (port == -1) ? 8443 : port; super.getSocket(sockHolder, msgContext, "http", host, lport, timeout, otherHeaders, useFullURL); GssSocket gsiSocket = (GssSocket)factory.createSocket(sockHolder.getSocket(), host, lport, context); gsiSocket.setAuthorization(auth); sockHolder.setSocket(gsiSocket); } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/GSIHTTPTransport.java000066400000000000000000000062751241116057200323750ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.transport; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.client.Call; import org.apache.axis.client.Transport; import org.apache.axis.transport.http.HTTPConstants; import org.globus.axis.gsi.GSIConstants; /** * Extends Transport by implementing the setupMessageContext function to * set HTTP-specific message context fields and transport chains. * May not even be necessary if we arrange things differently somehow. * Can hold state relating to URL properties. *
This code is based on Axis HTTPTransport.java code. */ public class GSIHTTPTransport extends Transport implements GSIConstants { public static final String DEFAULT_TRANSPORT_NAME = "httpg"; /** * HTTP properties */ public static final String URL = MessageContext.TRANS_URL; private String cookie; private String cookie2; private String action; public GSIHTTPTransport () { transportName = DEFAULT_TRANSPORT_NAME; } /** * helper constructor */ public GSIHTTPTransport (String url, String action) { transportName = DEFAULT_TRANSPORT_NAME; this.url = url; this.action = action; } /** * Set up any transport-specific derived properties in the message context. * @param mc the context to set up * @param call the client service instance * @param engine the engine containing the registries * @throws AxisFault if service cannot be found */ public void setupMessageContextImpl(MessageContext mc, Call call, AxisEngine engine) throws AxisFault { if (action != null) { mc.setUseSOAPAction(true); mc.setSOAPActionURI(action); } // Set up any cookies we know about if (cookie != null) mc.setProperty(HTTPConstants.HEADER_COOKIE, cookie); if (cookie2 != null) mc.setProperty(HTTPConstants.HEADER_COOKIE2, cookie2); // Allow the SOAPAction to determine the service, if the service // (a) has not already been determined, and (b) if a service matching // the soap action has been deployed. if (mc.getService() == null) { mc.setTargetService( (String)mc.getSOAPActionURI() ); } } public void processReturnedMessageContext(MessageContext context) { cookie = context.getStrProp(HTTPConstants.HEADER_COOKIE); cookie2 = context.getStrProp(HTTPConstants.HEADER_COOKIE2); } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/HTTPSSender.java000066400000000000000000000040071241116057200313700ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.transport; import java.io.IOException; import org.apache.axis.MessageContext; import org.apache.axis.components.net.BooleanHolder; import org.apache.axis.transport.http.SocketHolder; import org.apache.axis.transport.http.HTTPSender; import org.globus.gsi.gssapi.net.GssSocket; /** * This is meant to be used on a SOAP Client to call a SOAP server. *
This code is based on Axis HTTPSender.java code. */ public class HTTPSSender extends HTTPSender { protected void getSocket(SocketHolder sockHolder, MessageContext msgContext, String protocol, String host, int port, int timeout, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception { if (!protocol.equalsIgnoreCase("https")) { throw new IOException("Invalid protocol"); } int lport = (port == -1) ? 8443 : port; SSLContextHelper helper = new SSLContextHelper(msgContext, host, lport); super.getSocket(sockHolder, msgContext, "http", host, lport, timeout, otherHeaders, useFullURL); GssSocket gsiSocket = helper.wrapSocket(sockHolder.getSocket()); sockHolder.setSocket(gsiSocket); } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/HTTPSTransport.java000066400000000000000000000025211241116057200321430ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.transport; /** * Extends Transport by implementing the setupMessageContext function to * set HTTP-specific message context fields and transport chains. * May not even be necessary if we arrange things differently somehow. * Can hold state relating to URL properties. *
This code is based on Axis HTTPTransport.java code. */ public class HTTPSTransport extends GSIHTTPTransport { public static final String DEFAULT_TRANSPORT_NAME = "https"; public HTTPSTransport () { transportName = DEFAULT_TRANSPORT_NAME; } /** * helper constructor */ public HTTPSTransport (String url, String action) { super(url, action); transportName = DEFAULT_TRANSPORT_NAME; } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/HTTPUtils.java000066400000000000000000000105631241116057200311310ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.transport; import java.util.Hashtable; import javax.xml.rpc.Stub; import org.apache.axis.MessageContext; import org.apache.axis.transport.http.HTTPConstants; public class HTTPUtils { public static final String DISABLE_CHUNKING = "transport.http.disableChunking"; /** * Sets connection timeout. * * @param stub The stub to set the property on * @param timeout the new timeout value in milliseconds */ public static void setTimeout(Stub stub, int timeout) { if (stub instanceof org.apache.axis.client.Stub) { ((org.apache.axis.client.Stub)stub).setTimeout(timeout); } } /** * Sets on option on the stub to close the connection * after receiving the reply (connection will not * be reused). * * @param stub The stub to set the property on * @param close If true, connection close will be requested. Otherwise * connection close will not be requested. */ public static void setCloseConnection(Stub stub, boolean close) { Hashtable headers = getRequestHeaders(stub); if (close) { headers.put(HTTPConstants.HEADER_CONNECTION, HTTPConstants.HEADER_CONNECTION_CLOSE); } else { headers.remove(HTTPConstants.HEADER_CONNECTION); } } /** * Sets on option on the stub to control what HTTP protocol * version should be used. * * @param stub The stub to set the property on * @param enable If true, HTTP 1.0 will be used. If false, HTTP 1.1 * will be used. */ public static void setHTTP10Version(Stub stub, boolean enable) { setHTTPVersion(stub, enable); } /** * Sets on option on the stub to control what HTTP protocol * version should be used. * * @param stub The stub to set the property on * @param http10 If true, HTTP 1.0 will be used. Otherwise HTTP 1.1 * will be used. */ public static void setHTTPVersion(Stub stub, boolean http10) { stub._setProperty(MessageContext.HTTP_TRANSPORT_VERSION, (http10) ? HTTPConstants.HEADER_PROTOCOL_V10 : HTTPConstants.HEADER_PROTOCOL_V11); } /** * Sets on option on the stub to use to enable or disable chunked encoding * (only if used with HTTP 1.1). * * @param stub The stub to set the property on * @param enable If true, chunked encoding will be enabled. If false, * chunked encoding will be disabled. */ public static void setChunkedEncoding(Stub stub, boolean enable) { setDisableChunking(stub, !enable); } /** * Sets on option on the stub to use to disable chunking * (only if used with HTTP 1.1). * * @param stub The stub to set the property on * @param disable If true, chunking will be disabled. Otherwise chunking * will be performed (if HTTP 1.1 will be used). */ public static void setDisableChunking(Stub stub, boolean disable) { stub._setProperty(DISABLE_CHUNKING, (disable) ? Boolean.TRUE : Boolean.FALSE); Hashtable headers = getRequestHeaders(stub); headers.put(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED, (disable) ? "false" : "true"); } private static Hashtable getRequestHeaders(Stub stub) { Hashtable headers = (Hashtable)stub._getProperty(HTTPConstants.REQUEST_HEADERS); if (headers == null) { headers = new Hashtable(); stub._setProperty(HTTPConstants.REQUEST_HEADERS, headers); } return headers; } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/SSLContextHelper.java000066400000000000000000000125331241116057200324760ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.transport; import java.net.Socket; import org.apache.axis.MessageContext; import org.gridforum.jgss.ExtendedGSSContext; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; import org.globus.axis.util.Util; import org.globus.gsi.GSIConstants; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.HostOrSelfAuthorization; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; /** * This is meant to be used on a SOAP Client to call a SOAP server. *
This code is based on Axis HTTPSender.java code. */ public class SSLContextHelper { private String host; private int port; private Authorization myAuth; private ExtendedGSSContext myContext; public SSLContextHelper(MessageContext msgContext, String host, int port) throws GSSException { Authorization auth = (Authorization)Util.getProperty(msgContext, GSIHTTPTransport.GSI_AUTHORIZATION); Boolean anonymous = (Boolean)Util.getProperty(msgContext, GSIHTTPTransport.GSI_ANONYMOUS); GSSCredential cred = (GSSCredential)Util.getProperty(msgContext, GSIHTTPTransport.GSI_CREDENTIALS); Integer protection = (Integer)Util.getProperty(msgContext, GSIConstants.GSI_TRANSPORT); TrustedCertificates trustedCerts = (TrustedCertificates)Util.getProperty(msgContext, GSIHTTPTransport .TRUSTED_CERTIFICATES); init(host, port, auth, anonymous, cred, protection, trustedCerts); } public SSLContextHelper(String host, int port, Authorization auth, Boolean anonymous, GSSCredential cred, Integer protection, TrustedCertificates trustedCerts) throws GSSException { init(host, port, auth, anonymous, cred, protection, trustedCerts); } protected void init(String host, int port, Authorization auth, Boolean anonymous, GSSCredential cred, Integer protection, TrustedCertificates trustedCerts) throws GSSException { this.host = host; this.port = port; if (auth == null) { auth = HostOrSelfAuthorization.getInstance(); } GSSManager manager = ExtendedGSSManager.getInstance(); boolean anon = false; if (anonymous != null && anonymous.equals(Boolean.TRUE)) { anon = true; } if (anon) { GSSName name = manager.createName((String)null, (Oid)null); cred = manager.createCredential( name, GSSCredential.DEFAULT_LIFETIME, (Oid)null, GSSCredential.INITIATE_ONLY); } // Expected name is null since delegation is never // done. Custom authorization is invoked after handshake is finished. ExtendedGSSContext context =(ExtendedGSSContext)manager .createContext(null, GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); if (anon) { context.requestAnonymity(true); } context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); if (GSIConstants.ENCRYPTION.equals(protection)) { context.requestConf(true); } else { context.requestConf(false); } if (trustedCerts != null) { context.setOption(GSSConstants.TRUSTED_CERTIFICATES, trustedCerts); } this.myContext = context; this.myAuth = auth; } public GssSocket wrapSocket(Socket socket) { GssSocketFactory factory = GssSocketFactory.getDefault(); GssSocket gsiSocket = (GssSocket)factory.createSocket(socket, this.host, this.port, this.myContext); gsiSocket.setAuthorization(this.myAuth); return gsiSocket; } } JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/commons/000077500000000000000000000000001241116057200301345ustar00rootroot00000000000000CommonsHttpConnectionManager.java000066400000000000000000000220461241116057200365120ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/axis/src/main/java/org/globus/axis/transport/commons/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.axis.transport.commons; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.params.HostParams; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class CommonsHttpConnectionManager implements HttpConnectionManager { private static final IdleConnectionTimeoutThread IDLE_THREAD; static { IDLE_THREAD = new IdleConnectionTimeoutThread(); IDLE_THREAD.setTimeoutInterval(1000 * 60 * 2); IDLE_THREAD.start(); } private static Log logger = LogFactory.getLog(CommonsHttpConnectionManager.class); private String [] hostConfigurationParams; private HashMap hostPoolMap; private long idleTime = 1000 * 60 * 2; private boolean staleChecking = true; private HttpConnectionManagerParams params = new HttpConnectionManagerParams(); public CommonsHttpConnectionManager(String [] hostConfigurationParams) { this.hostConfigurationParams = hostConfigurationParams; this.hostPoolMap = new HashMap(); IDLE_THREAD.addConnectionManager(this); } public void setConnectionIdleTime(long time) { this.idleTime = time; } public long getConnectionIdleTime() { return this.idleTime; } public void setStaleCheckingEnabled(boolean staleChecking) { this.staleChecking = staleChecking; } public boolean isStaleCheckingEnabled() { return this.staleChecking; } public HttpConnection getConnection(HostConfiguration hostConfiguration) { return getConnectionWithTimeout(hostConfiguration, 0); } public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) { return getConnectionWithTimeout(hostConfiguration, timeout); } public HttpConnection getConnectionWithTimeout( HostConfiguration hostConfiguration, long timeout) { ExtendedHostConfiguration extendedHostConfiguration = new ExtendedHostConfiguration(hostConfiguration, this.hostConfigurationParams); ConnectionPool pool = getConnectionPool(extendedHostConfiguration); ExtendedHttpConnection httpConnection = pool.getPooledConnection(); if (httpConnection == null) { // not in the pool - create a new connection httpConnection = getNewConnection(extendedHostConfiguration); httpConnection.setFromPool(false); } else { httpConnection.setFromPool(true); } if (this.staleChecking) { // install our retry handler hostConfiguration.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, httpConnection.getRetryHandler()); } return httpConnection; } private ExtendedHttpConnection getNewConnection( HostConfiguration hostConfiguration) { ExtendedHttpConnection httpConnection = new ExtendedHttpConnection(hostConfiguration, this.staleChecking); httpConnection.setHttpConnectionManager(this); HttpConnectionParams connectionParams = httpConnection.getParams(); connectionParams.setDefaults(this.params); if (this.hostConfigurationParams != null) { HostParams hostParams = hostConfiguration.getParams(); for (int i=0;i parent org.jglobus 2.1.0 4.0.0 container-test-utils Connector test utilities commons-io commons-io org.apache.httpcomponents httpclient ${project.groupId} jsse ${project.version} junit junit JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/000077500000000000000000000000001241116057200226635ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/main/000077500000000000000000000000001241116057200236075ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/main/java/000077500000000000000000000000001241116057200245305ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/main/java/org/000077500000000000000000000000001241116057200253175ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/main/java/org/globus/000077500000000000000000000000001241116057200266125ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/main/java/org/globus/gsi/000077500000000000000000000000001241116057200273745ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/main/java/org/globus/gsi/testutils/000077500000000000000000000000001241116057200314345ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/main/java/org/globus/gsi/testutils/container/000077500000000000000000000000001241116057200334165ustar00rootroot00000000000000ClientTest.java000066400000000000000000000105121241116057200362570ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/container-test-utils/src/main/java/org/globus/gsi/testutils/container/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.testutils.container; import java.security.Security; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.globus.gsi.jsse.SSLConfigurator; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.stores.ResourceSigningPolicyStore; import org.globus.gsi.stores.Stores; import org.junit.Test; import static org.junit.Assert.fail; import javax.net.ssl.SSLPeerUnverifiedException; public abstract class ClientTest { static{ Security.addProvider(new GlobusProvider()); } public static int getPort() { return 5082; } /** * Test client with invalid credentials. * * @throws Exception * This should happen. */ @Test public void testInvalid() throws Exception { SSLConfigurator config = getConfig("classpath:/invalidkeystore.properties"); SSLSocketFactory fac = new SSLSocketFactory(config.getSSLContext()); fac.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); DefaultHttpClient httpclient = new DefaultHttpClient(); Scheme scheme = new Scheme("https", fac, getPort()); httpclient.getConnectionManager().getSchemeRegistry().register(scheme); HttpGet httpget = new HttpGet("https://localhost/"); System.out.println("executing request" + httpget.getRequestLine()); try { httpclient.execute(httpget); fail(); } catch (SSLPeerUnverifiedException ex) { // this better happen } } // This creates the client ssl configuration. it uses the default trust // store, signing policy store // and crl store. Then it applies the users credentials. private SSLConfigurator getConfig(String credStoreLocation) throws Exception { SSLConfigurator config = new SSLConfigurator(); config.setCrlLocationPattern(null); config.setCrlStoreType(GlobusProvider.CERTSTORE_TYPE); config.setCredentialStoreLocation(credStoreLocation); config.setCredentialStorePassword("password"); config.setCredentialStoreType(GlobusProvider.KEYSTORE_TYPE); config.setTrustAnchorStoreLocation("classpath:/mytruststore.properties"); config.setTrustAnchorStorePassword("password"); config.setTrustAnchorStoreType(GlobusProvider.KEYSTORE_TYPE); ResourceSigningPolicyStore policyStore = Stores.getSigningPolicyStore("classpath:/globus_ca.signing_policy"); config.setPolicyStore(policyStore); return config; } /** * Test a client using valid credentials * * @throws Exception * if this happens, the test fails. */ @Test public void testValid() throws Exception { SSLConfigurator config = getConfig("classpath:/mykeystore.properties"); SSLSocketFactory fac = new SSLSocketFactory(config.getSSLContext()); fac.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); DefaultHttpClient httpclient = new DefaultHttpClient(); Scheme scheme = new Scheme("https", fac, getPort()); httpclient.getConnectionManager().getSchemeRegistry().register(scheme); HttpGet httpget = new HttpGet("https://localhost/"); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system stores httpclient.getConnectionManager().shutdown(); } } JGlobus-JGlobus-Release-2.1.0/gram/000077500000000000000000000000001241116057200167255ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/pom.xml000066400000000000000000000014311241116057200202410ustar00rootroot00000000000000 4.0.0 parent org.jglobus 2.1.0 gram "Grid Resource Allocation and Management(GRAM)" http://maven.apache.org ${project.groupId} gss ${project.version} junit junit test JGlobus-JGlobus-Release-2.1.0/gram/src/000077500000000000000000000000001241116057200175145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/000077500000000000000000000000001241116057200204405ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/000077500000000000000000000000001241116057200213615ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/000077500000000000000000000000001241116057200221505ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/000077500000000000000000000000001241116057200234435ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/000077500000000000000000000000001241116057200243715ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/CallbackHandler.java000066400000000000000000000126311241116057200302310ustar00rootroot00000000000000/* * $Id: CallbackHandler.java,v 1.31 2010/08/06 02:07:53 hategan Exp $ */ /* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import java.io.IOException; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Hashtable; import org.globus.net.BaseServer; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.globus.gsi.gssapi.auth.AuthorizationException; import org.globus.gram.internal.CallbackResponse; import org.globus.gram.internal.GRAMProtocol; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The Server class acts as a basic multi-threaded HTTPS * server. * * @version $Revision: 1.31 $ */ public class CallbackHandler extends BaseServer { /** Registered jobs */ private Hashtable _jobs; /** * Construct a GRAM callback handler with default user * credentials. Port will be dynamically assigned. */ public CallbackHandler() throws IOException { super(null, 0); init(); } /** * Construct a GRAM callback handler with specifed credentials * and given port. * * @param cred * credentials to use. if null default * user credentials will be used * @param port * server port to listen on. if set to 0 * the port will be dynamically assigned */ public CallbackHandler(GSSCredential cred, int port) throws IOException { super(cred, port); init(); } private void init() { _jobs = new Hashtable(); super.initialize(); setAuthorization(SelfAuthorization.getInstance()); } /** * Registers gram job to listen for status updates * @param job gram job */ public void registerJob(GramJob job) { String id = job.getIDAsString(); _jobs.put(id, job); } /** * Unregisters gram job from listening to status updates * @param job gram job */ public void unregisterJob(GramJob job) { String id = job.getIDAsString(); _jobs.remove(id); } protected GramJob getJob(String url) { return (GramJob)_jobs.get(url); } /** * Returns number of registered jobs * @return int number of jobs */ public int getRegisteredJobsSize() { return _jobs.size(); } public String getURL() { if (url == null) { StringBuffer buf = new StringBuffer(); buf.append(getProtocol()). append("://"). append(getHost()). append(":"). append(String.valueOf(getPort())). append("/"). append(String.valueOf(System.currentTimeMillis())); url = buf.toString(); } return url; } protected void handleConnection(Socket socket) { GramCallbackHandler gcb = new GramCallbackHandler(this, socket); (new Thread(gcb)).start(); } } class GramCallbackHandler implements Runnable { private static Log logger = LogFactory.getLog(GramCallbackHandler.class.getName()); private CallbackHandler handler; private Socket socket; public GramCallbackHandler(CallbackHandler handler, Socket socket) { this.handler = handler; this.socket = socket; } /** * Listen on the server socket for a client, start another thread to * keep listening on the server socket, then deal with the client. */ public void run() { BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); try { CallbackResponse hd = new CallbackResponse( socket.getInputStream() ); if (hd.protocolVersion != GRAMProtocol.GRAM_PROTOCOL_VERSION) { throw new Exception("Gram callback protocol version mismatch"); } GramJob job = handler.getJob( hd.jobManagerUrl ); if (job == null) { throw new Exception("Not registered with this handler: " + hd.jobManagerUrl); } job.setError( hd.failureCode ); // the exit code needs to be set before the // status, since setStatus triggers a listener // notification job.setExitCode ( hd.exitCode ); job.setStatus( hd.status ); if (job.getStatus() == GramJob.STATUS_DONE || job.getStatus() == GramJob.STATUS_FAILED) { handler.unregisterJob(job); } try { out.write(GRAMProtocol.OKReply()); out.flush(); } catch(IOException ignoreE) { logger.debug("Ignoring IOException"); } } catch(AuthorizationException ex) { logger.debug("Authorization failed", ex); out.write(GRAMProtocol.ErrorReply(401, "Authorization Failed")); out.flush(); } catch (Exception ex) { logger.debug("General error", ex); out.write(GRAMProtocol.ErrorReply(400, ex.getMessage())); out.flush(); } } catch (IOException e) { logger.debug("IO Error", e); } finally { try { socket.close(); } catch (IOException e) { } } } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/Gram.java000066400000000000000000000715501241116057200261320ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import java.util.Hashtable; import java.util.Enumeration; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.net.Socket; import java.net.MalformedURLException; import org.globus.util.http.HttpResponse; import org.globus.util.deactivator.Deactivator; import org.globus.util.deactivator.DeactivationHandler; import org.globus.util.GlobusURL; import org.globus.common.ResourceManagerContact; import org.globus.gram.internal.GRAMProtocol; import org.globus.gram.internal.GRAMConstants; import org.globus.gram.internal.GatekeeperReply; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.SSLUtil; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.globus.gsi.gssapi.net.impl.GSIGssOutputStream; import org.globus.gsi.gssapi.net.impl.GSIGssInputStream; import org.globus.gsi.gssapi.auth.GSSAuthorization; import org.globus.gsi.gssapi.auth.IdentityAuthorization; import org.globus.gsi.gssapi.auth.HostAuthorization; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.globus.gsi.gssapi.auth.NoAuthorization; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSContext; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This is the main class for using the Globus GRAM API * It implements all of the GRAM API functionality such as * job submission, canceling, gatekeeper pinging, and job * signaling. It also allows for callback registering and * unregistering. */ public class Gram { private static Log logger = LogFactory.getLog(Gram.class.getName()); private static Socket gatekeeperConnect(GSSCredential cred, ResourceManagerContact rmc, boolean doDel, boolean limitedDelegation) throws GSSException, GramException { GSSAuthorization auth = null; String authDN = rmc.getDN(); if (authDN != null) { auth = new IdentityAuthorization(authDN); } else { auth = HostAuthorization.getInstance(); } GSSManager manager = ExtendedGSSManager.getInstance(); try { GSSName name = auth.getExpectedName(cred, rmc.getHostName()); ExtendedGSSContext context = (ExtendedGSSContext)manager.createContext(name, GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); context.requestCredDeleg(doDel); context.setOption(GSSConstants.DELEGATION_TYPE, (limitedDelegation) ? GSIConstants.DELEGATION_TYPE_LIMITED : GSIConstants.DELEGATION_TYPE_FULL); GssSocketFactory factory = GssSocketFactory.getDefault(); GssSocket socket = (GssSocket)factory.createSocket(rmc.getHostName(), rmc.getPortNumber(), context); socket.setAuthorization(NoAuthorization.getInstance()); return socket; } catch(IOException e) { throw new GramException(GramException.ERROR_CONNECTION_FAILED, e); } } /** */ private static void checkProtocolVersion(int protocolVersion) throws GramException { if (protocolVersion != GRAMProtocol.GRAM_PROTOCOL_VERSION) { throw new GramException(GramException.VERSION_MISMATCH); } } /** * @exception GramException * @param code */ private static void checkHttpReply(int code) throws GramException { if (code == 200) { return; } else if (code == 400) { throw new GramException(GramException.PROTOCOL_FAILED); } else if (code == 403) { throw new GramException(GramException.ERROR_AUTHORIZATION); } else if (code == 404) { throw new GramException(GramException.ERROR_SERVICE_NOT_FOUND); } else if (code == 500) { throw new GramException(GramException.GATEKEEPER_MISCONFIGURED); } else { // from globus code throw new GramException(GramException.HTTP_UNFRAME_FAILED, new Exception("Unexpected reply: " + code)); } } /** Returns total number of jobs currently running * for all credentials -- all callback handlers * * @return number of jobs running */ public static int getActiveJobs() { int jobs = 0; Enumeration e = callbackHandlers.elements(); while(e.hasMoreElements()) { CallbackHandler handler = (CallbackHandler)e.nextElement(); jobs += handler.getRegisteredJobsSize(); } return jobs; } /** Returns number of jobs currently running * for a specified credential (one credential one callback handler) * * @return number of jobs running for given credential */ public static int getActiveJobs(GSSCredential cred) { if (cred == null) { throw new IllegalArgumentException("cred == null"); } CallbackHandler handler = (CallbackHandler)callbackHandlers.get(cred); return (handler == null) ? 0 : handler.getRegisteredJobsSize(); } // ----------- GATEKEEPER CALLS --------------------------- /** * Performs ping operation on the gatekeeper with * default user credentials. * Verifies if the user is authorized to submit a job * to that gatekeeper. * * @throws GramException if an error occurs or user in unauthorized * @param resourceManagerContact resource manager contact */ public static void ping(String resourceManagerContact) throws GramException, GSSException { ping(null, resourceManagerContact); } /** * Performs ping operation on the gatekeeper with * specified user credentials. * Verifies if the user is authorized to submit a job * to that gatekeeper. * * @throws GramException if an error occurs or user in unauthorized * @param cred user credentials * @param resourceManagerContact resource manager contact */ public static void ping(GSSCredential cred, String resourceManagerContact) throws GramException, GSSException { ResourceManagerContact rmc = new ResourceManagerContact(resourceManagerContact); Socket socket = gatekeeperConnect(cred, rmc, false, false); HttpResponse hd = null; try { OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); String msg = GRAMProtocol.PING(rmc.getServiceName(), rmc.getHostName()); // send message out.write(msg.getBytes()); out.flush(); debug("PG SENT:", msg); // receive reply hd = new HttpResponse(in); } catch(IOException e) { throw new GramException(GramException.ERROR_PROTOCOL_FAILED, e); } finally { try { socket.close(); } catch (Exception e) {} } debug("PG RECEIVED:", hd); checkHttpReply(hd.httpCode); } /** * Submits a GramJob to specified gatekeeper as an * interactive job. Performs limited delegation. * * @throws GramException if an error occurs during submisson * @param resourceManagerContact resource manager contact * @param job gram job */ public static void request(String resourceManagerContact, GramJob job) throws GramException, GSSException { request(resourceManagerContact, job, false); } /** * Submits a GramJob to specified gatekeeper as * a interactive or batch job. Performs limited delegation. * * @throws GramException if an error occurs during submisson * @param resourceManagerContact resource manager contact * @param job gram job * @param batchJob true if batch job, interactive otherwise */ public static void request(String resourceManagerContact, GramJob job, boolean batchJob) throws GramException, GSSException { request(resourceManagerContact, job, batchJob, true); } /** * Submits a GramJob to specified gatekeeper as * a interactive or batch job. * * @throws GramException if an error occurs during submisson * @param resourceManagerContact * resource manager contact * @param job * gram job * @param batchJob * true if batch job, interactive otherwise. * @param limitedDelegation * true for limited delegation, false for full delegation. * limited delegation should be the default option. */ public static void request(String resourceManagerContact, GramJob job, boolean batchJob, boolean limitedDelegation) throws GramException, GSSException { GSSCredential cred = getJobCredentials(job); // at this point proxy cannot be null String callbackURL = null; CallbackHandler handler = null; if (!batchJob) { handler = initCallbackHandler(cred); callbackURL = handler.getURL(); logger.debug("Callback url: " + callbackURL); } else { callbackURL = "\"\""; } ResourceManagerContact rmc = new ResourceManagerContact(resourceManagerContact); Socket socket = gatekeeperConnect(cred, rmc, true, limitedDelegation); GatekeeperReply hd = null; try { OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); String msg = GRAMProtocol.REQUEST(rmc.getServiceName(), rmc.getHostName(), GRAMConstants.STATUS_ALL, callbackURL, job.getRSL()); // send message out.write(msg.getBytes()); out.flush(); debug("REQ SENT:", msg); // receive reply hd = new GatekeeperReply(in); } catch(IOException e) { throw new GramException(GramException.ERROR_PROTOCOL_FAILED, e); } finally { try { socket.close(); } catch (Exception e) {} } debug("REQ RECEIVED:", hd); // must be 200 checkHttpReply(hd.httpCode); // protocol version must match checkProtocolVersion(hd.protocolVersion); if (hd.status == 0 || hd.status == GramException.WAITING_FOR_COMMIT) { try { job.setID( hd.jobManagerUrl ); } catch(MalformedURLException ex) { throw new GramException(GramException.INVALID_JOB_CONTACT, ex); } if (!batchJob) handler.registerJob(job); if (hd.status == GramException.WAITING_FOR_COMMIT) { throw new WaitingForCommitException(); } } else { throw new GramException(hd.status); } } // --------------------- JOB MANAGER CALLS -------------------------------- private static GatekeeperReply jmConnect(GSSCredential cred, GlobusURL jobURL, String msg) throws GramException, GSSException { GSSManager manager = ExtendedGSSManager.getInstance(); GatekeeperReply reply = null; GssSocket socket = null; try { ExtendedGSSContext context = (ExtendedGSSContext)manager.createContext(null, GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); GssSocketFactory factory = GssSocketFactory.getDefault(); socket = (GssSocket)factory.createSocket(jobURL.getHost(), jobURL.getPort(), context); socket.setAuthorization(SelfAuthorization.getInstance()); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); out.write(msg.getBytes()); out.flush(); debug("JM SENT:", msg); reply = new GatekeeperReply(in); } catch(IOException e) { throw new GramException(GramException.ERROR_CONNECTION_FAILED, e); } finally { if (socket != null) { try { socket.close(); } catch (Exception e) {} } } debug("JM RECEIVED:", reply); // must be 200 otherwise throw exception checkHttpReply(reply.httpCode); // protocol version must match checkProtocolVersion(reply.protocolVersion); return reply; } /** * Frames and wraps a token according to the GRAM "renew" protocol * for use in a GSI delegation handshake. The input token is framed with * a 4 byte big-endian token length header, and the resulting framed token * wrapped in SSL mode (GSSContext's GSS_MODE option set to MODE_SSL) * * @param c The context used to wrap the token * @param token The unaltered output of the context's initDelegation * @throws GSSException if an error occurs during token wrapping or if * context is insufficient * @return a wrapped, framed token to send to globus job manager */ private static byte[] produceRenewToken(ExtendedGSSContext c, byte[] token) throws GSSException { if (!GSIConstants.MODE_SSL.equals(c.getOption(GSSConstants.GSS_MODE))) { throw new GSSException(GSSException.NO_CONTEXT); } byte[] framedToken = new byte[token.length + 4]; SSLUtil.writeInt(token.length, framedToken, 0); System.arraycopy(token, 0, framedToken, 4, token.length); return c.wrap(framedToken, 0, framedToken.length, null); } /** * Unwraps and discards frame of a token according to the GRAM "renew" * protocol for use in a GSI delegation handshake. The input token is * received from a globus job manager and comes wrapped (SSL mode) and * framed with a 4 byte big-endian token length header. * * @param c The context to use to unwrap the token * @param wrappedToken Token received from job manager during GSI handshake * @throws GSSException if an error occurs during token wrapping or if * context is insufficient * @return a token that can be passed to the context's next initDelegation */ private static byte[] consumeRenewToken(ExtendedGSSContext c, byte[] wrappedToken) throws GSSException { if (!GSIConstants.MODE_SSL.equals(c.getOption(GSSConstants.GSS_MODE))) { throw new GSSException(GSSException.NO_CONTEXT); } byte[] framedToken = c.unwrap(wrappedToken, 0, wrappedToken.length, null); byte[] token = new byte[framedToken.length - 4]; System.arraycopy(framedToken, 4, token, 0, framedToken.length - 4); return token; } /** * Completes a GSI delegation handshake with a globus job manager * that has agreed to a (previously sent) GRAM "renew" request. After * the job manager receives the last token in the handshake, it responds * with a message following the GRAM protocol indicating delegation success * or failure. * * @param context Previously established context with job manager * @param newCred The credential used to generate a new delegated proxy * @param out Stream used to send messages to job manager * @param in Stream used to receive messages from job manager * @throws GSSException if an error occurs during token wrapping/unwrapping * @throws IOException if a communication error occurs * @return the GRAM response message indicating delegation status */ private static GatekeeperReply renewDelegationHandshake( ExtendedGSSContext context, GSSCredential newCred, GSIGssOutputStream out, GSIGssInputStream in) throws GSSException, IOException { byte [] input = new byte[0]; byte [] output = null; do { output = produceRenewToken(context, context.initDelegation( newCred, null, 0, input, 0, input.length)); out.writeToken(output); if (!context.isDelegationFinished()) { input = consumeRenewToken(context, in.readHandshakeToken()); } } while (!context.isDelegationFinished()); GatekeeperReply reply = new GatekeeperReply(in); return reply; } /** * Requests that a globus job manager accept newly delegated credentials. Uses limited delegation. * * @param job The job whose credentials are to be renewed/refreshed * @param newCred The credentials to use in the delegation process * @throws GSSException if a GSSAPI error occurs * @throws GramException if a connection/communication error occurs or if * delegation failed */ public static void renew(GramJob job, GSSCredential newCred) throws GramException, GSSException { renew(job, newCred, true); } /** * Requests that a globus job manager accept newly delegated credentials. * This consists of a "renew" message in the GRAM protocol followed by a * GSI delegation handshake using wrapped/framed tokens. Upon successful * delegation, the job's credentials are set to the ones used in delegation. * * @param job The job whose credentials are to be renewed/refreshed * @param newCred The credentials to use in the delegation process * @param limitedDelegation Whether to use a full or limited proxy * @throws GSSException if a GSSAPI error occurs * @throws GramException if a connection/communication error occurs or if * delegation failed */ public static void renew(GramJob job, GSSCredential newCred, boolean limitedDelegation) throws GramException, GSSException { GSSCredential currentCred = getJobCredentials(job); GlobusURL jobURL = job.getID(); if (jobURL == null) { throw new GramException(GramException.ERROR_JOB_CONTACT_NOT_SET); } GSSManager manager = ExtendedGSSManager.getInstance(); GssSocket socket = null; try { ExtendedGSSContext context = (ExtendedGSSContext)manager.createContext(null, GSSConstants.MECH_OID, currentCred, GSSContext.DEFAULT_LIFETIME); context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); context.setOption(GSSConstants.DELEGATION_TYPE, (limitedDelegation) ? GSIConstants.DELEGATION_TYPE_LIMITED : GSIConstants.DELEGATION_TYPE_FULL); GssSocketFactory factory = GssSocketFactory.getDefault(); socket = (GssSocket)factory.createSocket(jobURL.getHost(), jobURL.getPort(), context); socket.setAuthorization(SelfAuthorization.getInstance()); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); // send GRAM protocol "renew" String msg = GRAMProtocol.RENEW(jobURL.getURL(), jobURL.getHost()); out.write(msg.getBytes()); out.flush(); debug("RENEW SENT:", msg); GatekeeperReply reply = new GatekeeperReply(in); debug("RENEW RECEIVED:", reply); // proceed w/ delegation only if response looks ok checkHttpReply(reply.httpCode); if (reply.failureCode == GramException.JOB_CONTACT_NOT_FOUND) { throw new GramException(GramException.JOB_CONTACT_NOT_FOUND); } reply = renewDelegationHandshake(context, newCred, (GSIGssOutputStream) out, (GSIGssInputStream) in); debug("RENEW RECEIVED: ", reply); checkHttpReply(reply.httpCode); if (reply.failureCode == GramException.DELEGATION_FAILED) { throw new GramException(GramException.DELEGATION_FAILED); } job.setCredentials(newCred); } catch (IOException e) { throw new GramException(GramException.ERROR_CONNECTION_FAILED, e); } finally { if (socket != null) { try { socket.close(); } catch (Exception e) {} } } } /** * This function cancels an already running job. * * @throws GramException if an error occurs during cancel * @param job job to be canceled */ public static void cancel(GramJob job) throws GramException, GSSException { GlobusURL jobURL = job.getID(); if (jobURL == null) { throw new GramException(GramException.ERROR_JOB_CONTACT_NOT_SET); } GSSCredential cred = getJobCredentials(job); String msg = GRAMProtocol.CANCEL_JOB(jobURL.getURL(), jobURL.getHost()); GatekeeperReply reply = jmConnect(cred, jobURL, msg); if (reply.failureCode != 0) { throw new GramException(reply.failureCode); } // this might need to be fixed // if (handler != null) handler.unregisterJob(jobContact); } /** * This function updates the status of a job (within the job object), * and throws an exception if the status is not OK. If the * job manager cannot be contacted the job error code is * set to GramException.ERROR_CONTACTING_JOB_MANAGER and an * exception with the same error code is thrown. * * @throws GramException if an error occurs during status update. * @param job the job whose status is to be updated. */ public static void jobStatus(GramJob job) throws GramException, GSSException { GlobusURL jobURL = job.getID(); GSSCredential cred = getJobCredentials(job); String msg = GRAMProtocol.STATUS_POLL(jobURL.getURL(), jobURL.getHost()); GatekeeperReply hd = null; try { hd = jmConnect(cred, jobURL, msg); } catch(GramException e) { // this is exactly what C does if (e.getErrorCode() == GramException.ERROR_CONNECTION_FAILED) { job.setError( GramException.ERROR_CONTACTING_JOB_MANAGER ); e.setErrorCode( GramException.ERROR_CONTACTING_JOB_MANAGER ); } throw e; } // We didn't seem to care much about setting things // before the status here, presumably because of the // assumption that, when polling, listeners are not used // on the GramJob. I disagree. There is no good reason // why that couldn't happen job.setExitCode( hd.exitCode ); job.setError( hd.failureCode ); job.setStatus( hd.status ); } /** * This function sends a signal to a job. * * @throws GramException if an error occurs during cancel * @param job the signaled job * @param signal type of the signal * @param arg argument of the signal */ public static int jobSignal(GramJob job, int signal, String arg) throws GramException, GSSException { GlobusURL jobURL = job.getID(); GSSCredential cred = getJobCredentials(job); String msg = GRAMProtocol.SIGNAL(jobURL.getURL(), jobURL.getHost(), signal, arg); GatekeeperReply hd = null; hd = jmConnect(cred, jobURL, msg); switch(signal) { case GramJob.SIGNAL_PRIORITY: return hd.failureCode; case GramJob.SIGNAL_STDIO_SIZE: case GramJob.SIGNAL_STDIO_UPDATE: case GramJob.SIGNAL_COMMIT_REQUEST: case GramJob.SIGNAL_COMMIT_EXTEND: case GramJob.SIGNAL_COMMIT_END: case GramJob.SIGNAL_STOP_MANAGER: if (hd.failureCode != 0 && hd.status == GramJob.STATUS_FAILED) { throw new GramException(hd.failureCode); } else if (hd.failureCode == 0 && hd.jobFailureCode != 0) { job.setError( hd.jobFailureCode ); job.setStatus(GramJob.STATUS_FAILED); return hd.failureCode; } else { job.setStatus(hd.status); return 0; } default: job.setStatus( hd.status ); job.setError( hd.failureCode ); return 0; } } /** * This function registers the job for status updates. * * @throws GramException if an error occurs during registration * @param job the job */ public static void registerListener(GramJob job) throws GramException, GSSException { CallbackHandler handler; GSSCredential cred = getJobCredentials(job); handler = initCallbackHandler(cred); registerListener(job, handler); } public static void registerListener(GramJob job, CallbackHandler handler) throws GramException, GSSException { String callbackURL; GlobusURL jobURL; GSSCredential cred = getJobCredentials(job); callbackURL = handler.getURL(); jobURL = job.getID(); String msg = GRAMProtocol.REGISTER_CALLBACK(jobURL.getURL(), jobURL.getHost(), GRAMConstants.STATUS_ALL, callbackURL); GatekeeperReply hd = jmConnect(cred, jobURL, msg); if (hd.failureCode == 0) { handler.registerJob(job); } else { throw new GramException(hd.failureCode); } } /** * This function unregisters the job from callback * listener. The job status will not be updated. * * @throws GramException if an error occurs during unregistering * @param job the job */ public static void unregisterListener(GramJob job) throws GramException, GSSException { CallbackHandler handler; GSSCredential cred = getJobCredentials(job); handler = initCallbackHandler(cred); unregisterListener(job, handler); } public static void unregisterListener(GramJob job, CallbackHandler handler) throws GramException, GSSException { GlobusURL jobURL; GSSCredential cred = getJobCredentials(job); jobURL = job.getID(); String msg = GRAMProtocol.UNREGISTER_CALLBACK(jobURL.getURL(), jobURL.getHost(), handler.getURL()); GatekeeperReply reply = jmConnect(cred, jobURL, msg); handler.unregisterJob(job); } /** * Deactivates all callback handlers. */ public static void deactivateAllCallbackHandlers() { synchronized(callbackHandlers) { Enumeration e = callbackHandlers.elements(); while(e.hasMoreElements()) { CallbackHandler handler = (CallbackHandler)e.nextElement(); handler.shutdown(); } callbackHandlers.clear(); } } /** * Deactivates a callback handler for a given credential. * * @param cred the credential of the callback handler. * @return the callback handler that was deactivated. Null, * if no callback handler is associated with the credential */ public static CallbackHandler deactivateCallbackHandler(GSSCredential cred) { if (cred == null) { return null; } CallbackHandler handler = (CallbackHandler)callbackHandlers.remove(cred); if (handler == null) { return null; } handler.shutdown(); return handler; } // -------- INTERNAL CALLBACK STUFF ----------------------- /** */ protected static Hashtable callbackHandlers = new Hashtable(); static { Deactivator.registerDeactivation(new DeactivationHandler() { public void deactivate() { Gram.deactivateAllCallbackHandlers(); } }); } /** */ private static synchronized CallbackHandler initCallbackHandler(GSSCredential cred) throws GSSException, GramException { if (cred == null) { throw new IllegalArgumentException("cred == null"); } CallbackHandler handler = (CallbackHandler)callbackHandlers.get(cred); if (handler == null) { try { handler = new CallbackHandler(cred, 0); // sets socket timeout to max cred lifetime handler.setTimeout(cred.getRemainingLifetime()); callbackHandlers.put(cred, handler); } catch(IOException e) { throw new GramException(GramException.INIT_CALLBACK_HANDLER_FAILED, e); } } return handler; } /** */ private static GSSCredential getJobCredentials(GramJob job) throws GSSException { GSSCredential cred = job.getCredentials(); if (cred == null) { GSSManager manager = ExtendedGSSManager.getInstance(); cred = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT); job.setCredentials(cred); } return cred; } // --------- DEBUG CONVINIENCE FUNCTIONS ------------ /** * Debug function for displaying the gatekeeper reply. */ private static void debug(String header, GatekeeperReply reply) { if (logger.isTraceEnabled()) { logger.trace(header); logger.trace(reply.toString()); } } /** * Debug function for displaying HTTP responses. */ private static void debug(String header, HttpResponse response) { if (logger.isTraceEnabled()) { logger.trace(header); logger.trace(response.toString()); } } /** A general debug message that prints the header and msg * when the debug level is smaler than 3 * * @param header The header to be printed * @param msg The message to be printed */ private static void debug(String header, String msg) { if (logger.isTraceEnabled()) { logger.trace(header); logger.trace(msg); } } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/GramAttributes.java000066400000000000000000000261371241116057200302020ustar00rootroot00000000000000/** * $Id: GramAttributes.java,v 1.9 2006/04/09 05:56:59 gawor Exp $ */ /* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import java.util.List; import java.util.Map; import org.globus.rsl.RslAttributes; import org.globus.rsl.RslNode; import org.globus.rsl.ParseException; /** * A convienience class for operating on GRAM-specific RSL attributes. * Please note the attribute values for attributes such as setStdout, * setStderr, setStdin, setDirectory, setExecutable, etc. are treated * as single arguments. In case the value contains a RSL variable, * the variable will not be properly resolved. For example, if you * set the stdout to: *
 * atts.setStdout("$(MY_URL)/bar");
 * atts.addEnvVariable("MY_URL", "http://foo");
 * 
* the resulting rsl will look like: *
 * &("stdout"="$(MY_URL)/hello")("environment"=("MY_URL" "http://foo"))
 * 
* Since the "$(MY_URL)/hello" is in double quotes it will be treated as * a single string and the variable will never be resolved. The parser * will set "stdout" to "$(MY_URL)/hello" instead of "http://foo/hello". */ public class GramAttributes extends RslAttributes { public static final int JOBTYPE_SINGLE = 1; public static final int JOBTYPE_MULTIPLE = 2; public static final int JOBTYPE_MPI = 3; public static final int JOBTYPE_CONDOR = 4; /** * Constructs a new, empty GramAttributes object. */ public GramAttributes() { super(); } /** * Constructs a new GramAttributes object initialized with * the specified RSL string. * * @param rsl the rsl string to initialize the class with. * @throws ParseException if the rsl cannot be parsed. */ public GramAttributes(String rsl) throws ParseException { super(rsl); } /** * Constructs a new GramAttributes object initialized with * the specified RSL parse tree. * * @param rslTree the rsl parse tree to initialize the class with. */ public GramAttributes(RslNode rslTree) { super(rslTree); } /** * Specify the name of the executable to run * * @param executable the name of the executable */ public void setExecutable(String executable) { set("executable", executable); } /** * Return executable name * * @return executable */ public String getExecutable() { return getSingle("executable"); } /** * Specify the directory path the executable will be run in * * @param directory the directory path on the submission machine */ public void setDirectory(String directory) { set("directory", directory); } /** * Return directory path * * @return directory */ public String getDirectory() { return getSingle("directory"); } /** * Specify the location to redirect stdout on the submission machine * * @param stdout the location to redirect stdout on the submission machine */ public void setStdout(String stdout) { set("stdout", stdout); } /** * Return the location used to redirect stdout on the submission machine * * @return stdout */ public String getStdout() { return getSingle("stdout"); } /** * Specify the location to redirect stderr on the submission machine * * @param stderr the location to redirect stderr on the submission machine */ public void setStderr(String stderr) { set("stderr", stderr); } /** * Return the location used to redirect stderr on the submission machine * * @return stderr */ public String getStderr() { return getSingle("stderr"); } /** * Specify the location to redirect stdin on the submission machine * * @param stdin the location to redirect stdin on the submission machine */ public void setStdin(String stdin) { set("stdin", stdin); } /** * Return the location used to redirect stdin on the submission machine * * @return stdin */ public String getStdin() { return getSingle("stdin"); } /** * Sets the dryrun parameter. * * @param enable true to enable dryrun, false otherwise. */ public void setDryRun(boolean enable) { set("dryrun", (enable) ? "yes" : "no"); } /** * Checks if dryryn is enabled. * * @return true only if dryrun is enabled. False, * otherwise. */ public boolean isDryRun() { String run = getSingle("dryrun"); if (run == null) return false; if (run.equalsIgnoreCase("yes")) return true; return false; } /** * Specify the queue name to be used for this job * * @param queue the queue name to be used for this job */ public void setQueue(String queue) { set("queue", queue); } /** * Return the queue name used for this job * * @return queue */ public String getQueue() { return getSingle("queue"); } /** * Specify the project to be charged for this job * * @param project the project to be charged for this job */ public void setProject(String project) { set("project", project); } /** * Return the project name charged for this job * * @return project */ public String getProject() { return getSingle("project"); } /** * Sets a job type. * * @param jobType type of the job: One of the following: * SINGLE, MULTIPLE, MPI, or CONDOR. */ public void setJobType(int jobType) { String type = null; switch(jobType) { case JOBTYPE_SINGLE: type = "single"; break; case JOBTYPE_MULTIPLE: type = "multiple"; break; case JOBTYPE_MPI: type = "mpi"; break; case JOBTYPE_CONDOR: type = "condor"; break; } if (type != null) { set("jobtype", type); } } /** * Returns type of the job. * * @return job type. -1 if not set or job type * is unknown. */ public int getJobType() { String jobType = getSingle("jobtype"); if (jobType == null) return -1; if (jobType.equalsIgnoreCase("single")) { return JOBTYPE_SINGLE; } else if (jobType.equalsIgnoreCase("multiple")) { return JOBTYPE_MULTIPLE; } else if (jobType.equalsIgnoreCase("mpi")) { return JOBTYPE_MPI; } else if (jobType.equalsIgnoreCase("condor")) { return JOBTYPE_CONDOR; } else { return -1; } } /** * Specify the minimum memory limit for this job * * @param minmemory the minimum memory limit for this job */ public void setMinMemory(int minmemory) { set("minmemory", String.valueOf(minmemory)); } /** * Return the minimum memory limit set for the job * * @return minmemory */ public int getMinMemory() { String value = getSingle("minmemory"); try { return Integer.parseInt(value); } catch(Exception e) { return -1; } } /** * Specify the nuber of processors to be used by the current executable * * @param numprocs the number of processors to use */ public void setNumProcs(int numprocs) { set("count", String.valueOf(numprocs)); } /** * Return the number of processors * * @return numprocs */ public int getNumProcs() { String value = getSingle("count"); try { return Integer.parseInt(value); } catch(Exception e) { return -1; } } /** * Specify the maximum wall time limit for this job * * @param maxwalltime the maximum wall time limit for this job */ public void setMaxWallTime(int maxwalltime) { set("maxwalltime", String.valueOf(maxwalltime)); } /** * Return the maximum wall time limit set for the job * * @return maxwalltime */ public int getMaxWallTime() { String value = getSingle("maxwalltime"); try { return Integer.parseInt(value); } catch(Exception e) { return -1; } } /** * Specify the maximum cpu time limit for this job * * @param maxcputime the maximum cpu time limit for this job */ public void setMaxCPUTime(int maxcputime) { set("maxcputime", String.valueOf(maxcputime)); } /** * Return the maximum cpu time limit set for the job * * @return maxcputime */ public int getMaxCPUTime() { String value = getSingle("maxcputime"); try { return Integer.parseInt(value); } catch(Exception e) { return -1; } } /** * Specify the maximum memory limit for this job * * @param maxmemory the maximum memory limit for this job */ public void setMaxMemory(int maxmemory) { set("maxmemory", String.valueOf(maxmemory)); } /** * Return the maximum memory limit set for the job * * @return maxmemory */ public int getMaxMemory() { String value = getSingle("maxmemory"); try { return Integer.parseInt(value); } catch(Exception e) { return -1; } } /** * Adds a single argument. * * @param argument an argument to add. * It will be treated as a single argument. */ public void addArgument(String argument) { add("arguments", argument); } /** * Removes a specific argument from the argument list. * * @param argument argument to remove. * @return true if the argument was removed, * false otherwise. */ public boolean deleteArgument(String argument) { return remove("arguments", argument); } /** * Returns a list of arguments. * * @return list of arguments. */ public List getArguments() { return getMulti("arguments"); } /** * Adds an environment variable. * * @param varName the variable name. * @param value the value of the variable. */ public void addEnvVariable(String varName, String value) { addMulti("environment", new String [] {varName, value}); } /** * Removes a specific environment variable from the * environment list. * * @param varName name of the variable to remove. * @return true if the environment variables was removed, * false otherwise. */ public boolean deleteEnvVariable(String varName) { return removeMap("environment", varName); } /** * Returns a variable/value pair list of environment * variables. * * @return the association list of environment * variables. */ public Map getEnvironment() { return getMap("environment"); } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/GramException.java000066400000000000000000000053461241116057200300110ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import java.util.ResourceBundle; import java.util.MissingResourceException; import java.util.Locale; import org.globus.common.ChainedException; import org.globus.gram.internal.GRAMProtocolErrorConstants; /** * This class defeines the Exceptions which are thrown by the various * Gram and GramJob methods. * This class contains many definitions for error codes of the * form ERROR_* in addition to SUCCESS. The error codes are a superset * of those defined for the GRAM C client. Additional error codes * are added for errors that can occur in the Java code. * */ public class GramException extends ChainedException implements GRAMProtocolErrorConstants { private static ResourceBundle resources; static { try { resources = ResourceBundle.getBundle("org.globus.gram.internal.errors", Locale.getDefault()); } catch (MissingResourceException mre) { System.err.println("org.globus.gram.internal.gramerrors.properties not found"); } } public static final int SUCCESS = 0; public static final int INIT_CALLBACK_HANDLER_FAILED = 1000; public static final int ERROR_JOB_CONTACT_NOT_SET = 1003; /** */ public static final int CUSTOM_ERROR = 9999; /** */ protected int errorCode; /** */ public GramException() { super( getMessage( SUCCESS ) ); errorCode = SUCCESS; } /** */ public GramException(int ec) { super( getMessage( ec ) ); errorCode = ec; } public GramException(String msg) { super( msg ); errorCode = CUSTOM_ERROR; } public GramException(int ec, Throwable ex) { super( getMessage( ec ), ex ); errorCode = ec; } /** */ public void setErrorCode(int ec) { errorCode = ec; } /** */ public int getErrorCode() { return errorCode; } public static String getMessage(int errorCode) { if (errorCode == SUCCESS) { return "Success"; } else { if (resources == null) return "Error code: " + errorCode; try { return resources.getString(String.valueOf(errorCode)); } catch (MissingResourceException mre) { return "Error code: " + errorCode; } } } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/GramJob.java000066400000000000000000000317421241116057200265640ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import java.util.Vector; import java.net.MalformedURLException; import org.globus.util.GlobusURL; import org.globus.gram.internal.GRAMConstants; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSCredential; /** * This class represents a simple gram job. It allows * for submitting a job to a gatekeeper, canceling it, * sending a signal command and registering and * unregistering from callback. */ public class GramJob implements GRAMConstants { /* holds job credentials */ private GSSCredential credential; private String rsl; private GlobusURL id; protected int status; protected int error; protected int exitCode; private Vector listeners; /** * Creates a gram job with specified rsl with * default user credentials. * * @param rsl resource specification string */ public GramJob(String rsl) { this.rsl = rsl; this.credential = null; this.id = null; this.status = 0; this.exitCode = Integer.MIN_VALUE; } /** * Creates a gram job with specified rsl and * user credentials. * * @param cred user credentials * @param rsl resource specification string */ public GramJob(GSSCredential cred, String rsl) { this.rsl = rsl; this.credential = cred; this.id = null; this.status = 0; } /** * Add a listener to the GramJob. The listener will be notified whenever * the status of the GramJob changes. * * @param listener The object that wishes to receive status updates. * @see org.globus.gram.GramJobListener */ public void addListener(GramJobListener listener) { if (listeners == null) listeners = new Vector(); listeners.addElement(listener); } /** * Remove a listener from the GramJob. The listener will no longer be * notified of status changes for the GramJob. * * @param listener The object that wishes to stop receiving status updates. * @see org.globus.gram.GramJobListener */ public void removeListener(GramJobListener listener) { if (listeners == null) return; listeners.removeElement(listener); } /** * Gets the rsl of this job. * * @return resource specification string */ public String getRSL() { return rsl; } /** * Gets the credentials of this job. * * @return job credentials. If null none were set. */ public GSSCredential getCredentials() { return this.credential; } /** * Sets credentials of the job * * @param credential user credentials */ public void setCredentials(GSSCredential credential) { this.credential = credential; } /** * Sets the job handle. It is automatically * set after the job successfuly has been * successfuly started on a gatekeeper. * * @param jobUrl job handle in form of url * @throws MalformedURLException if the job * handle is invalid */ public void setID(String jobUrl) throws MalformedURLException { this.id = new GlobusURL(jobUrl); } /** * Gets the job handle of this job. * * @return job handle */ public GlobusURL getID() { return id; } /** * Gets the job handle of this job and * returns it as a string representaion. * * @return job handle as string */ public String getIDAsString() { if (id == null) return null; return id.getURL(); } /** * Gets the current status of this job. * * @return current job status */ public int getStatus() { return status; } /** * Sets the status of the job. * User should not call this function. * * @param status status of the job */ protected void setStatus(int status) { if (this.status == status) return; this.status = status; if (listeners == null) return; int size = listeners.size(); for(int i=0;iAllows querying the job exit code. It only makes sense * to retrieve the exit code after the job has completed. If * the job has not completed, or if the service did not provide * an exit code for this job, this method will return * 0 and {@link #isExitCodeValid()} will return * false.

* @return the job exit code or 0 if the service did * not provide one or the job has not completed. */ public int getExitCode() { return exitCode == Integer.MIN_VALUE ? 0 : exitCode; } /** *

Can be used to determine whether the job exit code * returned by {@link #getExitCode()} is valid.

*

This method will return false if either * of the following is true: *

    *
  • The job has not completed yet
  • *
  • The service did not provide an exit code for * the job
  • *
* @return a boolean value indicating whether the value * returned by {@link #getExitCode()} represents the * actual process exit code of this job. */ public boolean isExitCodeValid() { return exitCode != Integer.MIN_VALUE; } /** * Submits a job to the specified gatekeeper as an * interactive job. Performs limited delegation. * * @param contact the resource manager contact. * The contact can be specified in number of ways for 1.1.3 gatekeepers: *
* host
* host:port
* host:port/service
* host/service
* host:/service
* host::subject
* host:port:subject
* host/service:subject
* host:/service:subject
* host:port/service:subject
* For 1.1.2 gatekeepers full contact string must be specifed. * * @throws GramException * if error occurs during job submission. * @throws GSSException * if user credentials are invalid. */ public void request(String contact) throws GramException, GSSException { Gram.request(contact, this, false); } /** * Submits a job to the specified gatekeeper either as * an interactive or batch job. Performs limited delegation. * * @param contact * the resource manager contact. * @param batch * specifies if the job should be submitted as * a batch job. * @throws GramException * if error occurs during job submission. * @throws GSSException * if user credentials are invalid. * @see #request(String) for detailed resource manager * contact specification. */ public void request(String contact, boolean batch) throws GramException, GSSException { Gram.request(contact, this, batch); } /** * Submits a job to the specified gatekeeper either as * an interactive or batch job. It can perform limited * or full delegation. * * @param contact * the resource manager contact. * @param batch * specifies if the job should be submitted as * a batch job. * @param limitedDelegation * true for limited delegation, false for * full delegation. * @throws GramException * if error occurs during job submission. * @throws GSSException * if user credentials are invalid. * @see #request(String) for detailed resource manager * contact specification. */ public void request(String contact, boolean batch, boolean limitedDelegation) throws GramException, GSSException { Gram.request(contact, this, batch, limitedDelegation); } /** * Requests that the job's delegated credentials be renewed/refreshed. * Uses limited delegation. * * @param newCred The credentials to use in the delegation process * @throws GramException if a connection/comunication error occurs or if * delegation failed * @throws GSSException if a GSSAPI error occurs */ public void renew(GSSCredential newCred) throws GramException, GSSException { renew(newCred, true); } /** * Requests that the job's delegated credentials be renewed/refreshed. * * @param newCred The credentials to use in the delegation process * @param limitedDelegation Whether to use limited or full delegated proxy * @throws GramException if a connection/comunication error occurs or if * delegation failed * @throws GSSException if a GSSAPI error occurs */ public void renew(GSSCredential newCred, boolean limitedDelegation) throws GramException, GSSException { Gram.renew(this, newCred, limitedDelegation); } /** * Cancels a job. * * @throws GramException * if error occurs during job cancelation. * @throws GSSException * if user credentials are invalid. */ public void cancel() throws GramException, GSSException { Gram.cancel(this); } /** * Registers a callback listener for this job. * (Reconnects to the job) * * @throws GramException * if error occurs during job registration. * @throws GSSException * if user credentials are invalid. */ public void bind() throws GramException, GSSException { Gram.registerListener(this); } /** * Unregisters a callback listener for this job. * (Disconnects from the job) * * @throws GramException * if error occurs during job unregistration. * @throws GSSException * if user credentials are invalid. */ public void unbind() throws GramException, GSSException { Gram.unregisterListener(this); } /** * Sends a signal command to the job. * * @param signal signal type * @param arg argument of signal * @throws GramException * if error occurs during signalization. * @throws GSSException * if user credentials are invalid. */ public int signal(int signal, String arg) throws GramException, GSSException { return Gram.jobSignal(this, signal, arg); } /** * Sends a signal command to the job. * * @param signal signal type * @throws GramException * if error occurs during signalization. * @throws GSSException * if user credentials are invalid. */ public int signal(int signal) throws GramException, GSSException { return Gram.jobSignal(this, signal, ""); } /** * Sets the error code of the job. * Note: User should not use this method. * * @param code error code */ protected void setError(int code) { this.error = code; } /** * Gets the error of the job. * * @return error number of the job. */ public int getError() { return error; } /** * Returns string representation of this job. * * @return string representation of this job. Useful for * debugging. */ public String toString() { return "RSL: " + rsl + " id: " + id; } /** * Get the status of the GramJob. * * @return string representing the status of the GramJob. This String is * useful for user-readable output. */ public String getStatusAsString() { return getStatusAsString(status); } /** * Convert the status of a GramJob from an integer to a string. This * method is not typically called by users. * * @return string representing the status of the GramJob passed as an * argument. */ public static String getStatusAsString(int status) { if (status == STATUS_PENDING) { return "PENDING"; } else if (status == STATUS_ACTIVE) { return "ACTIVE"; } else if (status == STATUS_DONE) { return "DONE"; } else if (status == STATUS_FAILED) { return "FAILED"; } else if (status == STATUS_SUSPENDED) { return "SUSPENDED"; } else if (status == STATUS_UNSUBMITTED) { return "UNSUBMITTED"; } else if (status == STATUS_STAGE_IN) { return "STAGE_IN"; } else if (status == STATUS_STAGE_OUT) { return "STAGE_OUT"; } return "Unknown"; } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/GramJobListener.java000066400000000000000000000017611241116057200302700ustar00rootroot00000000000000 /* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; /** * This interface is used to allow objects created by the Globus user to * listen for status changes of GramJobs. * */ public interface GramJobListener { /** * This method is used to notify the implementer when the status of a * GramJob has changed. * * @param job The GramJob whose status has changed. */ public void statusChanged(GramJob job); } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/GramJobRun.java000066400000000000000000000026411241116057200272450ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; public class GramJobRun extends GramJob implements Runnable { String resourceManagerContact = null; private GramJobRun( GSSCredential cred, String rsl ) { super( cred, rsl ); } private GramJobRun( String rsl ) { super( rsl ); } public GramJobRun( String rsl, String resourceManagerContact ) { super( rsl ); this.resourceManagerContact = resourceManagerContact; } public void run() { try { request( resourceManagerContact ); } catch( GSSException gpe ) { System.err.println( "Error: " + gpe.getMessage() ); setStatus( STATUS_FAILED ); } catch( GramException ge ) { System.err.println( "Error: " + ge.getMessage() ); setStatus( STATUS_FAILED ); } } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/WaitingForCommitException.java000066400000000000000000000016611241116057200323410ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; /** * This class represents a specific type of GramException. * This exception is thrown when a two phase commit request is * made to GRAM 1.5 compatibile service. */ public class WaitingForCommitException extends GramException { public WaitingForCommitException() { super(WAITING_FOR_COMMIT); } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/example/000077500000000000000000000000001241116057200260245ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/example/GramClient.java000066400000000000000000000042271241116057200307210ustar00rootroot00000000000000package org.globus.gram.example; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; //import org.globus.ftp.examples.LocalCredentialHelper; import org.globus.gram.GramJob; import org.globus.gram.GramJobListener; import org.globus.gsi.gssapi.auth.IdentityAuthorization; import org.globus.util.ConfigUtil; import org.gridforum.jgss.ExtendedGSSCredential; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; public class GramClient { public static void main(String argv[]) { String port = "ubuntu:50000:"; String DN ="/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand"; try { GramJob j = new GramJob("&(executable=/bin/ls)"); j.request(port + DN ); j.addListener(new GramJobListener() { public void statusChanged(GramJob job) { System.out.println(job.getStatusAsString()); } }); //j.request(port + DN +"/jobmanager-fork"); System.out.println("Submitted"); Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } } } class LocalCredentialHelper { private Log log = LogFactory.getLog(LocalCredentialHelper.class); public GSSCredential getDefaultCredential() throws IOException, GSSException { System.out.println("Proxy Location "+ ConfigUtil.discoverProxyLocation()); return this.getCredential(new File(ConfigUtil.discoverProxyLocation())); } public GSSCredential getCredential(File proxyFile) throws IOException, GSSException { byte[] proxyBytes = new byte[(int) proxyFile.length()]; FileInputStream in = new FileInputStream(proxyFile); in.read(proxyBytes); in.close(); ExtendedGSSManager manager = (ExtendedGSSManager) ExtendedGSSManager.getInstance(); return manager.createCredential(proxyBytes, ExtendedGSSCredential.IMPEXP_OPAQUE, GSSCredential.DEFAULT_LIFETIME, null, GSSCredential.INITIATE_AND_ACCEPT); } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/internal/000077500000000000000000000000001241116057200262055ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/internal/CallbackResponse.java000066400000000000000000000027711241116057200322720ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram.internal; import java.io.InputStream; import java.io.IOException; public class CallbackResponse extends GatekeeperReply { protected String httpMethod = null; protected String callbackURL = null; public CallbackResponse(InputStream in) throws IOException { super(in); } public void parseHttp(String line) { int p1 = line.indexOf(" "); if (p1 == -1) { return; } httpMethod = line.substring(0, p1); int p2 = line.indexOf(" ", p1+1); if (p2 == -1) { return; } callbackURL = line.substring(p1+1, p2); int p3 = line.indexOf(" ", p2+1); if (p3 == -1) { return; } httpType = line.substring(p2+1); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("HttpMethod : " + httpMethod + "\n"); buf.append("URL : " + callbackURL + "\n"); buf.append(super.toString()); return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/internal/GRAMConstants.java000066400000000000000000000105151241116057200314750ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram.internal; public interface GRAMConstants { /** The job is waiting for resources to become available to run. */ public static final int STATUS_PENDING = 1; /** The job has received resources and the application is executing. */ public static final int STATUS_ACTIVE = 2; /* The job terminated before completion because an error, user-triggered cancel, or system-triggered cancel. */ public static final int STATUS_FAILED = 4; /** The job completed successfully */ public static final int STATUS_DONE = 8; /** The job has been suspended. Resources which were allocated for * this job may have been released due to some scheduler-specific * reason. */ public static final int STATUS_SUSPENDED = 16; /** The job has not been submitted to the scheduler yet, pending the * reception of the GLOBUS_GRAM_PROTOCOL_JOB_SIGNAL_COMMIT_REQUEST * signal from a client. */ public static final int STATUS_UNSUBMITTED = 32; /** The job manager is staging in files to run the job. */ public static final int STATUS_STAGE_IN = 64; /** The job manager is staging out files generated by the job. */ public static final int STATUS_STAGE_OUT = 128; /** A mask of all job states. */ public static final int STATUS_ALL = 0xFFFF; /** Cancel a job */ public static final int SIGNAL_CANCEL = 1; /** Suspend a job */ public static final int SIGNAL_SUSPEND = 2; /** Resume a previously suspended job */ public static final int SIGNAL_RESUME = 3; /** Change the priority of a job */ public static final int SIGNAL_PRIORITY = 4; /** Signal the job manager to commence with a job submission if the job * request was accompanied by the (two_state=yes) RSL attribute. */ public static final int SIGNAL_COMMIT_REQUEST = 5; /** Signal the job manager to wait an additional number of seconds * (specified by an integer value string as the signal's argument) before * timing out a two-phase job commit. */ public static final int SIGNAL_COMMIT_EXTEND = 6; /** Signal the job manager to change the way it is currently handling * standard output and/or standard error. The argument for this * signal is an RSL containing new stdout, stderr, stdout_position, * stderr_position, or remote_io_url relations. */ public static final int SIGNAL_STDIO_UPDATE = 7; /** Signal the job manager to verify that streamed I/O has been completely * received. The argument to this signal contains the number of bytes of stdout * and stderr received, seperated by a space. The reply to this signal * will be a SUCCESS message if these matched the amount sent by the * job manager. Otherwise, an error reply indicating * GLOBUS_GRAM_PROTOCOL_ERROR_STDIO_SIZE is returned. * If standard output and standard error are merged, only one number should be * sent as an argument to this signal. An argument of -1 for either stream * size indicates that the client is not interested in the size of that * stream. */ public static final int SIGNAL_STDIO_SIZE = 8; /** Signal the job manager to stop managing the current job and terminate. * The job continues to run as normal. The job manager will send a * state change callback with the job status being FAILED and the error * GLOBUS_GRAM_PROTOCOL_ERROR_JM_STOPPED. */ public static final int SIGNAL_STOP_MANAGER = 9; /** Signal the job manager to clean up after the completion of the job if * the job RSL contained the (two-phase = yes) relation. */ public static final int SIGNAL_COMMIT_END = 10; } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/internal/GRAMProtocol.java000066400000000000000000000101211241116057200313130ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram.internal; /** * This protocol is documented at: * http://www.globus.org/internal/gram-1.1-protocol.html */ import org.globus.util.Util; import org.globus.util.http.HTTPProtocol; public class GRAMProtocol extends HTTPProtocol { public static final int GRAM_PROTOCOL_VERSION = 2; public static final String APPLICATION = "application/x-globus-gram"; public static final String PROTOCOL_VERSION = "protocol-version: "; public static final String JOB_STATE_MASK = "job-state-mask: "; public static final String CALLBACK_URL = "callback-url: "; public static final String RSL = "rsl: "; public static final String STATUS = "status"; public static final String CANCEL = "cancel"; public static final String REGISTER = "register"; public static final String UNREGISTER = "unregister"; public static final String SIGNAL = "signal"; public static final String RENEW = "renew"; public static final String PROTOCOL_VERSION_LINE = PROTOCOL_VERSION + GRAM_PROTOCOL_VERSION + CRLF; public static String REQUEST(String servicename, String hostname, int state_mask, String callback_url, String rsl_string) { StringBuffer msg = new StringBuffer(); msg.append(PROTOCOL_VERSION_LINE); msg.append(JOB_STATE_MASK).append(String.valueOf(state_mask)).append(CRLF); msg.append(CALLBACK_URL).append(callback_url).append(CRLF); msg.append(RSL).append(Util.quote(rsl_string)).append(CRLF).append(CRLF); return createHTTPHeader(servicename, hostname, APPLICATION, msg); } public static String PING(String servicename, String hostname) { return createHTTPHeader("ping" + servicename, hostname, APPLICATION, new StringBuffer(0)); } public static String STATUS_POLL(String jobmanager_url, String hostname) { return JMREQUEST(jobmanager_url, hostname, STATUS); } public static String SIGNAL(String jobmanager_url, String hostname, int signal, String arg) { return JMREQUEST(jobmanager_url, hostname, SIGNAL + " " + signal + " " + arg); } public static String REGISTER_CALLBACK(String jobmanager_url, String hostname, int state_mask, String callback_url) { return JMREQUEST(jobmanager_url, hostname, REGISTER + " " + state_mask + " " + callback_url); } public static String UNREGISTER_CALLBACK(String jobmanager_url, String hostname, String callback_url) { return JMREQUEST(jobmanager_url, hostname, UNREGISTER + " " + callback_url); } public static String RENEW(String jobmanager_url, String hostname) { return JMREQUEST(jobmanager_url, hostname, RENEW); } public static String CANCEL_JOB(String jobmanager_url, String hostname) { return JMREQUEST(jobmanager_url, hostname, CANCEL); } private static final String JMREQUEST(String jobmanager_url, String hostname, String request) { StringBuffer msg = new StringBuffer(); msg.append(PROTOCOL_VERSION_LINE); msg.append(Util.quote(request)); msg.append(CRLF).append(CRLF); return createHTTPHeader(jobmanager_url, hostname, APPLICATION, msg); } public static String OKReply() { return getOKReply(APPLICATION); } } GRAMProtocolErrorConstants.java000066400000000000000000000066461241116057200341640ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/internal/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram.internal; public interface GRAMProtocolErrorConstants { public static final int PARAMETER_NOT_SUPPORTED = 1, INALID_REQUEST = 2, NO_RESOURCES = 3, BAD_DIRECTORY = 4, EXECUTABLE_NOT_FOUND = 5, INSUFFICIENT_FUNDS = 6, ERROR_AUTHORIZATION = 7, USER_CANCELLED = 8, SYSTEM_CANCELLED = 9, PROTOCOL_FAILED = 10, ERROR_PROTOCOL_FAILED = 10, STDIN_NOT_FOUND = 11, CONNECTION_FAILED = 12, ERROR_CONNECTION_FAILED = 12, INVALID_MAXTIME = 13, INVALID_COUNT = 14, NULL_SPECIFICATION_TREE = 15, JM_FAILED_ALLOW_ATTACH = 16, JOB_EXECUTION_FAILED = 17, INVALID_PARADYN = 18, INVALID_JOBTYPE = 19, INVALID_MYJOB = 20, BAD_SCRIPT_ARG_FILE = 21, ARG_FILE_CREATION_FAILED = 22, INVALID_JOBSTATUS = 23, INVALID_SCRIPT_REPLY = 24, INVALID_SCRIPT_STATUS = 25, MPI_NOT_SUPPORTED = 26, UNIMPLEMENTED = 27, TEMP_SCRIPT_FILE_FAILED = 28, USER_PROXY_NOT_FOUND = 29, PROXY_FILE_OPEN_FAILED = 30, JOB_CANCEL_FAILED = 31, MALLOC_FAILED = 32, DUCT_INIT_FAILED = 33, DUCT_LSP_FAILED = 34, INVALID_HOST_COUNT = 35, UNSUPPORTED_PARAMETER = 36, INVALID_QUEUE = 37, INVALID_PROJECT = 38, RSL_EVALUATION_FAILED = 39, BAD_RSL_ENVIRONMENT = 40, DRYRUN = 41, ZERO_LENGTH_RSL = 42, ERROR_STAGING_EXECUTABLE = 43, ERROR_STAGING_STDIN = 44, INVALID_JOB_MANAGER_TYPE = 45, BAD_ARGUMENTS = 46, GATEKEEPER_MISCONFIGURED = 47, BAD_RSL = 48, VERSION_MISMATCH = 49, RSL_ARGUMENTS = 50, RSL_COUNT = 51, RSL_DIRECTORY = 52, RSL_DRYRUN = 53, RSL_ENVIRONMENT = 54, RSL_EXECUTABLE = 55, RSL_HOST_COUNT = 56, RSL_JOBTYPE = 57, RSL_MAXTIME = 58, RSL_MYJOB = 59, ERROR_RSL_PARADYN = 60, ERROR_RSL_PROJECT = 61, ERROR_RSL_QUEUE = 62, ERROR_RSL_STDERR = 63, ERROR_RSL_STDIN = 64, ERROR_RSL_STDOUT = 65, ERROR_OPENING_JOBMANAGER_SCRIPT = 66, ERROR_CREATING_PIPE = 67, ERROR_FCNTL_FAILED = 68, ERROR_STDOUT_FILENAME_FAILED = 69, ERROR_STDERR_FILENAME_FAILED = 70, ERROR_FORKING_EXECUTABLE = 71, EXECUTABLE_PERMISSIONS = 72, ERROR_OPENING_STDOUT = 73, ERROR_OPENING_STDERR = 74, ERROR_OPENING_CACHE_USER_PROXY = 75, ERROR_OPENING_CACHE = 76, ERROR_INSERTING_CLIENT_CONTACT = 77, CLIENT_CONTACT_NOT_FOUND = 78, ERROR_CONTACTING_JOB_MANAGER = 79, INVALID_JOB_CONTACT = 80, EXECUTABLE_UNDEFINED = 81, INVALID_MIN_MEMORY = 86, INVALID_MAX_MEMORY = 87, HTTP_UNFRAME_FAILED = 89, HTTP_UNPACK_FAILED = 91, INVALID_JOB_QUERY = 92, ERROR_SERVICE_NOT_FOUND = 93, JOB_QUERY_DENIAL = 94, CALLBACK_NOT_FOUND = 95, BAD_GATEKEEPER_CONTACT = 96, INVALID_MAX_WALL_TIME = 102, INVALID_MAX_CPU_TIME = 104, ERROR_SIGNALING_JOB = 107, UNKNOWN_SIGNAL_TYPE = 108, WAITING_FOR_COMMIT = 110, COMMIT_TIMED_OUT = 111, JOB_CONTACT_NOT_FOUND = 156, DELEGATION_FAILED = 157; } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/internal/GatekeeperReply.java000066400000000000000000000060231241116057200321410ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram.internal; import org.globus.util.http.HttpResponse; import java.io.IOException; import java.io.InputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class GatekeeperReply extends HttpResponse { private static Log logger = LogFactory.getLog(GatekeeperReply.class.getName()); public int protocolVersion = -1; public int status = -1; public String jobManagerUrl = null; public int failureCode = -1; public int jobFailureCode = -1; // since there is no specification that // would rule out -1 as valid value // for the exit code, it is inapropriate // to mean "special value" public int exitCode = Integer.MIN_VALUE; public GatekeeperReply(InputStream in) throws IOException { super(in); charsRead = 1; if (contentLength > 0) myparse(); } protected void myparse() throws IOException { String line, tmp; while(charsRead < contentLength) { line = readLine(input); if (line.length() == 0) break; if (logger.isTraceEnabled()) { logger.trace(line); } tmp = getRest(line.trim()); if (line.startsWith("protocol-version:")) { protocolVersion = Integer.parseInt(tmp); } else if (line.startsWith("status:")) { status = Integer.parseInt(tmp); } else if (line.startsWith("job-manager-url:")) { jobManagerUrl = tmp; } else if (line.startsWith("failure-code:")) { failureCode = Integer.parseInt(tmp); } else if (line.startsWith("job-failure-code:")) { jobFailureCode = Integer.parseInt(tmp); } else if (line.startsWith("exit-code:")) { // exit code is quoted String unquotedValue = tmp.substring(1, tmp.length() - 1); exitCode = Integer.parseInt(unquotedValue); } } } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(super.toString()); buf.append("Protocol-version : " + protocolVersion + "\n"); buf.append("Status : " + status); if (jobManagerUrl != null) { buf.append("\nJob-manager-url : " + jobManagerUrl); } if (failureCode >= 0) { buf.append("\nFailure-code : " + failureCode); } if (jobFailureCode >= 0) { buf.append("\nJob failure code : " + jobFailureCode); } if (exitCode != Integer.MIN_VALUE) { buf.append("\nExit code : " + exitCode); } return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/internal/package.html000066400000000000000000000010021241116057200304570ustar00rootroot00000000000000 org.globus.gram.internal package Low-level protocol classes used by the org.globus.gram package.

Package Specification

(none)

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/gram/package.html000066400000000000000000000044061241116057200266560ustar00rootroot00000000000000 org.globus.gram package This library is a full implementation of the GRAM client API. It allows for submitting and canceling of jobs, polling for job status and sending signals to a job. The library enables a user to 'ping' a gatekeeper to verify if the user can authenticate to it. In addition, this library allows for registering and un-registering of callback listeners that listen for job status updates. The callbacks are implemented as Java events.
Beyond the functionality of Globus, the Java GRAM API allows the specification of the delegation type to perform-either full or limited.

Notification of state changes for GRAM jobs is supported by the user's class adding itself as a listener to a GramJob. See the example below for more details.

Example

public class GramExample implements GramJobListener {

   private someMethod() {
     ...

     String gramContact = "pitcairn.mcs.anl.gov:6722:...";
     String rsl = "&(executable=...)(...)(...)";
     
     try {
         Gram.ping(gramContact);
     } catch (GramException e) {
        // can't submit
        return;
     }

     job.addListener(this);
     // add this class as a listener for state changes

     GramJob job = null;
     try {
        job = new GramJob(rsl);
	Gram.request(gramContact,job);
     } catch (GramException e) {
        // request failed
        ...
     }

     ...

     try {
         job.cancel();
     } catch (GramException e) {
       // cancel failed
       ...
     }
   }

   // this method must be implemented in order for the class to 
   // implement the GramJobListener class
   public stateChanged(GramJob job) {
       System.out.println("Job state change \n" +
                          "     ID   : " + job.getID() + "\n"  +
			  "     State: " + job.getStateAsString());
    }
}

Package Specification

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/000077500000000000000000000000001241116057200242435ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/ASCII_CharStream.java000066400000000000000000000222141241116057200300500ustar00rootroot00000000000000/* Generated By:JavaCC: Do not edit this line. ASCII_CharStream.java Version 0.7pre6 */ package org.globus.rsl; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public final class ASCII_CharStream { public static final boolean staticFlag = false; int bufsize; int available; int tokenBegin; public int bufpos = -1; private int bufline[]; private int bufcolumn[]; private int column = 0; private int line = 1; private boolean prevCharIsCR = false; private boolean prevCharIsLF = false; private java.io.Reader inputStream; private char[] buffer; private int maxNextCharInd = 0; private int inBuf = 0; private final void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } private final void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } public final char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } private final void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (8 - (column & 07)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } public final char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; return (char)((char)0xff & buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]); } if (++bufpos >= maxNextCharInd) FillBuff(); char c = (char)((char)0xff & buffer[bufpos]); UpdateLineColumn(c); return (c); } /** * @deprecated * @see #getEndColumn */ public final int getColumn() { return bufcolumn[bufpos]; } /** * @deprecated * @see #getEndLine */ public final int getLine() { return bufline[bufpos]; } public final int getEndColumn() { return bufcolumn[bufpos]; } public final int getEndLine() { return bufline[bufpos]; } public final int getBeginColumn() { return bufcolumn[tokenBegin]; } public final int getBeginLine() { return bufline[tokenBegin]; } public final void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } public ASCII_CharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } public ASCII_CharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } public ASCII_CharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); } public ASCII_CharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); } public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } public final String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } public final char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token.
*/ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/AbstractRslNode.java000066400000000000000000000162531241116057200301470ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl; import java.util.*; /** * This class represents an abstract RSL parse tree. It is composed of variable definitions * (bindings), relations, and sub-specifications (sub nodes). */ public abstract class AbstractRslNode { public static final int AND = 1; public static final int OR = 2; public static final int MULTI = 3; protected int _operator; protected List _specifications; public AbstractRslNode() { setOperator(AND); } public AbstractRslNode(int operator) { setOperator(operator); } public abstract boolean add(Bindings bindings); public abstract boolean add(NameOpValue relations); /** * Adds a rsl parse tree to this node. * * @param node the rsl parse tree to add. */ public boolean add(AbstractRslNode node) { if (_specifications == null) _specifications = new LinkedList(); return _specifications.add(node); } /** * Returns the relation associated with the given attribute. * * @param attribute the attribute of the relation. * @return the relation for the attribute. Null, if not found. */ public abstract NameOpValue getParam(String attribute); /** * Returns the variable definitions associated wit the given * attribute. * * @param attribute the attribute of the variable deinitions. * @return the variable deinitions for the attribute. * Null, if not found. */ public abstract Bindings getBindings(String attribute); /** * Removes a specific sub-specification tree from the * sub-specification list. * * @param node node to remove. * @return true if the tree was removed successfuly. False, * otherwise. */ public boolean removeSpecification(AbstractRslNode node) { if (_specifications == null || node == null) return false; return _specifications.remove(node); } /** * Removes a bindings list for the specified attribute. * * @param attribute the attribute name for the * bindings. * @return the bindings that were removed. */ public abstract Bindings removeBindings(String attribute); /** * Removes a relation for the specified attribute. * * @param attribute the attribute name for the * relation to remove. * @return the relation that was removed. */ public abstract NameOpValue removeParam(String attribute); /** * Merges the specified node with the current node. * All sub-specifications from the given node will be * copied to the current node. All relations and variable * definitions will be added together in the current node. * * @param inNode the source parse tree. */ public void merge(AbstractRslNode inNode) { inNode.mergeTo(this); } public void mergeTo(AbstractRslNode dstNode) { Iterator iter = null; if (_specifications != null) { iter = _specifications.iterator(); AbstractRslNode node; while(iter.hasNext()) { node = (AbstractRslNode)iter.next(); dstNode.add(node); } } } /** * Returns the list of sub-specifications. * * @return the list of other sub-specifications. */ public List getSpecifications() { return _specifications; } /** * Returns the node operator. * * @return the operator. */ public int getOperator() { return _operator; } /** * Sets the operator. * * @param oper the operator. */ public void setOperator(int oper) { _operator = oper; } /** * Returns the operator as a string. * * @return operator in a string representation. */ public String getOperatorAsString() { return getOperatorAsString(_operator); } /** * Returns a string represention of a given operator. * * @param op the operator. * @return the string representation of the operator. */ public static String getOperatorAsString(int op) { switch(op) { case AND: return "&"; case MULTI: return "+"; case OR: return "|"; default: return "??"; } } /** * Evalutes the rsl tree. * All the variable definitions are first evaluated because * they might update the symbol table. Then all the relations * followed by the sub-specifications are evaluated. * * @return the evaluated rsl tree. * @exception RslEvaluationException If an error occured during * rsl evaluation. */ public AbstractRslNode evaluate() throws RslEvaluationException { return evaluate(null); } /** * Evalutes the rsl tree against the specified symbol table. * All the variable definitions are first evaluated because * they might update the symbol table. Then all the relations * followed by the sub-specifications are evaluated. * * @param symbolTable the symbol table to evalute variables against. * @return the evaluated rsl tree. * @exception RslEvaluationException If an error occured during * rsl evaluation. */ public abstract AbstractRslNode evaluate(Map symbolTable) throws RslEvaluationException; /** * Returns a RSL representation of this relation.
* Note: Enable explicitConcat to generate more 'valid' RSL * * @param explicitConcat if true explicit concatination will * be used in RSL strings. * @return RSL representation of this relation. */ public String toRSL(boolean explicitConcat) { StringBuffer buf = new StringBuffer(); toRSL(buf, explicitConcat); return buf.toString(); } /** * Produces a RSL representation of node. * * @param buf buffer to add the RSL representation to. * @param explicitConcat if true explicit concatination will * be used in RSL strings. */ public abstract void toRSL(StringBuffer buf, boolean explicitConcat); public String toString() { return toRSL(true); } /** * Canonicalizes a string by removing any underscores and * moving all characters to lowercase. * * @param str string to canonicalize * @return canonicalized string */ public static String canonicalize(String str) { if (str == null) return null; int length = str.length(); char ch; StringBuffer buf = new StringBuffer(length); for (int i=0;i 0) { iter = _bindings.iterator(); localSymbolTable = new HashMap(symbolTable); Bindings binds; while( iter.hasNext() ) { binds = (Bindings)iter.next(); finalRsl.add( binds.evaluate( localSymbolTable ) ); } } else { localSymbolTable = symbolTable; } if (_relations != null && _relations.size() > 0) { iter = _relations.iterator(); NameOpValue nov; while(iter.hasNext()) { nov = (NameOpValue)iter.next(); finalRsl.add( nov.evaluate(localSymbolTable) ); } } if (_specifications != null && _specifications.size() > 0) { iter = _specifications.iterator(); AbstractRslNode node; while(iter.hasNext()) { node = (AbstractRslNode)iter.next(); finalRsl.add( node.evaluate(localSymbolTable) ); } } return finalRsl; } /** * Produces a RSL representation of node. * * @param buf buffer to add the RSL representation to. * @param explicitConcat if true explicit concatination will * be used in RSL strings. */ public void toRSL(StringBuffer buf, boolean explicitConcat) { Iterator iter; buf.append( getOperatorAsString() ); if (_bindings != null && _bindings.size() > 0) { iter = _bindings.iterator(); Bindings binds; while( iter.hasNext() ) { binds = (Bindings)iter.next(); binds.toRSL(buf, explicitConcat); } } if (_relations != null && _relations.size() > 0) { iter = _relations.iterator(); NameOpValue nov; while(iter.hasNext()) { nov = (NameOpValue)iter.next(); nov.toRSL(buf, explicitConcat); } } if (_specifications != null && _specifications.size() > 0) { iter = _specifications.iterator(); AbstractRslNode node; while(iter.hasNext()) { node = (AbstractRslNode)iter.next(); buf.append(" ("); node.toRSL(buf, explicitConcat); buf.append(" )"); } } } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/NameOpValue.java000066400000000000000000000147201241116057200272660ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl; import java.util.*; /** * This class represents a single relation in the RSL string. */ public class NameOpValue extends NameValue { public static final int EQ = 1; public static final int NEQ = 2; public static final int GT = 3; public static final int GTEQ = 4; public static final int LT = 5; public static final int LTEQ = 6; protected int operator; public NameOpValue(String attribute) { super(attribute); } public NameOpValue(String attribute, int op) { super(attribute); setOperator(op); } public NameOpValue(String attribute, int op, String strValue) { this(attribute, op); add(strValue); } public NameOpValue(String attribute, int op, String [] strValues) { this(attribute, op); add(strValues); } public NameOpValue(String attribute, int op, Value value) { this(attribute, op); add(value); } /** * Sets the relation operator. * * @param oper the relation operator. */ public void setOperator(int oper) { operator = oper; } /** * Returns the relation operator. * * @return the relation operator. */ public int getOperator() { return operator; } /** * Returns the relation operator as a string. * * @return the relation operator as a string. */ public String getOperatorAsString() { return getOperatorAsString(operator); } /** * Returns a string representation of the specified * relation operator. * * @param op the relation operator * @return the string representaion of the relation operator. */ public static String getOperatorAsString(int op) { switch(op) { case EQ: return "="; case NEQ: return "!="; case GT: return ">"; case GTEQ: return ">="; case LT: return "<"; case LTEQ: return "<="; default: return "??"; } } /** * Adds a value to the list of values. * * @param value the value to add. */ public void add(Value value) { if (values == null) values = new LinkedList(); values.add(value); } /** * Adds a value to the list of values. * The string value is first converted into * a Value object. * * @param strValue the value to add. */ public void add(String strValue) { add(new Value(strValue)); } /** * Adds an array of values to the list of values. * Each element in the array is converted into a * Value object and inserted as a separate value * into the list of values. * * @param strValues the array of values to add. */ public void add(String [] strValues) { if (strValues == null) return; if (values == null) values = new LinkedList(); for (int i=0;i */ public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal ) { super(""); specialConstructor = true; currentToken = currentTokenVal; expectedTokenSequences = expectedTokenSequencesVal; tokenImage = tokenImageVal; } /** * The following constructors are for use by you for whatever * purpose you can think of. Constructing the exception in this * manner makes the exception behave in the normal way - i.e., as * documented in the class "Throwable". The fields "errorToken", * "expectedTokenSequences", and "tokenImage" do not contain * relevant information. The JavaCC generated code does not use * these constructors. */ public ParseException() { super(); specialConstructor = false; } public ParseException(String message) { super(message); specialConstructor = false; } /** * This variable determines which constructor was used to create * this object and thereby affects the semantics of the * "getMessage" method (see below). */ protected boolean specialConstructor; /** * This is the last token that has been consumed successfully. If * this object has been created due to a parse error, the token * followng this token will (therefore) be the first error token. */ public Token currentToken; /** * Each entry in this array is an array of integers. Each array * of integers represents a sequence of tokens (by their ordinal * values) that is expected at this point of the parse. */ public int[][] expectedTokenSequences; /** * This is a reference to the "tokenImage" array of the generated * parser within which the parse error occurred. This array is * defined in the generated ...Constants interface. */ public String[] tokenImage; /** * This method has the standard behavior when this object has been * created using the standard constructors. Otherwise, it uses * "currentToken" and "expectedTokenSequences" to generate a parse * error message and returns it. If this object has been created * due to a parse error, and you do not catch it (it gets thrown * from the parser), then this method is called during the printing * of the final stack trace, and hence the correct error message * gets displayed. */ public String getMessage() { if (!specialConstructor) { return super.getMessage(); } String expected = ""; int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected += tokenImage[expectedTokenSequences[i][j]] + " "; } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected += "..."; } expected += eol + " "; } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += add_escapes(tok.image); tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn + "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected; return retval; } /** * The end of line string for this machine. */ protected String eol = System.getProperty("line.separator", "\n"); /** * Used to convert raw characters to their escaped version * when these raw version cannot be used as part of an ASCII * string literal. */ protected String add_escapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/RSLParser.java000066400000000000000000000475351241116057200267410ustar00rootroot00000000000000/* Generated By:JavaCC: Do not edit this line. RSLParser.java */ /* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl; import java.io.StringReader; import java.util.LinkedList; import java.util.ListIterator; /** * Parser for the * Globus Resource Specification Language RSL v1.0. *
* Things that are not supported:
* (1) User-specified delimiter for quoted literals.
* (2) RSLs that only contain relations outside of 'spec-list'.

* Other notes:
* (1) Implicit concatenation is not part of the 'simple value' relation * and is implemented by inspecting the white space between individual * values. */ public class RSLParser implements RSLParserConstants { private Class nodeClass = RslNode.class; public static void main(String argv[]) throws ParseException { if ((argv.length != 0) && (argv.length != 1)) { System.err.println("Usage: RSL [rsl string]"); System.exit(1); } RSLParser parser = null; if (argv.length == 0) { parser = new RSLParser(System.in); } else { parser = new RSLParser(new StringReader(argv[0])); } parser.parse(); } public static RslNode parse(String rsl) throws ParseException { return (RslNode)parse(RslNode.class, rsl); } public static AbstractRslNode parse(Class rslNodeClass, String rsl) throws ParseException { RSLParser parser = new RSLParser(new StringReader(rsl)); parser.setRslNodeClass(rslNodeClass); return parser.parse(); } public RSLParser(String rsl) throws ParseException { this(new StringReader(rsl)); } public void setRslNodeClass(Class rslNodeClass) { nodeClass = rslNodeClass; } private String unQuotify(String str, char quoteChar) { char curChar; char nextChar; int size = str.length(); StringBuffer buf = new StringBuffer(size-2); for (int i=1;i 0) { valueList.add( concat(tokenList) ); tokenList.clear(); } } private String unQuotify(Token tok) { switch(tok.kind) { case DOUBLE_QUOTED_LITERAL: return unQuotify(tok.image,'"'); case SINGLE_QUOTED_LITERAL: return unQuotify(tok.image,'\''); default: return tok.image; } } final public AbstractRslNode parse() throws ParseException { AbstractRslNode tree; tree = subSpecification(); jj_consume_token(0); {if (true) return tree;} throw new Error("Missing return statement in function"); } final public void specification(AbstractRslNode parentNode) throws ParseException { AbstractRslNode node; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VARIABLES: case VARIABLES_DQUOTE: case VARIABLES_SQUOTE: case UNQUOTED_LITERAL: case DOUBLE_QUOTED_LITERAL: case SINGLE_QUOTED_LITERAL: relation(parentNode); break; case AND: case OR: case MULTI: node = subSpecification(); parentNode.add(node); break; default: jj_la1[0] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public AbstractRslNode subSpecification() throws ParseException { AbstractRslNode node = null; try { node = (AbstractRslNode)nodeClass.newInstance(); } catch(Exception e) { throw new ParseException("Failed to instantiate rsl node class: " + e.getMessage()); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND: jj_consume_token(AND); specList(node); node.setOperator(RslNode.AND); {if (true) return node;} break; case MULTI: jj_consume_token(MULTI); specList(node); node.setOperator(RslNode.MULTI); {if (true) return node;} break; case OR: jj_consume_token(OR); specList(node); node.setOperator(RslNode.OR); {if (true) return node;} break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } final public void relation(AbstractRslNode node) throws ParseException { String attribute; int op; LinkedList values; Token tok; Bindings bd; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VARIABLES: tok = jj_consume_token(VARIABLES); jj_consume_token(EQUAL); values = bindingSequence(); bd = new Bindings(tok.image); bd.setValues(values); node.add(bd); break; case VARIABLES_DQUOTE: tok = jj_consume_token(VARIABLES_DQUOTE); jj_consume_token(EQUAL); values = bindingSequence(); bd = new Bindings(unQuotify(tok.image,'"')); bd.setValues(values); node.add(bd); break; case VARIABLES_SQUOTE: tok = jj_consume_token(VARIABLES_SQUOTE); jj_consume_token(EQUAL); values = bindingSequence(); bd = new Bindings(unQuotify(tok.image,'\'')); bd.setValues(values); node.add(bd); break; case UNQUOTED_LITERAL: case DOUBLE_QUOTED_LITERAL: case SINGLE_QUOTED_LITERAL: attribute = attribute(); op = op(); values = valueSequence(); NameOpValue nm = new NameOpValue(attribute, op); nm.setValues(values); node.add(nm); break; default: jj_la1[2] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void specList(AbstractRslNode node) throws ParseException { label_1: while (true) { jj_consume_token(RPAREN); specification(node); jj_consume_token(LPAREN); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case RPAREN: ; break; default: jj_la1[3] = jj_gen; break label_1; } } } final public int op() throws ParseException { Token tok; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQUAL: tok = jj_consume_token(EQUAL); {if (true) return NameOpValue.EQ;} break; case NOT_EQUAL: tok = jj_consume_token(NOT_EQUAL); {if (true) return NameOpValue.NEQ;} break; case GREATER_THAN: tok = jj_consume_token(GREATER_THAN); {if (true) return NameOpValue.GT;} break; case GREATER_THAN_EQUAL: tok = jj_consume_token(GREATER_THAN_EQUAL); {if (true) return NameOpValue.GTEQ;} break; case LESS_THAN: tok = jj_consume_token(LESS_THAN); {if (true) return NameOpValue.LT;} break; case LESS_THAN_EQUAL: tok = jj_consume_token(LESS_THAN_EQUAL); {if (true) return NameOpValue.LTEQ;} break; default: jj_la1[4] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } final public String attribute() throws ParseException { String name; name = stringLiteral(); {if (true) return name;} throw new Error("Missing return statement in function"); } final public LinkedList valueSequence() throws ParseException { LinkedList list = new LinkedList(); LinkedList tokenList = new LinkedList(); label_2: while (true) { value(list, tokenList); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case RPAREN: case VARSTART: case UNQUOTED_LITERAL: case DOUBLE_QUOTED_LITERAL: case SINGLE_QUOTED_LITERAL: ; break; default: jj_la1[5] = jj_gen; break label_2; } } if (tokenList.size() > 0) { list.add( concat(tokenList) ); } {if (true) return list;} throw new Error("Missing return statement in function"); } final public LinkedList bindingSequence() throws ParseException { LinkedList list = new LinkedList(); label_3: while (true) { binding(list); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case RPAREN: ; break; default: jj_la1[6] = jj_gen; break label_3; } } {if (true) return list;} throw new Error("Missing return statement in function"); } final public void binding(LinkedList list) throws ParseException { Value value; String name; jj_consume_token(RPAREN); name = stringLiteral(); value = concatSimpleValue(); jj_consume_token(LPAREN); Binding db = new Binding(name, value); list.add(db); } final public void value(LinkedList list, LinkedList tokenList) throws ParseException { Object value = null; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case RPAREN: jj_consume_token(RPAREN); value = valueSequence(); jj_consume_token(LPAREN); list.add(value); break; case VARSTART: case UNQUOTED_LITERAL: case DOUBLE_QUOTED_LITERAL: case SINGLE_QUOTED_LITERAL: value = SimpleValue(list, tokenList); tokenList.add(value); break; default: jj_la1[7] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public Value SimpleValue(LinkedList valueList, LinkedList tokenList) throws ParseException { Token t1 = null; Value v1 = null; Value v2 = null; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case UNQUOTED_LITERAL: case DOUBLE_QUOTED_LITERAL: case SINGLE_QUOTED_LITERAL: t1 = stringToken(); v2 = explicitConcat(valueList, tokenList); updateValueList(t1, valueList, tokenList); Value v = new Value( unQuotify(t1) ); if (v2 != null) { v.concat(v2); } {if (true) return v;} break; case VARSTART: v1 = variableReference(valueList, tokenList); v2 = explicitConcat(valueList, tokenList); if (v2 != null) { v1.concat(v2); } {if (true) return v1;} break; default: jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } final public Value variableReference(LinkedList valueList, LinkedList tokenList) throws ParseException { String name = null; Value value = null; Token t1; t1 = jj_consume_token(VARSTART); name = stringLiteral(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VARSTART: case UNQUOTED_LITERAL: case DOUBLE_QUOTED_LITERAL: case SINGLE_QUOTED_LITERAL: value = concatSimpleValue(); break; default: jj_la1[9] = jj_gen; ; } jj_consume_token(LPAREN); updateValueList(t1, valueList, tokenList); VarRef vr = new VarRef(name); if (value != null) vr.setDefaultValue(value); {if (true) return vr;} throw new Error("Missing return statement in function"); } final public Value explicitConcat(LinkedList valueList, LinkedList tokenList) throws ParseException { Object v1 = null; Value v2 = null; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 27: jj_consume_token(27); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case UNQUOTED_LITERAL: case DOUBLE_QUOTED_LITERAL: case SINGLE_QUOTED_LITERAL: v1 = stringLiteral(); break; case VARSTART: v1 = variableReference(valueList, tokenList); break; default: jj_la1[10] = jj_gen; jj_consume_token(-1); throw new ParseException(); } v2 = explicitConcat(valueList, tokenList); break; default: jj_la1[11] = jj_gen; ; } Value v = null; if (v1 instanceof String) { v = new Value( (String)v1); } else if (v1 instanceof Value) { v = (Value)v1; } if (v2 != null) { v.concat(v2); } {if (true) return v;} throw new Error("Missing return statement in function"); } final public Token stringToken() throws ParseException { Token tok; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case UNQUOTED_LITERAL: tok = jj_consume_token(UNQUOTED_LITERAL); {if (true) return tok;} break; case DOUBLE_QUOTED_LITERAL: tok = jj_consume_token(DOUBLE_QUOTED_LITERAL); {if (true) return tok;} break; case SINGLE_QUOTED_LITERAL: tok = jj_consume_token(SINGLE_QUOTED_LITERAL); {if (true) return tok;} break; default: jj_la1[12] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } final public String stringLiteral() throws ParseException { Token tok; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case UNQUOTED_LITERAL: tok = jj_consume_token(UNQUOTED_LITERAL); {if (true) return tok.image;} break; case DOUBLE_QUOTED_LITERAL: tok = jj_consume_token(DOUBLE_QUOTED_LITERAL); {if (true) return unQuotify(tok.image,'"');} break; case SINGLE_QUOTED_LITERAL: tok = jj_consume_token(SINGLE_QUOTED_LITERAL); {if (true) return unQuotify(tok.image,'\'');} break; default: jj_la1[13] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } // ----------------------------------------------------- final public Value concatSimpleValue() throws ParseException { LinkedList list = new LinkedList(); LinkedList tokenList = new LinkedList(); label_4: while (true) { concatSimpleValueSub(list, tokenList); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VARSTART: case UNQUOTED_LITERAL: case DOUBLE_QUOTED_LITERAL: case SINGLE_QUOTED_LITERAL: ; break; default: jj_la1[14] = jj_gen; break label_4; } } if (tokenList.size() > 0) { list.add( concat(tokenList) ); } if (list.size() == 1) { {if (true) return (Value)list.getFirst();} } else { {if (true) throw new ParseException("Encountered sequence instead of a single value.");} } throw new Error("Missing return statement in function"); } final public void concatSimpleValueSub(LinkedList list, LinkedList tokenList) throws ParseException { Object value = null; value = SimpleValue(list, tokenList); tokenList.add(value); } public RSLParserTokenManager token_source; ASCII_CharStream jj_input_stream; public Token token, jj_nt; private int jj_ntk; private int jj_gen; final private int[] jj_la1 = new int[15]; final private int[] jj_la1_0 = {0x71c7000,0x7000,0x71c0000,0x8000,0xfc0,0x7028000,0x8000,0x7028000,0x7020000,0x7020000,0x7020000,0x8000000,0x7000000,0x7000000,0x7020000,}; public RSLParser(java.io.InputStream stream) { jj_input_stream = new ASCII_CharStream(stream, 1, 1); token_source = new RSLParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 15; i++) jj_la1[i] = -1; } public void ReInit(java.io.InputStream stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 15; i++) jj_la1[i] = -1; } public RSLParser(java.io.Reader stream) { jj_input_stream = new ASCII_CharStream(stream, 1, 1); token_source = new RSLParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 15; i++) jj_la1[i] = -1; } public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 15; i++) jj_la1[i] = -1; } public RSLParser(RSLParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 15; i++) jj_la1[i] = -1; } public void ReInit(RSLParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 15; i++) jj_la1[i] = -1; } final private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; return token; } token = oldToken; jj_kind = kind; throw generateParseException(); } final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; } final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } final private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } private java.util.Vector jj_expentries = new java.util.Vector(); private int[] jj_expentry; private int jj_kind = -1; final public ParseException generateParseException() { jj_expentries.removeAllElements(); boolean[] la1tokens = new boolean[28]; for (int i = 0; i < 28; i++) { la1tokens[i] = false; } if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 15; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1< * Globus Resource Specification Language RSL v1.0. *
* Things that are not supported:
* (1) User-specified delimiter for quoted literals.
* (2) RSLs that only contain relations outside of 'spec-list'.

* Other notes:
* (1) Implicit concatenation is not part of the 'simple value' relation * and is implemented by inspecting the white space between individual * values. */ public class RSLParser { private Class nodeClass = RslNode.class; public static void main(String argv[]) throws ParseException { if ((argv.length != 0) && (argv.length != 1)) { System.err.println("Usage: RSL [rsl string]"); System.exit(1); } RSLParser parser = null; if (argv.length == 0) { parser = new RSLParser(System.in); } else { parser = new RSLParser(new StringReader(argv[0])); } parser.parse(); } public static RslNode parse(String rsl) throws ParseException { return (RslNode)parse(RslNode.class, rsl); } public static AbstractRslNode parse(Class rslNodeClass, String rsl) throws ParseException { RSLParser parser = new RSLParser(new StringReader(rsl)); parser.setRslNodeClass(rslNodeClass); return parser.parse(); } public RSLParser(String rsl) throws ParseException { this(new StringReader(rsl)); } public void setRslNodeClass(Class rslNodeClass) { nodeClass = rslNodeClass; } private String unQuotify(String str, char quoteChar) { char curChar; char nextChar; int size = str.length(); StringBuffer buf = new StringBuffer(size-2); for (int i=1;i 0) { valueList.add( concat(tokenList) ); tokenList.clear(); } } private String unQuotify(Token tok) { switch(tok.kind) { case DOUBLE_QUOTED_LITERAL: return unQuotify(tok.image,'"'); case SINGLE_QUOTED_LITERAL: return unQuotify(tok.image,'\''); default: return tok.image; } } } PARSER_END(RSLParser) SPECIAL_TOKEN : { " " | "\t" | "\r" | "\n" } SKIP : { <"(*" (~["*"])* "*" ("*" | ~["*",")"] (~["*"])* "*")* ")"> } TOKEN : { < EQUAL : "=" > | < NOT_EQUAL : "!=" > | < GREATER_THAN : ">" > | < GREATER_THAN_EQUAL : ">=" > | < LESS_THAN : "<" > | < LESS_THAN_EQUAL : "<=" > | < AND : "&" > | < OR : "|" > | < MULTI : "+" > | < RPAREN : "(" > | < LPAREN : ")" > | < VARSTART : "$(" > | < VARIABLES : "rsl_substitution" | "rslsubstitution" > | < VARIABLES_DQUOTE : "\"" "rsl_substitution" "\"" | "\"" "rslsubstitution" "\"" > | < VARIABLES_SQUOTE : "'" "rsl_substitution" "'" | "'" "rslsubstitution" "'" > | < #CHARACTER : ["a"-"z"] | ["A"-"Z"] > | < #DIGIT : ["0"-"9"] > | < #OTHER_CHAR : "_" | "-" > | < UNQUOTED_LITERAL : (~["+","&","|","(",")","=","<",">", "!","\"","'","^","#","$","\n","\t"," "])+ > | < DOUBLE_QUOTED_LITERAL : "\"" (~["\""] | "\"\"")* "\"" > | < SINGLE_QUOTED_LITERAL : "'" (~["'"] | "''")* "'" > } AbstractRslNode parse() : { AbstractRslNode tree; } { ( tree = subSpecification() ) { return tree; } } void specification(AbstractRslNode parentNode) : { AbstractRslNode node; } { ( relation(parentNode) ) { } | ( node = subSpecification() ) { parentNode.add(node); } } AbstractRslNode subSpecification() : { AbstractRslNode node = null; try { node = (AbstractRslNode)nodeClass.newInstance(); } catch(Exception e) { throw new ParseException("Failed to instantiate rsl node class: " + e.getMessage()); } } { ( "&" specList(node) ) { node.setOperator(RslNode.AND); return node; } | ( "+" specList(node) ) { node.setOperator(RslNode.MULTI); return node; } | ( "|" specList(node) ) { node.setOperator(RslNode.OR); return node; } } void relation(AbstractRslNode node) : { String attribute; int op; LinkedList values; Token tok; Bindings bd; } { ( tok = "=" values = bindingSequence() ) { bd = new Bindings(tok.image); bd.setValues(values); node.add(bd); } | ( tok = "=" values = bindingSequence() ) { bd = new Bindings(unQuotify(tok.image,'"')); bd.setValues(values); node.add(bd); } | ( tok = "=" values = bindingSequence() ) { bd = new Bindings(unQuotify(tok.image,'\'')); bd.setValues(values); node.add(bd); } | ( attribute = attribute() op = op() values = valueSequence() ) { NameOpValue nm = new NameOpValue(attribute, op); nm.setValues(values); node.add(nm); } } void specList(AbstractRslNode node) : { } { ( "(" specification(node) ")" )+ { } } int op() : { Token tok; } { ( tok = ) { return NameOpValue.EQ; } | (tok = ) { return NameOpValue.NEQ; } | (tok = ) { return NameOpValue.GT; } | (tok = ) { return NameOpValue.GTEQ; } | (tok = ) { return NameOpValue.LT; } | (tok = ) { return NameOpValue.LTEQ; } } String attribute() : { String name; } { ( name = stringLiteral() ) { return name; } } LinkedList valueSequence() : { LinkedList list = new LinkedList(); LinkedList tokenList = new LinkedList(); } { ( value(list, tokenList) )+ { if (tokenList.size() > 0) { list.add( concat(tokenList) ); } return list; } } LinkedList bindingSequence() : { LinkedList list = new LinkedList(); } { ( binding(list) )+ { return list; } } void binding(LinkedList list) : { Value value; String name; } { ( "(" name = stringLiteral() value = concatSimpleValue() ")" ) { Binding db = new Binding(name, value); list.add(db); } } void value(LinkedList list, LinkedList tokenList) : { Object value = null; } { ( "(" value = valueSequence() ")" ) { list.add(value); } | ( value = SimpleValue(list, tokenList) ) { tokenList.add(value); } } Value SimpleValue(LinkedList valueList, LinkedList tokenList) : { Token t1 = null; Value v1 = null; Value v2 = null; } { ( t1 = stringToken() v2 = explicitConcat(valueList, tokenList) ) { updateValueList(t1, valueList, tokenList); Value v = new Value( unQuotify(t1) ); if (v2 != null) { v.concat(v2); } return v; } | ( v1 = variableReference(valueList, tokenList) v2 = explicitConcat(valueList, tokenList) ) { if (v2 != null) { v1.concat(v2); } return v1; } } Value variableReference(LinkedList valueList, LinkedList tokenList) : { String name = null; Value value = null; Token t1; } { ( t1 = name = stringLiteral() [ value = concatSimpleValue() ] ")" ) { updateValueList(t1, valueList, tokenList); VarRef vr = new VarRef(name); if (value != null) vr.setDefaultValue(value); return vr; } } Value explicitConcat(LinkedList valueList, LinkedList tokenList) : { Object v1 = null; Value v2 = null; } { [ "#" ( v1 = stringLiteral() | v1 = variableReference(valueList, tokenList) ) v2 = explicitConcat(valueList, tokenList) ] { Value v = null; if (v1 instanceof String) { v = new Value( (String)v1); } else if (v1 instanceof Value) { v = (Value)v1; } if (v2 != null) { v.concat(v2); } return v; } } Token stringToken() : { Token tok; } { ( tok = ) { return tok; } | ( tok = ) { return tok; } | ( tok = ) { return tok; } } String stringLiteral() : { Token tok; } { ( tok = ) { return tok.image; } | ( tok = ) { return unQuotify(tok.image,'"'); } | ( tok = ) { return unQuotify(tok.image,'\''); } } // ----------------------------------------------------- Value concatSimpleValue() : { LinkedList list = new LinkedList(); LinkedList tokenList = new LinkedList(); } { ( concatSimpleValueSub(list, tokenList) )+ { if (tokenList.size() > 0) { list.add( concat(tokenList) ); } if (list.size() == 1) { return (Value)list.getFirst(); } else { throw new ParseException("Encountered sequence instead of a single value."); } } } void concatSimpleValueSub(LinkedList list, LinkedList tokenList) : { Object value = null; } { ( value = SimpleValue(list, tokenList) ) { tokenList.add(value); } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/RSLParserConstants.java000066400000000000000000000033721241116057200306250ustar00rootroot00000000000000/* Generated By:JavaCC: Do not edit this line. RSLParserConstants.java */ /* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl; public interface RSLParserConstants { int EOF = 0; int EQUAL = 6; int NOT_EQUAL = 7; int GREATER_THAN = 8; int GREATER_THAN_EQUAL = 9; int LESS_THAN = 10; int LESS_THAN_EQUAL = 11; int AND = 12; int OR = 13; int MULTI = 14; int RPAREN = 15; int LPAREN = 16; int VARSTART = 17; int VARIABLES = 18; int VARIABLES_DQUOTE = 19; int VARIABLES_SQUOTE = 20; int CHARACTER = 21; int DIGIT = 22; int OTHER_CHAR = 23; int UNQUOTED_LITERAL = 24; int DOUBLE_QUOTED_LITERAL = 25; int SINGLE_QUOTED_LITERAL = 26; int DEFAULT = 0; String[] tokenImage = { "", "\" \"", "\"\\t\"", "\"\\r\"", "\"\\n\"", "", "\"=\"", "\"!=\"", "\">\"", "\">=\"", "\"<\"", "\"<=\"", "\"&\"", "\"|\"", "\"+\"", "\"(\"", "\")\"", "\"$(\"", "", "", "", "", "", "", "", "", "", "\"#\"", }; } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/RSLParserTokenManager.java000066400000000000000000000676751241116057200312440ustar00rootroot00000000000000/* Generated By:JavaCC: Do not edit this line. RSLParserTokenManager.java */ /* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl; import java.io.StringReader; import java.util.LinkedList; import java.util.ListIterator; public class RSLParserTokenManager implements RSLParserConstants { private final int jjStopStringLiteralDfa_0(int pos, long active0) { switch (pos) { case 0: if ((active0 & 0x8000L) != 0L) return 0; if ((active0 & 0x8L) != 0L) return 7; return -1; default : return -1; } } private final int jjStartNfa_0(int pos, long active0) { return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); } private final int jjStopAtPos(int pos, int kind) { jjmatchedKind = kind; jjmatchedPos = pos; return pos + 1; } private final int jjStartNfaWithStates_0(int pos, int kind, int state) { jjmatchedKind = kind; jjmatchedPos = pos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return pos + 1; } return jjMoveNfa_0(state, pos + 1); } private final int jjMoveStringLiteralDfa0_0() { switch(curChar) { case 9: return jjStopAtPos(0, 2); case 10: return jjStopAtPos(0, 4); case 13: return jjStartNfaWithStates_0(0, 3, 7); case 32: return jjStopAtPos(0, 1); case 33: return jjMoveStringLiteralDfa1_0(0x80L); case 35: return jjStopAtPos(0, 27); case 36: return jjMoveStringLiteralDfa1_0(0x20000L); case 38: return jjStopAtPos(0, 12); case 40: return jjStartNfaWithStates_0(0, 15, 0); case 41: return jjStopAtPos(0, 16); case 43: return jjStopAtPos(0, 14); case 60: jjmatchedKind = 10; return jjMoveStringLiteralDfa1_0(0x800L); case 61: return jjStopAtPos(0, 6); case 62: jjmatchedKind = 8; return jjMoveStringLiteralDfa1_0(0x200L); case 124: return jjStopAtPos(0, 13); default : return jjMoveNfa_0(6, 0); } } private final int jjMoveStringLiteralDfa1_0(long active0) { try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0); return 1; } switch(curChar) { case 40: if ((active0 & 0x20000L) != 0L) return jjStopAtPos(1, 17); break; case 61: if ((active0 & 0x80L) != 0L) return jjStopAtPos(1, 7); else if ((active0 & 0x200L) != 0L) return jjStopAtPos(1, 9); else if ((active0 & 0x800L) != 0L) return jjStopAtPos(1, 11); break; default : break; } return jjStartNfa_0(0, active0); } private final void jjCheckNAdd(int state) { if (jjrounds[state] != jjround) { jjstateSet[jjnewStateCnt++] = state; jjrounds[state] = jjround; } } private final void jjAddStates(int start, int end) { do { jjstateSet[jjnewStateCnt++] = jjnextStates[start]; } while (start++ != end); } private final void jjCheckNAddTwoStates(int state1, int state2) { jjCheckNAdd(state1); jjCheckNAdd(state2); } private final void jjCheckNAddStates(int start, int end) { do { jjCheckNAdd(jjnextStates[start]); } while (start++ != end); } private final void jjCheckNAddStates(int start) { jjCheckNAdd(jjnextStates[start]); jjCheckNAdd(jjnextStates[start + 1]); } static final long[] jjbitVec0 = { 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL }; private final int jjMoveNfa_0(int startState, int curPos) { int[] nextStates; int startsAt = 0; jjnewStateCnt = 111; int i = 1; jjstateSet[0] = startState; int j, kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; MatchLoop: do { switch(jjstateSet[--i]) { case 6: if ((0x8ffff420fffff9ffL & l) != 0L) { if (kind > 24) kind = 24; jjCheckNAdd(7); } else if (curChar == 39) jjCheckNAddStates(0, 4); else if (curChar == 34) jjCheckNAddStates(5, 9); else if (curChar == 40) jjstateSet[jjnewStateCnt++] = 0; break; case 0: if (curChar == 42) jjCheckNAddTwoStates(1, 2); break; case 1: if ((0xfffffbffffffffffL & l) != 0L) jjCheckNAddTwoStates(1, 2); break; case 2: if (curChar == 42) jjCheckNAddStates(10, 12); break; case 3: if ((0xfffff9ffffffffffL & l) != 0L) jjCheckNAddTwoStates(4, 2); break; case 4: if ((0xfffffbffffffffffL & l) != 0L) jjCheckNAddTwoStates(4, 2); break; case 5: if (curChar == 41 && kind > 5) kind = 5; break; case 7: if ((0x8ffff420fffff9ffL & l) == 0L) break; if (kind > 24) kind = 24; jjCheckNAdd(7); break; case 37: if (curChar == 34) jjCheckNAddStates(5, 9); break; case 39: if (curChar == 34 && kind > 19) kind = 19; break; case 70: if ((0xfffffffbffffffffL & l) != 0L) jjCheckNAddStates(13, 15); break; case 71: if (curChar == 34) jjCheckNAddStates(13, 15); break; case 72: if (curChar == 34) jjstateSet[jjnewStateCnt++] = 71; break; case 73: if (curChar == 34 && kind > 25) kind = 25; break; case 74: if (curChar == 39) jjCheckNAddStates(0, 4); break; case 76: if (curChar == 39 && kind > 20) kind = 20; break; case 107: if ((0xffffff7fffffffffL & l) != 0L) jjCheckNAddStates(16, 18); break; case 108: if (curChar == 39) jjCheckNAddStates(16, 18); break; case 109: if (curChar == 39) jjstateSet[jjnewStateCnt++] = 108; break; case 110: if (curChar == 39 && kind > 26) kind = 26; break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); MatchLoop: do { switch(jjstateSet[--i]) { case 6: if ((0xefffffffbfffffffL & l) != 0L) { if (kind > 24) kind = 24; jjCheckNAdd(7); } if ((0x4000000040000L & l) != 0L) jjAddStates(19, 20); break; case 1: jjCheckNAddTwoStates(1, 2); break; case 3: case 4: jjCheckNAddTwoStates(4, 2); break; case 7: if ((0xefffffffbfffffffL & l) == 0L) break; if (kind > 24) kind = 24; jjCheckNAdd(7); break; case 8: if ((0x4000000040000L & l) != 0L) jjAddStates(19, 20); break; case 9: if ((0x400000004000L & l) != 0L && kind > 18) kind = 18; break; case 10: case 24: if ((0x800000008000L & l) != 0L) jjCheckNAdd(9); break; case 11: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 10; break; case 12: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 11; break; case 13: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 12; break; case 14: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 13; break; case 15: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 14; break; case 16: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 15; break; case 17: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 16; break; case 18: if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 17; break; case 19: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 18; break; case 20: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 19; break; case 21: if (curChar == 95) jjstateSet[jjnewStateCnt++] = 20; break; case 22: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 21; break; case 23: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 22; break; case 25: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 24; break; case 26: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 25; break; case 27: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 26; break; case 28: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 27; break; case 29: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 28; break; case 30: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 29; break; case 31: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 30; break; case 32: if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 31; break; case 33: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 32; break; case 34: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 33; break; case 35: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 34; break; case 36: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 35; break; case 38: case 55: if ((0x400000004000L & l) != 0L) jjCheckNAdd(39); break; case 40: if ((0x800000008000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 38; break; case 41: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 40; break; case 42: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 41; break; case 43: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 42; break; case 44: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 43; break; case 45: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 44; break; case 46: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 45; break; case 47: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 46; break; case 48: if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 47; break; case 49: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 48; break; case 50: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 49; break; case 51: if (curChar == 95) jjstateSet[jjnewStateCnt++] = 50; break; case 52: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 51; break; case 53: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 52; break; case 54: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 53; break; case 56: if ((0x800000008000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 55; break; case 57: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 56; break; case 58: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 57; break; case 59: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 58; break; case 60: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 59; break; case 61: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 60; break; case 62: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 61; break; case 63: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 62; break; case 64: if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 63; break; case 65: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 64; break; case 66: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 65; break; case 67: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 66; break; case 68: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 67; break; case 69: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 68; break; case 70: jjAddStates(13, 15); break; case 75: case 92: if ((0x400000004000L & l) != 0L) jjCheckNAdd(76); break; case 77: if ((0x800000008000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 75; break; case 78: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 77; break; case 79: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 78; break; case 80: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 79; break; case 81: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 80; break; case 82: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 81; break; case 83: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 82; break; case 84: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 83; break; case 85: if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 84; break; case 86: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 85; break; case 87: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 86; break; case 88: if (curChar == 95) jjstateSet[jjnewStateCnt++] = 87; break; case 89: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 88; break; case 90: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 89; break; case 91: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 90; break; case 93: if ((0x800000008000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 92; break; case 94: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 93; break; case 95: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 94; break; case 96: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 95; break; case 97: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 96; break; case 98: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 97; break; case 99: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 98; break; case 100: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 99; break; case 101: if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 100; break; case 102: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 101; break; case 103: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 102; break; case 104: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 103; break; case 105: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 104; break; case 106: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 105; break; case 107: jjAddStates(16, 18); break; default : break; } } while(i != startsAt); } else { int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); MatchLoop: do { switch(jjstateSet[--i]) { case 6: case 7: if ((jjbitVec0[i2] & l2) == 0L) break; if (kind > 24) kind = 24; jjCheckNAdd(7); break; case 1: if ((jjbitVec0[i2] & l2) != 0L) jjCheckNAddTwoStates(1, 2); break; case 3: case 4: if ((jjbitVec0[i2] & l2) != 0L) jjCheckNAddTwoStates(4, 2); break; case 70: if ((jjbitVec0[i2] & l2) != 0L) jjAddStates(13, 15); break; case 107: if ((jjbitVec0[i2] & l2) != 0L) jjAddStates(16, 18); break; default : break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 111 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } static final int[] jjnextStates = { 91, 106, 107, 109, 110, 54, 69, 70, 72, 73, 2, 3, 5, 70, 72, 73, 107, 109, 110, 23, 36, }; public static final String[] jjstrLiteralImages = { "", null, null, null, null, null, "\75", "\41\75", "\76", "\76\75", "\74", "\74\75", "\46", "\174", "\53", "\50", "\51", "\44\50", null, null, null, null, null, null, null, null, null, "\43", }; public static final String[] lexStateNames = { "DEFAULT", }; static final long[] jjtoToken = { 0xf1fffc1L, }; static final long[] jjtoSkip = { 0x3eL, }; static final long[] jjtoSpecial = { 0x1eL, }; private ASCII_CharStream input_stream; private final int[] jjrounds = new int[111]; private final int[] jjstateSet = new int[222]; protected char curChar; public RSLParserTokenManager(ASCII_CharStream stream) { if (ASCII_CharStream.staticFlag) throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); input_stream = stream; } public RSLParserTokenManager(ASCII_CharStream stream, int lexState) { this(stream); SwitchTo(lexState); } public void ReInit(ASCII_CharStream stream) { jjmatchedPos = jjnewStateCnt = 0; curLexState = defaultLexState; input_stream = stream; ReInitRounds(); } private final void ReInitRounds() { int i; jjround = 0x80000001; for (i = 111; i-- > 0;) jjrounds[i] = 0x80000000; } public void ReInit(ASCII_CharStream stream, int lexState) { ReInit(stream); SwitchTo(lexState); } public void SwitchTo(int lexState) { if (lexState >= 1 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; } private final Token jjFillToken() { Token t = Token.newToken(jjmatchedKind); t.kind = jjmatchedKind; String im = jjstrLiteralImages[jjmatchedKind]; t.image = (im == null) ? input_stream.GetImage() : im; t.beginLine = input_stream.getBeginLine(); t.beginColumn = input_stream.getBeginColumn(); t.endLine = input_stream.getEndLine(); t.endColumn = input_stream.getEndColumn(); return t; } int curLexState = 0; int defaultLexState = 0; int jjnewStateCnt; int jjround; int jjmatchedPos; int jjmatchedKind; public final Token getNextToken() { int kind; Token specialToken = null; Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); matchedToken.specialToken = specialToken; return matchedToken; } jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { matchedToken = jjFillToken(); matchedToken.specialToken = specialToken; return matchedToken; } else { if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { matchedToken = jjFillToken(); if (specialToken == null) specialToken = matchedToken; else { matchedToken.specialToken = specialToken; specialToken = (specialToken.next = matchedToken); } } continue EOFLoop; } } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/RslAttributes.java000066400000000000000000000252321241116057200277210ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl; import java.util.*; /** * This class provides convieniene methods for * accessing and manipulatig simple rsl expressions. * The class provides methods for retreiving and setting * values of specified attributes. */ public class RslAttributes { protected RslNode rslTree; /** * Creates an empty RslAttributes object. */ public RslAttributes() { rslTree = new RslNode(); } /** * Creates a new RslAttributes object with * specified rsl parse tree. * * @param rslTree the rsl parse tree. */ public RslAttributes(RslNode rslTree) { this.rslTree = rslTree; } /** * Creates a new RslAttributes object from * specified RSL string. * * @param rsl the rsl string. * @exception ParseException if the rsl cannot be parsed. */ public RslAttributes(String rsl) throws ParseException { rslTree = RSLParser.parse(rsl); } /** * Returns the rsl parse tree. * * @return the rsl parse tree. */ public RslNode getRslNode() { return rslTree; } /** * Returns a string value of the specified attribute. * If the attribute contains multiple values the * first one is returned. * * @param attribute the rsl attribute to return the value of. * @return value of the relation. Null is returned if there is * no such attribute of the attribute/value relation is * not an equality relation. */ public String getSingle(String attribute) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null || nv.getOperator() != NameOpValue.EQ) return null; Object obj = nv.getFirstValue(); if (obj != null && obj instanceof Value) { return ((Value)obj).getCompleteValue(); } else { return null; } } /** * Returns a list of strings for a specified attribute. * For example for 'arguments' attribute. * * @param attribute the rsl attribute to return the values of. * @return the list of values of the relation. Each value is * a string. Null is returned if there is no such * attribute or the attribute/values relation is not * an equality relation. */ public List getMulti(String attribute) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null || nv.getOperator() != NameOpValue.EQ) return null; List values = nv.getValues(); List list = new LinkedList(); Iterator iter = values.iterator(); Object obj; while( iter.hasNext() ) { obj = iter.next(); if (obj instanceof Value) { list.add( ((Value)obj).getCompleteValue() ); } } return list; } /** * Returns a key/value pair map for a specified attribute. * For example for 'environment' attribute. * Note: Use getVariables() for rsl_substitution attribute. * * @param attribute the rsl attribute to return the key/value pair map of. * @return a key/value pair map. Null is returned if there is no such * attribute defined or if the attribute/value relation is not * an equality relation. */ public Map getMap(String attribute) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null || nv.getOperator() != NameOpValue.EQ) return null; List values = nv.getValues(); Map map = new HashMap(); Iterator iter = values.iterator(); Object obj; while( iter.hasNext() ) { obj = iter.next(); if (obj instanceof List) { String key, value; List list = (List)obj; if (list.size() != 2) continue; // must have 2 values! obj = list.get(0); if (obj instanceof Value) { key = ((Value)obj).getCompleteValue(); } else { continue; } obj = list.get(1); if (obj instanceof Value) { value = ((Value)obj).getCompleteValue(); } else { continue; } map.put(key, value); } } return map; } /** * Returns a variable name/value pair map of variable definitions. * Currently specified by the 'rsl_substitution' attribute. * * @param attribute the attribute that defines variables. Currently, * only 'rsl_substitution' is supported. * @return a variable name/value pair map. Null, if there is no * definitions for a specified attribute. * */ public Map getVariables(String attribute) { Bindings binds = rslTree.getBindings(attribute); if (binds == null) return null; List values = binds.getValues(); Map map = new HashMap(); Iterator iter = values.iterator(); Binding binding; while( iter.hasNext() ) { binding = (Binding)iter.next(); map.put(binding.getName(), binding.getValue().getCompleteValue()); } return map; } /** * Adds a new variable definition to the specified variable definitions * attribute. * * @param attribute the variable definitions attribute - rsl_subsititution. * @param varName the variable name to add. * @param value the value of the variable to add. */ public void addVariable(String attribute, String varName, String value) { Bindings binds = rslTree.getBindings(attribute); if (binds == null) { binds = new Bindings(attribute); rslTree.put(binds); } binds.add(new Binding(varName, value)); } /** * Removes a specific variable definition given a variable name. * * @param attribute the attribute that defines variable definitions. * @param varName the name of the variable to remove. * @return true if the variable was successfully removed. Otherwise, * returns false, */ public boolean removeVariable(String attribute, String varName) { Bindings binds = rslTree.getBindings(attribute); if (binds == null) return false; return binds.removeVariable(varName); } /** * Removes a specific attribute from attribute/value relations. * * @param attribute the attribute name to remove. */ public void remove(String attribute) { rslTree.removeParam(attribute); } /** * Removes a specific value from a list of values of the specified * attribute. * * @param attribute the attribute from which to remote the value from. * @param value the specific value to remove. * @return true if the value was successfully removed. Otherwise, * returns false, */ public boolean remove(String attribute, String value) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null || nv.getOperator() != NameOpValue.EQ) return false; return nv.remove(new Value(value)); } /** * Removes a specific key from a list of values of the specified * attribute. The attribute values must be in the right form. See * the 'environment' rsl attribute. * * @param attribute the attribute to remove the key from. * @param key the key to remove. * @return true if the key was successfully removed. Otherwise, * returns false. */ public boolean removeMap(String attribute, String key) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null || nv.getOperator() != NameOpValue.EQ) return false; List values = nv.getValues(); Iterator iter = values.iterator(); Object obj; int i=0; int found = -1; while( iter.hasNext() ) { obj = iter.next(); if (obj instanceof List) { List vr = (List)obj; if (vr.size() > 0) { Object var = vr.get(0); if (var instanceof Value && ((Value)var).getValue().equals(key)) { found = i; break; } } } i++; } if (found != -1) { values.remove(found); return true; } else { return false; } } protected NameOpValue getRelation(String attribute) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null) { nv = new NameOpValue(attribute, NameOpValue.EQ); rslTree.put(nv); } return nv; } /** * Sets the attribute value to the given value. * All previous values are removed first. * * @param attribute the attribute to set the value of. * @param value the value to add. */ public void set(String attribute, String value) { NameOpValue nv = getRelation(attribute); nv.clear(); nv.add(new Value(value)); } /** * Adds a simple value to the list of values of a given * attribute. * * @param attribute the attribute to add the value to. * @param value the value to add. */ public void add(String attribute, String value) { NameOpValue nv = getRelation(attribute); nv.add(new Value(value)); } /** * Sets the attribute value to the given list of values. * The list of values is added as a single value. * * @param attribute the attribute to set the value of. * @param values the list of values to add. */ public void setMulti(String attribute, String [] values) { NameOpValue nv = getRelation(attribute); nv.clear(); List list = new LinkedList(); for (int i=0;i 0) { localSymbolTable = new HashMap(symbolTable); iter = _bindings.keySet().iterator(); Bindings binds; while( iter.hasNext() ) { binds = getBindings( (String)iter.next() ); finalRsl.put( binds.evaluate( localSymbolTable ) ); } } else { localSymbolTable = symbolTable; } if (_relations != null && _relations.size() > 0) { iter = _relations.keySet().iterator(); NameOpValue nov; while(iter.hasNext()) { nov = getParam( (String)iter.next() ); finalRsl.put( nov.evaluate(localSymbolTable) ); } } if (_specifications != null && _specifications.size() > 0) { iter = _specifications.iterator(); AbstractRslNode node; while(iter.hasNext()) { node = (AbstractRslNode)iter.next(); finalRsl.add( node.evaluate(localSymbolTable) ); } } return finalRsl; } /** * Produces a RSL representation of node. * * @param buf buffer to add the RSL representation to. * @param explicitConcat if true explicit concatination will * be used in RSL strings. */ public void toRSL(StringBuffer buf, boolean explicitConcat) { Iterator iter; buf.append( getOperatorAsString() ); if (_bindings != null && _bindings.size() > 0) { iter = _bindings.keySet().iterator(); Bindings binds; while( iter.hasNext() ) { binds = getBindings( (String)iter.next() ); binds.toRSL(buf, explicitConcat); } } if (_relations != null && _relations.size() > 0) { iter = _relations.keySet().iterator(); NameOpValue nov; while(iter.hasNext()) { nov = getParam( (String)iter.next() ); nov.toRSL(buf, explicitConcat); } } if (_specifications != null && _specifications.size() > 0) { iter = _specifications.iterator(); AbstractRslNode node; while(iter.hasNext()) { node = (AbstractRslNode)iter.next(); buf.append(" ("); node.toRSL(buf, explicitConcat); buf.append(" )"); } } } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/Token.java000066400000000000000000000051571241116057200261760ustar00rootroot00000000000000/* Generated By:JavaCC: Do not edit this line. Token.java Version 0.7pre3 */ package org.globus.rsl; /** * Describes the input token stream. */ public class Token { /** * An integer that describes the kind of this token. This numbering * system is determined by JavaCCParser, and a table of these numbers is * stored in the file ...Constants.java. */ public int kind; /** * beginLine and beginColumn describe the position of the first character * of this token; endLine and endColumn describe the position of the * last character of this token. */ public int beginLine, beginColumn, endLine, endColumn; /** * The string image of the token. */ public String image; /** * A reference to the next regular (non-special) token from the input * stream. If this is the last token from the input stream, or if the * token manager has not read tokens beyond this one, this field is * set to null. This is true only if this token is also a regular * token. Otherwise, see below for a description of the contents of * this field. */ public Token next; /** * This field is used to access special tokens that occur prior to this * token, but after the immediately preceding regular (non-special) token. * If there are no such special tokens, this field is set to null. * When there are more than one such special token, this field refers * to the last of these special tokens, which in turn refers to the next * previous special token through its specialToken field, and so on * until the first special token (whose specialToken field is null). * The next fields of special tokens refer to other special tokens that * immediately follow it (without an intervening regular token). If there * is no such token, this field is null. */ public Token specialToken; /** * Returns the image. */ public final String toString() { return image; } /** * Returns a new Token object, by default. However, if you want, you * can create and return subclass objects based on the value of ofKind. * Simply add the cases to the switch for all those special cases. * For example, if you have a subclass of Token called IDToken that * you want to create if ofKind is ID, simlpy add something like : * * case MyParserConstants.ID : return new IDToken(); * * to the following switch statement. Then you can cast matchedToken * variable to the appropriate type and use it in your lexical actions. */ public static final Token newToken(int ofKind) { switch(ofKind) { default : return new Token(); } } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/TokenMgrError.java000066400000000000000000000101631241116057200276470ustar00rootroot00000000000000/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 0.7pre2 */ package org.globus.rsl; public class TokenMgrError extends Error { /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occured. */ static final int LEXICAL_ERROR = 0; /** * An attempt wass made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their espaced (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexicl error * curLexState : lexical state in which this error occured * errorLine : line number when the error occured * errorColumn : column number when the error occured * errorAfter : prefix that was seen before this error occured * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ private static final String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ public TokenMgrError() { } public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } JGlobus-JGlobus-Release-2.1.0/gram/src/main/java/org/globus/rsl/Value.java000066400000000000000000000126131241116057200261650ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl; import java.util.*; /** * This class represents a simple value (a string) that can be * concatinated with another value. */ public class Value { protected String value; protected Value concatValue; public Value(String value) { this(value, null); } public Value(String value, Value concatValue) { this.value = value; this.concatValue = concatValue; } public boolean equals(Object obj) { if (obj instanceof Value) { Value src = (Value)obj; if (src.getValue() == null) { if (getValue() != null) return false; } else { if (!src.getValue().equals(getValue())) return false; } if (src.getConcat() == null) { if (getConcat() != null) return false; } else { if (!src.getConcat().equals(getConcat())) return false; } return true; } else { return super.equals(obj); } } public int hashCode() { int hashCode = 0; if (this.value != null) { hashCode += this.value.hashCode(); } if (this.concatValue != null) { hashCode += this.concatValue.hashCode(); } return hashCode; } /** * Sets the actual value. * * @param value the new value. */ public void setValue(String value) { this.value = value; } /** * Returns the actual string value. * * @return the current value. */ public String getValue() { return value; } /** * Returns the value that is concatinated * with this value. * * @return the value that is concatinated * with this value. Null, otherwise. */ public Value getConcat() { return concatValue; } /** * Appends the specified value to the end of the chain * of concatinated values. That is, if this value has * no concatinated value then set the specified value * as the concatinated value. If this value already * has a concatinated value then append the * specified value to that concatinated value. * * @param value the value to concatinate. */ public void concat(Value value) { if (concatValue != null) { concatValue.concat(value); } else { concatValue = value; } } /** * Evaluates the value with the specified * symbol table. * In this case the function just returns the * string representation of the actual value. * No symbol table lookups are performed. * * @param symbolTable the symbol table to evaluate * the value against. * @return an evaluated string. * @exception RslEvaluationException If an error occured during * rsl evaluation. */ public String evaluate(Map symbolTable) throws RslEvaluationException { if (concatValue == null) { return value; } else { StringBuffer buf = new StringBuffer(value); buf.append(concatValue.evaluate(symbolTable)); return buf.toString(); } } /** * Returns a RSL representation of this value. * * @param explicitConcat if true explicit concatination will * be used in RSL strings. * @return RSL representation of this value. */ public String toRSL(boolean explicitConcat) { StringBuffer buf = new StringBuffer(); toRSL(buf, explicitConcat); return buf.toString(); } private String quotify(String str) { char curChar; char quoteChar = '"'; int size = str.length(); StringBuffer buf = new StringBuffer(size+2); buf.append(quoteChar); for (int i=0;i org.globus.rsl package This library provides a convenience API for creating, manipulating, and checking the validity of RSL expressions. It also handles an XML-based RSL representation.

Package Specification

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/gram/src/main/resources/000077500000000000000000000000001241116057200224525ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/resources/org/000077500000000000000000000000001241116057200232415ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/resources/org/globus/000077500000000000000000000000001241116057200245345ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/resources/org/globus/gram/000077500000000000000000000000001241116057200254625ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/resources/org/globus/gram/internal/000077500000000000000000000000001241116057200272765ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/main/resources/org/globus/gram/internal/errors.properties000066400000000000000000000213661241116057200327400ustar00rootroot000000000000001 = Parameter not supported 2 = The RSL length is greater than the maximum allowed 3 = No resources available 4 = Bad directory specified 5 = The executable does not exist 6 = Insufficient funds 7 = Authentication with the remote server failed 8 = Job cancelled by user 9 = Job cancelled by system 10 = Data transfer to the server failed 11 = The stdin file does not exist 12 = The connection to the server failed (check host and port) 13 = The provided RSL 'maxtime' value is invalid (not an integer or must be greater than 0) 14 = The provided RSL 'count' value is invalid (not an integer or must be greater than 0) 15 = The job manager received an invalid RSL 16 = Could not connect to job manager 17 = The job failed when the job manager attempted to run it 18 = Paradyn error 19 = The provided RSL 'jobtype' value is invalid 20 = The provided RSL 'myjob' value is invalid 21 = The job manager failed to locate an internal script argument file 22 = The job manager failed to create an internal script argument file 23 = The job manager detected an invalid job state 24 = The job manager detected an invalid script response 25 = The job manager detected an invalid job state 26 = The provided RSL 'jobtype' value is not supported by this job manager 27 = Unimplemented 28 = The job manager failed to create an internal script submission file 29 = The job manager cannot find the user proxy 30 = The job manager failed to open the user proxy 31 = The job manager failed to cancel the job as requested 32 = System memory allocation failed 33 = The interprocess job communication initialization failed 34 = The interprocess job communication setup failed 35 = The provided RSL 'host count' value is invalid 36 = One of the provided RSL parameters is unsupported 37 = The provided RSL 'queue' parameter is invalid 38 = The provided RSL 'project' parameter is invalid 39 = The provided RSL string includes variables that could not be identified 40 = The provided RSL 'environment' parameter is invalid 41 = The provided RSL 'dryrun' parameter is invalid 42 = The provided RSL is invalid (an empty string) 43 = The job manager failed to stage the executable 44 = The job manager failed to stage the stdin file 45 = The requested job manager type is invalid 46 = The provided RSL 'arguments' parameter is invalid 47 = The gatekeeper failed to run the job manager 48 = The provided RSL could not be properly parsed 49 = There is a version mismatch between GRAM components 50 = The provided RSL 'arguments' parameter is invalid 51 = The provided RSL 'count' parameter is invalid 52 = The provided RSL 'directory' parameter is invalid 53 = The provided RSL 'dryrun' parameter is invalid 54 = The provided RSL 'environment' parameter is invalid 55 = The provided RSL 'executable' parameter is invalid 56 = The provided RSL 'host_count' parameter is invalid 57 = The provided RSL 'jobtype' parameter is invalid 58 = The provided RSL 'maxtime' parameter is invalid 59 = The provided RSL 'myjob' parameter is invalid 60 = The provided RSL 'paradyn' parameter is invalid 61 = The provided RSL 'project' parameter is invalid 62 = The provided RSL 'queue' parameter is invalid 63 = The provided RSL 'stderr' parameter is invalid 64 = The provided RSL 'stdin' parameter is invalid 65 = The provided RSL 'stdout' parameter is invalid 66 = The job manager failed to locate an internal script 67 = The job manager failed on the system call pipe() 68 = The job manager failed on the system call fcntl() 69 = The job manager failed to create the temporary stdout filename 70 = The job manager failed to create the temporary stderr filename 71 = The job manager failed on the system call fork() 72 = The executable file permissions do not allow execution 73 = The job manager failed to open stdout 74 = The job manager failed to open stderr 75 = The cache file could not be opened in order to relocate the user proxy 76 = Cannot access cache files in ~/.globus/.gass_cache, check permissions, quota, and disk space 77 = The job manager failed to insert the contact in the client contact list 78 = The contact was not found in the job manager's client contact list 79 = Connecting to the job manager failed. Possible reasons: job terminated, invalid job contact, network problems, ... 80 = The syntax of the job contact is invalid 81 = The executable parameter in the RSL is undefined 82 = The job manager service is misconfigured. condor arch undefined 83 = The job manager service is misconfigured. condor os undefined 84 = The provided RSL 'min_memory' parameter is invalid 85 = The provided RSL 'max_memory' parameter is invalid 86 = The RSL 'min_memory' value is not zero or greater 87 = The RSL 'max_memory' value is not zero or greater 88 = The creation of a HTTP message failed 89 = Parsing incoming HTTP message failed 90 = The packing of information into a HTTP message failed 91 = An incoming HTTP message did not contain the expected information 92 = The job manager does not support the service that the client requested 93 = The gatekeeper failed to find the requested service 94 = The jobmanager does not accept any new requests (shutting down) 95 = The client failed to close the listener associated with the callback URL 96 = The gatekeeper contact cannot be parsed 97 = The job manager could not find the 'poe' command 98 = The job manager could not find the 'mpirun' command 99 = The provided RSL 'start_time' parameter is invalid" 100 = The provided RSL 'reservation_handle' parameter is invalid 101 = The provided RSL 'max_wall_time' parameter is invalid 102 = The RSL 'max_wall_time' value is not zero or greater 103 = The provided RSL 'max_cpu_time' parameter is invalid 104 = The RSL 'max_cpu_time' value is not zero or greater 105 = The job manager is misconfigured, a scheduler script is missing 106 = The job manager is misconfigured, a scheduler script has invalid permissions 107 = The job manager failed to signal the job 108 = The job manager did not recognize/support the signal type 109 = The job manager failed to get the job id from the local scheduler 110 = The job manager is waiting for a commit signal 111 = The job manager timed out while waiting for a commit signal 112 = The provided RSL 'save_state' parameter is invalid 113 = The provided RSL 'restart' parameter is invalid 114 = The provided RSL 'two_phase' parameter is invalid 115 = The RSL 'two_phase' value is not zero or greater 116 = The provided RSL 'stdout_position' parameter is invalid 117 = The RSL 'stdout_position' value is not zero or greater 118 = The provided RSL 'stderr_position' parameter is invalid 119 = The RSL 'stderr_position' value is not zero or greater 120 = The job manager restart attempt failed 121 = The job state file doesn't exist 122 = Could not read the job state file 123 = Could not write the job state file 124 = The old job manager is still alive 125 = The job manager state file TTL expired 126 = It is unknown if the job was submitted 127 = The provided RSL 'remote_io_url' parameter is invalid 128 = Could not write the remote io url file 129 = The standard output/error size is different 130 = The job manager was sent a stop signal (job is still running) 131 = The user proxy expired (job is still running) 132 = The job was not submitted by original jobmanager 133 = The job manager is not waiting for that commit signal 134 = The provided RSL scheduler specific parameter is invalid 135 = The job manager could not stage in a file 136 = The scratch directory could not be created 137 = The provided 'gass_cache' parameter is invalid 138 = The RSL contains attributes which are not valid for job submission 139 = The RSL contains attributes which are not valid for stdio update 140 = The RSL contains attributes which are not valid for job restart 141 = The provided RSL 'file_stage_in' parameter is invalid 142 = The provided RSL 'file_stage_in_shared' parameter is invalid 143 = The provided RSL 'file_stage_out' parameter is invalid 144 = The provided RSL 'gass_cache' parameter is invalid 145 = The provided RSL 'file_cleanup' parameter is invalid 146 = The provided RSL 'scratch_dir' parameter is invalid 147 = The provided scheduler-specific RSL parameter is invalid 148 = A required RSL attribute was not defined in the RSL spec 149 = The gass_cache attribute points to an invalid cache directory 150 = The provided RSL 'save_state' parameter has an invalid value 151 = The job manager could not open the RSL attribute validation file 152 = The job manager could not read the RSL attribute validation file 153 = The provided RSL 'proxy_timeout' is invalid 154 = The RSL 'proxy_timeout' value is not greater than zero 155 = The job manager could not stage out a file 156 = The job contact string does not match any which the job manager is handling 157 = Proxy delegation failed 158 = The job manager could not lock the state lock file 1000 = Failed to start up callback handler 1003 = Job contact not set JGlobus-JGlobus-Release-2.1.0/gram/src/test/000077500000000000000000000000001241116057200204735ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/000077500000000000000000000000001241116057200214145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/000077500000000000000000000000001241116057200222035ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/000077500000000000000000000000001241116057200234765ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/gram/000077500000000000000000000000001241116057200244245ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/gram/GramTest.java000066400000000000000000000060351241116057200270210ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import org.globus.util.deactivator.*; public class GramTest { public static void main(String [] args) { GramJob job1 = new GramJob("&(executable=/bin/sleep)(directory=/tmp)(arguments=15)"); GramJob job2 = new GramJob("&(executable=/bin/sleep)(directory=/tmp)(arguments=25)"); GramJob job3 = new GramJob("&(executable=/bin/sleep)(directory=/tmp)(arguments=35)"); String contact = null; if (args.length == 0) { System.err.println("Usage: java GramTest [resource manager]"); System.exit(1); } contact = args[0]; try { job1.addListener( new GramJobListener() { public void statusChanged(GramJob job) { System.out.println("Job1 status change \n" + " ID : "+ job.getIDAsString() + "\n" + " Status : "+ job.getStatusAsString()); } }); job3.addListener( new GramJobListener() { public void statusChanged(GramJob job) { System.out.println("Job3 status change \n" + " ID : "+ job.getIDAsString() + "\n" + " Status : "+ job.getStatusAsString()); } }); job2.addListener( new GramJobListener() { public void statusChanged(GramJob job) { System.out.println("Job2 status change \n" + " ID : "+ job.getIDAsString() + "\n" + " Status : "+ job.getStatusAsString()); if (job.getStatus() == 2) { try { System.out.println("disconnecting from job2"); job.unbind(); System.out.println("canceling job2"); job.cancel(); } catch(Exception e) { System.out.println(e); } } } }); System.out.println("submitting job1..."); job1.request(contact); System.out.println("job submited: " + job1.getIDAsString()); System.out.println("submitting job2..."); job2.request(contact); System.out.println("job submited: " + job2.getIDAsString()); System.out.println("submitting job3 in batch mode..."); job3.request(contact, true); System.out.println("job submited: " + job3.getIDAsString()); try { Thread.sleep(2000); } catch(Exception e) {} System.out.println("rebinding to job3.."); job3.bind(); try { while ( Gram.getActiveJobs() != 0 ) { Thread.sleep(2000); } } catch(Exception e) {} System.out.println("Test completed."); } catch(Exception e) { System.out.println(e.getMessage()); } finally { Deactivator.deactivateAll(); } } } JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/gram/MultiUserGramTest.java000066400000000000000000000076341241116057200307010ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import org.globus.util.deactivator.Deactivator; import org.globus.gsi.GlobusCredential; import org.globus.gsi.X509Credential; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.ietf.jgss.GSSCredential; public class MultiUserGramTest implements GramJobListener { public void statusChanged(GramJob job) { String subject = "unknown"; try { subject = job.getCredentials().getName().toString(); } catch (Exception e) { } System.out.println( "Job status change \n" + " ID : " + job.getIDAsString() + "\n" + " Status : " + job.getStatusAsString() + "\n" + " Subject : " + subject); } private static GramJob createJob(GSSCredential proxy, GramJobListener listener, String dir, int id) { String subject = "unknown"; try { subject = proxy.getName().toString(); } catch (Exception e) { } GramJob job = null; String env = "(environment=(CERT_SUBJECT \"" + subject + "\"))"; job = new GramJob("&(directory=\"" + dir + "\")" + "(stdout=date.out." + id + ")" + env + "(executable=\"/bin/env\")"); job.setCredentials(proxy); job.addListener(listener); return job; } private static GSSCredential load(String file) { try { X509Credential cred = new X509Credential(file); return new GlobusGSSCredentialImpl(cred, GSSCredential.INITIATE_AND_ACCEPT); } catch(Exception e) { System.err.println("Failed to load proxy: " + e.getMessage()); System.exit(-1); } return null; } private static Thread submit(String contact, GramJob job) { Thread t = new Thread(new JobRun(contact, job)); t.start(); return t; } public static void main(String argv[]) { if (argv.length < 4) { System.out.println("Usage: java MultiUserGramTest" + " contact dir proxy1 proxy2"); System.exit(-1); } String contact = argv[0]; String dir = argv[1]; GSSCredential proxy1, proxy2; GramJob job1, job2; Thread t1, t2; proxy1 = load(argv[2]); proxy2 = load(argv[3]); MultiUserGramTest test = new MultiUserGramTest(); job1 = createJob(proxy1, test, dir, 0); job2 = createJob(proxy2, test, dir, 1); t1 = submit(contact, job1); t2 = submit(contact, job2); System.out.println("wait for job completion."); while(true) { try { Thread.sleep(1000); } catch (InterruptedException e) {} if ( (job1.getStatus() == GramJob.STATUS_DONE || job1.getStatus() == GramJob.STATUS_FAILED) && (job2.getStatus() == GramJob.STATUS_DONE || job2.getStatus() == GramJob.STATUS_FAILED) ) break; } Deactivator.deactivateAll(); } } class JobRun implements Runnable { private String resourceManagerContact = null; private GramJob gramJob = null; public JobRun( String resourceManagerContact, GramJob gramJob ) { this.resourceManagerContact = resourceManagerContact; this.gramJob = gramJob; } public void run() { try { String jobname = gramJob.getCredentials().getName().toString(); System.out.println("Submitting job with subject : " + jobname); Gram.request( resourceManagerContact, gramJob ); System.out.println("Job submitted:\n" + " ID : "+ gramJob.getIDAsString() + "\n" + " Subject : "+ jobname); } catch( Exception gpe ) { System.err.println( "Error: " + gpe.getMessage() ); } } } JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/gram/tests/000077500000000000000000000000001241116057200255665ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/gram/tests/GramAttributesTest.java000066400000000000000000000101151241116057200322240ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram.tests; import org.globus.gram.GramAttributes; import java.util.Map; import java.util.List; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; public class GramAttributesTest extends TestCase { protected GramAttributes attribs; public GramAttributesTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(GramAttributesTest.class); } public void setUp() { //String rsl = "&(executable=/bin/ls)(arguments=-arg1 -arg2 \"-arg3 with space\" \"'arg4 in quotes'\")(directory=/home/gawor)(stdin=https://pitcairn.mcs.anl.gov:9999/test)(environment=(v1 value1/$(JAREK)/value2 ) (v2 $(GLOBUS)) (v3 $(HOME)/data # /bin))"; String rsl = "&(executable=/bin/ls)(arguments=-arg1 -arg2 \"-arg3 with space\" \"'arg4 in quotes'\")(directory=/home/vijay/gram)(stdin=https://localhost:44444/test)(environment=(v1 value1/$(JAREK)/value2 ) (v2 $(GLOBUS)) (v3 $(HOME)/data # /bin))"; try { attribs = new GramAttributes(rsl); } catch(Exception e) { fail("Failed to parse rsl"); } } public void testParse() { assertEquals("executable", "/bin/ls", attribs.getExecutable()); assertEquals("directory", "/home/vijay/gram", attribs.getDirectory()); assertEquals("stdin", "https://localhost:44444/test", attribs.getStdin()); assertEquals("stdout", null, attribs.getStdout()); List args = attribs.getArguments(); assertEquals("arg size", 4, args.size()); assertEquals("arg 1", "-arg1", args.get(0)); assertEquals("arg 2", "-arg2", args.get(1)); assertEquals("arg 3", "-arg3 with space", args.get(2)); assertEquals("arg 4", "'arg4 in quotes'", args.get(3)); Map envs = attribs.getEnvironment(); assertEquals("env size", 3, envs.size()); assertEquals("env1", "value1/$(JAREK)/value2", envs.get("v1")); assertEquals("env2", "$(GLOBUS)", envs.get("v2")); assertEquals("env3", "$(HOME)/data/bin", envs.get("v3")); } public void testModify() { attribs.setExecutable("/bin/ls"); assertEquals("executable", "/bin/ls", attribs.getExecutable()); attribs.setStdout("localhost:22222:/test"); assertEquals("stdout", "localhost:22222:/test", attribs.getStdout()); // modify arg list assertEquals("delete arg1", true, attribs.deleteArgument("-arg2") ); assertEquals("delete arg2", false, attribs.deleteArgument("-noarg") ); attribs.addArgument("test arg"); // check arg list List args = attribs.getArguments(); assertEquals("arg size", 4, args.size()); assertEquals("arg 1", "-arg1", args.get(0)); assertEquals("arg 2", "-arg3 with space", args.get(1)); assertEquals("arg 3", "'arg4 in quotes'", args.get(2)); assertEquals("arg 4", "test arg", args.get(3)); // modify env assertEquals("delete env1", true, attribs.deleteEnvVariable("v2") ); assertEquals("delete env2", false, attribs.deleteEnvVariable("v8") ); attribs.addEnvVariable("v5", "value5"); // check env Map envs = attribs.getEnvironment(); assertEquals("env size", 3, envs.size()); assertEquals("env1", "value1/$(JAREK)/value2", envs.get("v1")); assertEquals("env2", "$(HOME)/data/bin", envs.get("v3")); assertEquals("env3", "value5", envs.get("v5")); System.out.println( attribs.toRSL() ); } } JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/rsl/000077500000000000000000000000001241116057200242765ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/rsl/tests/000077500000000000000000000000001241116057200254405ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/rsl/tests/ListRslNodeTest.java000066400000000000000000000260231241116057200313500ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl.tests; import org.globus.rsl.*; import java.util.*; import java.io.*; import junit.framework.*; import junit.extensions.*; public class ListRslNodeTest extends TestCase { protected ListRslNode rslTree; public ListRslNodeTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(ListRslNodeTest.class); } public void setUp() { String rsl = "&(exECutable=/bin/ls)(arGUments=-arg1 -arg2 \" -arg3 \")(directory=/home/vijay/gram)(stdin=https://localhost:9999/test)(environment=(v1 value1/$(JAREK)/value2 ) (v2 $(GLOBUS)) (v3 $(HOME)/data # /bin))"; try { rslTree = (ListRslNode)RSLParser.parse(ListRslNode.class, rsl); } catch(Exception e) { fail("Failed to parse rsl"); } } public void testMerge() { ListRslNode node = null; String rsl2 = "&(rslSubSTitution=(var1 value1))(arguments=\" -end\")(stdout=stdout.file)"; try { node = (ListRslNode)RSLParser.parse(ListRslNode.class, rsl2); } catch(Exception e) { fail("Failed to parse rsl"); } // merge the rsl rslTree.merge(node); NameOpValue nv = null; List values; nv = rslTree.getParam("ARGUMENTS"); values = nv.getValues(); assertEquals("arg size", 4, values.size()); assertEquals("arg 1", "-arg1", ((Value)values.get(0)).getValue() ); assertEquals("arg 2", "-arg2", ((Value)values.get(1)).getValue() ); assertEquals("arg 3", " -arg3 ", ((Value)values.get(2)).getValue() ); assertEquals("arg 4", " -end", ((Value)values.get(3)).getValue() ); nv = rslTree.getParam("stdout"); values = nv.getValues(); assertEquals("stdout size", 1, values.size()); assertEquals("stdout value", "stdout.file", ((Value)values.get(0)).getValue() ); Bindings db = rslTree.getBindings("rsl_substitutION"); assertTrue("bindings null", (db != null)); values = db.getValues(); assertEquals("rslsubsitution size", 1, values.size() ); assertEquals("rslsub variable", "var1", ((Binding)values.get(0)).getName()); assertEquals("rslsub variable value", "value1", ((Binding)values.get(0)).getValue().getValue()); System.out.println("the final rsl:" + rslTree); } public void testCreate() { ListRslNode rslTree = new ListRslNode(RslNode.AND); Bindings bindings = null; NameOpValue nv = null; List values = null; // two executables! rslTree.add(new NameOpValue("executable", NameOpValue.EQ, "/usr/local/bin/ls")); rslTree.add(new NameOpValue("executable", NameOpValue.EQ, "/bin/ls")); rslTree.add(new NameOpValue("myMemory", NameOpValue.LTEQ, "5")); rslTree.add(new NameOpValue("arguments", NameOpValue.EQ, new String [] {"-l", "-p", " -o "})); bindings = new Bindings("rsl_substitution"); bindings.add(new Binding("var1", "value1")); bindings.add(new Binding("var2", "value2")); bindings.add(new Binding("var3", "value3")); rslTree.add(bindings); // test stuff nv = rslTree.getParam("ARGUMENTS"); values = nv.getValues(); assertEquals("arg size", 3, values.size()); assertEquals("arg 1", "-l", ((Value)values.get(0)).getValue() ); assertEquals("arg 2", "-p", ((Value)values.get(1)).getValue() ); assertEquals("arg 3", " -o ", ((Value)values.get(2)).getValue() ); // remove some args... assertEquals("remove arg", false, nv.remove(new Value("-p "))); assertEquals("remove arg2", true, nv.remove(new Value("-p"))); // test the args again... assertEquals("arg size", 2, values.size()); assertEquals("arg 1", "-l", ((Value)values.get(0)).getValue() ); assertEquals("arg 2", " -o ", ((Value)values.get(1)).getValue() ); // test the executable.. - returns the first one only! nv = rslTree.getParam("EXECUTABLE"); assertEquals("executable", "/usr/local/bin/ls", ((Value)nv.getFirstValue()).getValue() ); nv = rslTree.getParam("MY_MEMORY"); assertEquals("myMemory", "5", ((Value)nv.getFirstValue()).getValue() ); assertEquals("myMemory operator", NameOpValue.LTEQ, nv.getOperator()); // test bindings bindings = rslTree.getBindings("rslSUBstitution"); assertTrue("bindings null", (bindings != null)); values = bindings.getValues(); assertEquals("bind size", 3, values.size()); assertEquals("bind 1", "var1", ((Binding)values.get(0)).getName() ); assertEquals("bind 2", "var2", ((Binding)values.get(1)).getName() ); assertEquals("bind 3", "var3", ((Binding)values.get(2)).getName() ); } public void testRemove() { ListRslNode node = null; String rsl2 = "&(rsl_SubSTitution=(var1 value1))(arguments=\" -end\")(stdout=stdout.file)(stdout=ptys)"; try { node = (ListRslNode)RSLParser.parse(ListRslNode.class, rsl2); } catch(Exception e) { fail("Failed to parse rsl"); } NameOpValue nv = null; Bindings bindings = null; List values; nv = node.removeParam("stdout"); values = nv.getValues(); assertEquals("stdout", "stdout.file", ((Value)values.get(0)).getValue() ); nv = node.removeParam("stdout"); values = nv.getValues(); assertEquals("stdout", "ptys", ((Value)values.get(0)).getValue() ); assertEquals("stdout", null, node.removeParam("stdout")); bindings = node.removeBindings("rslsubstitutION"); values = bindings.getValues(); assertEquals("rsl subst.", "var1", ((Binding)values.get(0)).getName() ); assertEquals("rsl subst.", null, node.removeBindings("rsl_substiTution")); } public void testEvaluate() { String rsl = " + " + "(& " + "(directory = $(TOPDIR))" + "(executable = $(VAR1))" + ")" + "(&" + "(rsl_substitution = (TOPDIR \"/home/vijay/gram\")" + "(DATADIR $(TOPDIR)\"/data\") " + "(EXECDIR $(TOPDIR)/bin) )" + "(executable = $(EXECDIR)/a # .out" + "(* ^-- implicit concatenation *))" + "(directory = $(TOPDIR) )" + "(arguments = $(DATADIR)/file1\n" + "(* ^-- implicit concatenation *)" + "$(DATADIR) # /file2\n" + "(* ^-- explicit concatenation *)" + "'$(FOO)' (* <-- a quoted literal *))" + "(environment = (DATADIR $(DATADIR)))" + "(count = 1)" + ")"; ListRslNode tree = null; try { tree = (ListRslNode)RSLParser.parse(ListRslNode.class, rsl); } catch(Exception e) { fail("Rsl failed to parse!"); } System.out.println( tree.toRSL(true) ); // null is the symbol table Properties p = new Properties(); p.put("VAR1", "testValue1"); p.put("TOPDIR", "/home/gawor"); AbstractRslNode finalRsl = null; try { finalRsl = tree.evaluate(p); } catch (RslEvaluationException e) { fail("failed to evaluate rsl!"); } System.out.println(); System.out.println( finalRsl.toRSL(true) ); NameOpValue nv = null; List values = null; List specs = finalRsl.getSpecifications(); // this should be the first one... finalRsl = (ListRslNode)specs.get(0); assertTrue("rsl node 0 null", (finalRsl != null)); nv = finalRsl.getParam("executable"); values = nv.getValues(); assertEquals("executable", "testValue1", ((Value)values.get(0)).getValue()); nv = finalRsl.getParam("directory"); values = nv.getValues(); assertEquals("directory", "/home/gawor", ((Value)values.get(0)).getValue()); // this should be the second one... finalRsl = (ListRslNode)specs.get(1); assertTrue("rsl node 1 null", (finalRsl != null)); nv = finalRsl.getParam("executable"); values = nv.getValues(); assertEquals("executable", "/home/vijay/gram/bin/a.out", ((Value)values.get(0)).getValue()); nv = finalRsl.getParam("directory"); values = nv.getValues(); assertEquals("directory", "/home/vijay/gram", ((Value)values.get(0)).getValue()); nv = finalRsl.getParam("arguments"); values = nv.getValues(); assertEquals("arg1", "/home/vijay/gram/data/file1", ((Value)values.get(0)).getValue()); assertEquals("arg2", "/home/vijay/gram/data/file2", ((Value)values.get(1)).getValue()); assertEquals("arg3", "$(FOO)", ((Value)values.get(2)).getValue()); nv = finalRsl.getParam("environment"); values = nv.getValues(); values = (List)values.get(0); assertEquals("env name", "DATADIR", ((Value)values.get(0)).getValue()); assertEquals("env value", "/home/vijay/gram/data", ((Value)values.get(1)).getValue()); Bindings bindings = finalRsl.getBindings("rsl_substitution"); assertTrue("bindings null", (bindings != null)); values = bindings.getValues(); assertEquals("bind1: name", "TOPDIR", ((Binding)values.get(0)).getName()); assertEquals("bind1: value", "/home/vijay/gram", ((Binding)values.get(0)).getValue().getValue()); assertEquals("bind2: name", "DATADIR", ((Binding)values.get(1)).getName()); assertEquals("bind2: value", "/home/vijay/gram/data", ((Binding)values.get(1)).getValue().getValue()); assertEquals("bind3: name", "EXECDIR", ((Binding)values.get(2)).getName()); assertEquals("bind3: value", "/home/vijay/gram/bin", ((Binding)values.get(2)).getValue().getValue()); } } JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/rsl/tests/RSLParserTest.java000066400000000000000000000162671241116057200307740ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl.tests; import org.globus.rsl.*; import java.util.*; import java.io.*; import junit.framework.*; import junit.extensions.*; public class RSLParserTest extends TestCase { private Properties validRsls; private Properties invalidRsls; public RSLParserTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(RSLParserTest.class); } public void setUp() { validRsls = new Properties(); validRsls.put("rsl1", "+(&(executable=myprogram)(stdin<2.4))(&(stdin=8) \n\n\n(stdin=0))"); validRsls.put("rsl2", "&(executable=myprogram)(stdin<2.4)(stdin=8)(stdin=0)"); validRsls.put("rsl3", "&(a=a)(a=b)"); validRsls.put("rsl4", " &(a=a)"); validRsls.put("rsl5", "(* dont use this comment *)\n&(string=\"my name is \"\"Nick Karonis\"\" today\") (*or this one*)"); validRsls.put("rsl6", "&(&(&(&(a=a))))"); validRsls.put("rsl7", "&(args=\"aa ) bb\")"); validRsls.put("rsl8", "+(&(executable=myprogram)(stdin<2.4))(|(stdin=8) \n\n\n(stdin=0))"); validRsls.put("rsl9", "+(&(executable=myprogram)(stdin<2.4)(|(a=bbb)(yyy=z)))(|(stdin=8) \n\n\n(stdin=0))"); validRsls.put("rsl10", "&(args=hello \n\n)"); validRsls.put("rsl11", "&(executable=\"\")"); validRsls.put("rsl12", "&(executable=\"abc \"\" \"\" def\")"); //validRsls.put("rsl13", "args=\"aa ) \"\"bb cc dd\""); validRsls.put("rsl14", "&((*comment*)string(*comment*) \n=(*comment\ncontinue comment*)\"my (* ok *) name is \"\"Nick Karonis\"\" today\"(*comment*)) (* or this one *)"); validRsls.put("rsl15", "&(* dont use this comment *)\n(\n(*comment*)string(*comment*)\n=(*comment\ncontinue comment*)\"my name is \"\"Nick Karonis\"\" today\"(*comment*)) (*or this one*)"); //validRsls.put("rsl16", "(* dont use this comment *)\n(* comment*) string (* comment*)\n=(*comment\ncontinue comment*)\"my name is \"\"Nick Karonis\"\" today\"(*comment*) (*or this one*)"); validRsls.put("rsl17", "+(* dont use this comment *)\n((*comment*)string(*comment*)=(*comment\ncontinue comment*)\"my name is \"\"Nick Karonis\"\" today\"(*comment*)) (*or this one*)"); validRsls.put("rsl18", "+(string='let''s try ''single quotes'' with \"double too\" ok')"); invalidRsls = new Properties(); invalidRsls.put("rsl1", "(my executable=a.out)"); invalidRsls.put("rsl2", "(executable=/home /a.ou:t#22)"); invalidRsls.put("rsl3", "&(args=dddd)(executable=)(more_args=ooo)"); invalidRsls.put("rsl4", "(executable=^$test $$$ quotes$)"); invalidRsls.put("rsl5", "(executable=^$my value $ \nmore \"\"\" stuff)"); invalidRsls.put("rsl6", "(executable=)"); invalidRsls.put("rsl7", "(args=\"\"a\"\"b\")"); invalidRsls.put("rsl8", "(args=hello \n\nworld)"); invalidRsls.put("rsl9", "(arguments=\"ccc ddd\"\"zzz\"\")"); //invalidRsls.put("rsl10", "&(arguments=\"\"\"\"\")(exe=abc)"); invalidRsls.put("rsl11", "(a=a)"); invalidRsls.put("rsl12", "+(&(executable=myprogram)(stdin<2.4))(+(stdin=8) \n\n\n(stdin=0))+"); invalidRsls.put("rsl13", "(=a.out)"); invalidRsls.put("rsl14", "(executable=\")"); invalidRsls.put("rsl15", "(executable=^\")"); invalidRsls.put("rsl16", "(executable=^/)"); } public void testAdvanced() throws Exception { String rsl = "&(arguments = -e '$GLOBUS_SH_PERL -e ''print STDERR \"stderr\n\"; '" + "# 'print STDOUT \"stdout\n\";''')"; RslNode node = RSLParser.parse(rsl); NameOpValue nv = null; List values; nv = node.getParam("ARGUMENTS"); values = nv.getValues(); assertEquals("arg size", 2, values.size()); assertEquals("arg 1", "-e", ((Value)values.get(0)).getValue() ); String e = "$GLOBUS_SH_PERL -e 'print STDERR \"stderr\n\"; print STDOUT \"stdout\n\";'"; assertEquals("arg 2", e, ((Value)values.get(1)).getCompleteValue() ); } public void testSlash() throws Exception { String rsl; RslNode node; rsl = "&(executable=/bin/echo)(arguments=\\)"; node = RSLParser.parse(rsl); NameOpValue nv = null; List values; nv = node.getParam("ARGUMENTS"); values = nv.getValues(); assertEquals("arg size", 1, values.size()); assertEquals("arg 1", "\\", ((Value)values.get(0)).getCompleteValue() ); rsl = "&(executable=/bin/echo)(arguments=\"\\\")"; node = RSLParser.parse(rsl); assertEquals("arg size", 1, values.size()); assertEquals("arg 1", "\\", ((Value)values.get(0)).getCompleteValue() ); } public void testValid() { Enumeration e = validRsls.keys(); String key; String rsl; while(e.hasMoreElements()) { key = (String)e.nextElement(); rsl = validRsls.getProperty(key); System.out.println("Parsing valid rsl " + key + ": " + rsl); try { RSLParser.parse(rsl); } catch(Exception ex) { ex.printStackTrace(); fail("Failed to parse!!!"); } } } public void testInvalid() { Enumeration e = invalidRsls.keys(); String key; String rsl; while(e.hasMoreElements()) { key = (String)e.nextElement(); rsl = invalidRsls.getProperty(key); System.out.println("Parsing invalid rsl " + key + ": " + rsl); try { RslNode tree = RSLParser.parse(rsl); fail("Failed to catch parse error of " + rsl); } catch(Exception ex) { } } } public void testQuotes() throws Exception { String rsl; RslNode node; rsl = "&(arg1=\"foo\"\"bar\")(arg2='foo''bar')(arg3='')(arg4=\"\")" + "(executable=\"/bin/echo\")(arguments='mis')"; node = RSLParser.parse(rsl); testQuotesSub(node); rsl = node.toString(); node = RSLParser.parse(rsl); testQuotesSub(node); } private void testQuotesSub(RslNode node) { NameOpValue nv = null; List values; nv = node.getParam("arg1"); values = nv.getValues(); assertEquals("arg1", "foo\"bar", ((Value)values.get(0)).getCompleteValue() ); nv = node.getParam("arg2"); values = nv.getValues(); assertEquals("arg2", "foo'bar", ((Value)values.get(0)).getCompleteValue() ); nv = node.getParam("arg3"); values = nv.getValues(); assertEquals("arg3", "", ((Value)values.get(0)).getCompleteValue() ); nv = node.getParam("arg4"); values = nv.getValues(); assertEquals("arg4", "", ((Value)values.get(0)).getCompleteValue() ); nv = node.getParam("executable"); values = nv.getValues(); assertEquals("executable", "/bin/echo", ((Value)values.get(0)).getCompleteValue() ); nv = node.getParam("arguments"); values = nv.getValues(); assertEquals("arguments", "mis", ((Value)values.get(0)).getCompleteValue() ); } } JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/rsl/tests/RslAttributesTest.java000066400000000000000000000123711241116057200317560ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl.tests; import org.globus.rsl.*; import java.util.*; import java.io.*; import junit.framework.*; import junit.extensions.*; public class RslAttributesTest extends TestCase { protected RslAttributes attribs; public RslAttributesTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(RslAttributesTest.class); } public void setUp() { String rsl = "&(rsl_substitution=(HOME /home/gawor)(VAR2 testValue))(exECutable=/bin/ls)(arGUments=-arg1 -arg2 \"-arg3 with space\" \"'arg4 in quotes'\")(directory=/home/vijay/gram)(stdin=https://localhost:9999/test)(environment=(v1 value1/$(JAREK)/value2 ) (v2 $(GLOBUS)) (v3 $(HOME)/data # /bin))"; try { attribs = new RslAttributes(rsl); } catch(Exception e) { fail("Failed to parse rsl"); } } public void testParse() { assertEquals("executable", "/bin/ls", attribs.getSingle("executable")); assertEquals("directory", "/home/vijay/gram", attribs.getSingle("directory")); assertEquals("stdin", "https://localhost:9999/test", attribs.getSingle("stdin")); assertEquals("stdout", null, attribs.getSingle("stdout")); List args = attribs.getMulti("arguments"); assertEquals("arg size", 4, args.size()); assertEquals("arg 1", "-arg1", args.get(0)); assertEquals("arg 2", "-arg2", args.get(1)); assertEquals("arg 3", "-arg3 with space", args.get(2)); assertEquals("arg 4", "'arg4 in quotes'", args.get(3)); Map envs = attribs.getMap("environment"); assertEquals("env size", 3, envs.size()); assertEquals("env1", "value1/$(JAREK)/value2", envs.get("v1")); assertEquals("env2", "$(GLOBUS)", envs.get("v2")); assertEquals("env3", "$(HOME)/data/bin", envs.get("v3")); Map vars = attribs.getVariables("rsl_substitution"); assertEquals("var name 1", true, vars.containsKey("HOME")); assertEquals("var name 2", true, vars.containsKey("VAR2")); assertEquals("var name 3", false, vars.containsKey("home")); assertEquals("var value 1", "/home/gawor", vars.get("HOME")); assertEquals("var value 2", "testValue", vars.get("VAR2")); } public void testModify() { attribs.set("executabLE", "/home/gawor/ls"); assertEquals("executable", "/home/gawor/ls", attribs.getSingle("executable")); attribs.set("stdout", "http://goshen.mcs.anl.gov:2222:/kkkk"); assertEquals("stdout", "http://goshen.mcs.anl.gov:2222:/kkkk", attribs.getSingle("stdOUT")); // modify arg list assertEquals("delete arg1", true, attribs.remove("arguments", "-arg2") ); assertEquals("delete arg2", false, attribs.remove("arguments", "-noarg") ); attribs.add("arguments", "test arg"); // check arg list List args = attribs.getMulti("arguments"); assertEquals("arg size", 4, args.size()); assertEquals("arg 1", "-arg1", args.get(0)); assertEquals("arg 2", "-arg3 with space", args.get(1)); assertEquals("arg 3", "'arg4 in quotes'", args.get(2)); assertEquals("arg 4", "test arg", args.get(3)); // modify env assertEquals("delete env1", true, attribs.removeMap("environment", "v2") ); assertEquals("delete env2", false, attribs.removeMap("environment", "v8") ); attribs.addMulti("environment", new String [] {"v5", "value5"}); // check env Map envs = attribs.getMap("environment"); assertEquals("env size", 3, envs.size()); assertEquals("env1", "value1/$(JAREK)/value2", envs.get("v1")); assertEquals("env2", "$(HOME)/data/bin", envs.get("v3")); assertEquals("env3", "value5", envs.get("v5")); // modify variables assertEquals("var remove", false, attribs.removeVariable("rsl_substitution", "VAR1")); assertEquals("var remove", true, attribs.removeVariable("rsl_substitution", "VAR2")); attribs.addVariable("rsl_substitution", "VAR3", "variable3"); // check variables Map vars = attribs.getVariables("rsl_substitution"); assertEquals("var name 1", true, vars.containsKey("HOME")); assertEquals("var name 2", false, vars.containsKey("VAR2")); assertEquals("var name 3", true, vars.containsKey("VAR3")); assertEquals("var value 1", "/home/gawor", vars.get("HOME")); assertEquals("var value 2", "variable3", vars.get("VAR3")); System.out.println( attribs.toRSL() ); } } JGlobus-JGlobus-Release-2.1.0/gram/src/test/java/org/globus/rsl/tests/RslNodeTest.java000066400000000000000000000250641241116057200305200ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.rsl.tests; import org.globus.rsl.*; import java.util.*; import java.io.*; import junit.framework.*; import junit.extensions.*; public class RslNodeTest extends TestCase { protected RslNode rslTree; public RslNodeTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(RslNodeTest.class); } public void setUp() { String rsl = "&(exECutable=/bin/ls)(arGUments=-arg1 -arg2 \" -arg3 \")(directory=/home/vijay/gram)(stdin=https://localhost:9999/test)(environment=(v1 value1/$(JAREK)/value2 ) (v2 $(GLOBUS)) (v3 $(HOME)/data # /bin))"; try { rslTree = RSLParser.parse(rsl); } catch(Exception e) { fail("Failed to parse rsl"); } } public void testMerge() { RslNode node = null; String rsl2 = "&(rslSubSTitution=(var1 value1))(arguments=\" -end\")(stdout=stdout.file)"; try { node = RSLParser.parse(rsl2); } catch(Exception e) { fail("Failed to parse rsl"); } // merge the rsl rslTree.merge(node); NameOpValue nv = null; List values; nv = rslTree.getParam("ARGUMENTS"); values = nv.getValues(); assertEquals("arg size", 4, values.size()); assertEquals("arg 1", "-arg1", ((Value)values.get(0)).getValue() ); assertEquals("arg 2", "-arg2", ((Value)values.get(1)).getValue() ); assertEquals("arg 3", " -arg3 ", ((Value)values.get(2)).getValue() ); assertEquals("arg 4", " -end", ((Value)values.get(3)).getValue() ); nv = rslTree.getParam("stdout"); values = nv.getValues(); assertEquals("stdout size", 1, values.size()); assertEquals("stdout value", "stdout.file", ((Value)values.get(0)).getValue() ); Bindings db = rslTree.getBindings("rsl_substitutION"); assertTrue("bindings null", (db != null)); values = db.getValues(); assertEquals("rslsubsitution size", 1, values.size() ); assertEquals("rslsub variable", "var1", ((Binding)values.get(0)).getName()); assertEquals("rslsub variable value", "value1", ((Binding)values.get(0)).getValue().getValue()); System.out.println("the final rsl:" + rslTree); } public void testCreate() { RslNode rslTree = new RslNode(RslNode.AND); Bindings bindings = null; NameOpValue nv = null; List values = null; rslTree.put(new NameOpValue("executable", NameOpValue.EQ, "/usr/local/bin/ls")); rslTree.put(new NameOpValue("executable", NameOpValue.EQ, "/bin/ls")); rslTree.put(new NameOpValue("myMemory", NameOpValue.LTEQ, "5")); rslTree.put(new NameOpValue("arguments", NameOpValue.EQ, new String [] {"-l", "-p", " -o "})); bindings = new Bindings("rsl_substitution"); bindings.add(new Binding("var1", "value1")); bindings.add(new Binding("var2", "value2")); bindings.add(new Binding("var3", "value3")); rslTree.put(bindings); // test stuff nv = rslTree.getParam("ARGUMENTS"); values = nv.getValues(); assertEquals("arg size", 3, values.size()); assertEquals("arg 1", "-l", ((Value)values.get(0)).getValue() ); assertEquals("arg 2", "-p", ((Value)values.get(1)).getValue() ); assertEquals("arg 3", " -o ", ((Value)values.get(2)).getValue() ); // remove some args... assertEquals("remove arg", false, nv.remove(new Value("-p "))); assertEquals("remove arg2", true, nv.remove(new Value("-p"))); // test the args again... assertEquals("arg size", 2, values.size()); assertEquals("arg 1", "-l", ((Value)values.get(0)).getValue() ); assertEquals("arg 2", " -o ", ((Value)values.get(1)).getValue() ); // test the executable.. nv = rslTree.getParam("EXECUTABLE"); assertEquals("executable", "/bin/ls", ((Value)nv.getFirstValue()).getValue() ); nv = rslTree.getParam("MY_MEMORY"); assertEquals("myMemory", "5", ((Value)nv.getFirstValue()).getValue() ); assertEquals("myMemory operator", NameOpValue.LTEQ, nv.getOperator()); // test bindings bindings = rslTree.getBindings("rslSUBstitution"); assertTrue("bindings null", (bindings != null)); values = bindings.getValues(); assertEquals("bind size", 3, values.size()); assertEquals("bind 1", "var1", ((Binding)values.get(0)).getName() ); assertEquals("bind 2", "var2", ((Binding)values.get(1)).getName() ); assertEquals("bind 3", "var3", ((Binding)values.get(2)).getName() ); } public void testRemove() { RslNode node = null; String rsl2 = "&(\"rsl_SubSTitution\"=(var1 value1))(arguments=\" -end\")(stdout=stdout.file)(stdout=ptys)"; try { node = RSLParser.parse(rsl2); } catch(Exception e) { fail("Failed to parse rsl"); } NameOpValue nv = null; Bindings bindings = null; List values; nv = node.removeParam("stdout"); values = nv.getValues(); assertEquals("stdout", "ptys", ((Value)values.get(0)).getValue() ); assertEquals("stdout", null, node.removeParam("stdout")); bindings = node.removeBindings("rslsubstitutION"); values = bindings.getValues(); assertEquals("rsl subst.", "var1", ((Binding)values.get(0)).getName() ); assertEquals("rsl subst.", null, node.removeBindings("rsl_substiTution")); } public void testEvaluate() { String rsl = " + " + "(& " + "(directory = $(TOPDIR))" + "(executable = $(VAR1))" + ")" + "(&" + "(rsl_substitution = (TOPDIR \"/home/nobody\")" + "(DATADIR $(TOPDIR)\"/data\") " + "(EXECDIR $(TOPDIR)/bin) )" + "(executable = $(EXECDIR)/a # .out" + "(* ^-- implicit concatenation *))" + "(directory = $(TOPDIR) )" + "(arguments = $(DATADIR)/file1\n" + "(* ^-- implicit concatenation *)" + "$(DATADIR) # /file2\n" + "(* ^-- explicit concatenation *)" + "'$(FOO)' (* <-- a quoted literal *))" + "(environment = (DATADIR $(DATADIR)))" + "(count = 1)" + ")"; RslNode tree = null; try { tree = RSLParser.parse(rsl); } catch(Exception e) { fail("Rsl failed to parse!"); } System.out.println( tree.toRSL(true) ); // null is the symbol table Properties p = new Properties(); p.put("VAR1", "testValue1"); p.put("TOPDIR", "/home/gawor"); AbstractRslNode finalRsl = null; try { finalRsl = tree.evaluate(p); } catch (RslEvaluationException e) { fail("failed to evaluate rsl!"); } System.out.println(); System.out.println( finalRsl.toRSL(true) ); NameOpValue nv = null; List values = null; List specs = finalRsl.getSpecifications(); // this should be the first one... finalRsl = (RslNode)specs.get(0); assertTrue("rsl node 0 null", (finalRsl != null)); nv = finalRsl.getParam("executable"); values = nv.getValues(); assertEquals("executable", "testValue1", ((Value)values.get(0)).getValue()); nv = finalRsl.getParam("directory"); values = nv.getValues(); assertEquals("directory", "/home/gawor", ((Value)values.get(0)).getValue()); // this should be the second one... finalRsl = (RslNode)specs.get(1); assertTrue("rsl node 1 null", (finalRsl != null)); nv = finalRsl.getParam("executable"); values = nv.getValues(); assertEquals("executable", "/home/nobody/bin/a.out", ((Value)values.get(0)).getValue()); nv = finalRsl.getParam("directory"); values = nv.getValues(); assertEquals("directory", "/home/nobody", ((Value)values.get(0)).getValue()); nv = finalRsl.getParam("arguments"); values = nv.getValues(); assertEquals("arg1", "/home/nobody/data/file1", ((Value)values.get(0)).getValue()); assertEquals("arg2", "/home/nobody/data/file2", ((Value)values.get(1)).getValue()); assertEquals("arg3", "$(FOO)", ((Value)values.get(2)).getValue()); nv = finalRsl.getParam("environment"); values = nv.getValues(); values = (List)values.get(0); assertEquals("env name", "DATADIR", ((Value)values.get(0)).getValue()); assertEquals("env value", "/home/nobody/data", ((Value)values.get(1)).getValue()); Bindings bindings = finalRsl.getBindings("rsl_substitution"); assertTrue("bindings null", (bindings != null)); values = bindings.getValues(); assertEquals("bind1: name", "TOPDIR", ((Binding)values.get(0)).getName()); assertEquals("bind1: value", "/home/nobody", ((Binding)values.get(0)).getValue().getValue()); assertEquals("bind2: name", "DATADIR", ((Binding)values.get(1)).getName()); assertEquals("bind2: value", "/home/nobody/data", ((Binding)values.get(1)).getValue().getValue()); assertEquals("bind3: name", "EXECDIR", ((Binding)values.get(2)).getName()); assertEquals("bind3: value", "/home/nobody/bin", ((Binding)values.get(2)).getValue().getValue()); } } JGlobus-JGlobus-Release-2.1.0/gridftp/000077500000000000000000000000001241116057200174365ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/pom.xml000066400000000000000000000013451241116057200207560ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 gridftp gridftp ${project.groupId} gss ${project.version} junit junit test JGlobus-JGlobus-Release-2.1.0/gridftp/src/000077500000000000000000000000001241116057200202255ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/000077500000000000000000000000001241116057200211515ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/000077500000000000000000000000001241116057200220725ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/000077500000000000000000000000001241116057200226615ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/000077500000000000000000000000001241116057200241545ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/000077500000000000000000000000001241116057200247455ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/Buffer.java000066400000000000000000000037031241116057200270240ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** Represents a chunk of data cut out of a larger data volume. Buffer is characterized by offset at which it belongs to the larger data volume, and length. The internal data array always starts at 0 and ends at (length -1). Its indexing has nothing to do with offset. **/ public class Buffer { protected byte[] buf; protected int length; protected long offset; /** * @param buf the data buffer (always starts at 0) * @param length length of the data in the buffer */ public Buffer(byte [] buf, int length) { this(buf, length, -1); } /** * @param buf the data buffer (always starts at 0) * @param length length of the data in the buffer * @param offset offset of the data the buffer was read from. * */ public Buffer(byte [] buf, int length, long offset) { this.buf = buf; this.length = length; this.offset = offset; } public byte[] getBuffer() { return buf; } public int getLength() { return length; } /** * Returns offset of the data the buffer was read from. * Value -1 indicates that offset is not supported. * For instance, this will happen if the buffer represents * a chunk of data read off the data channel in the stream * mode. * */ public long getOffset() { return offset; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/ByteRange.java000066400000000000000000000105021241116057200274660ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** Represents a range of integers. The name reflects the fact that it is used with FTP extended mode restart markers, where it represents a range of transfered bytes. **/ public class ByteRange { /** lower range limit **/ public long from; /** upper range limit **/ public long to; /** @param from lower range limit @param to upper range limit @throws IllegalArgumentException if to < from **/ public ByteRange(long from, long to) { if (to < from) { throw new IllegalArgumentException( "Range upper boundary smaller than lower boundary"); } this.from = from; this.to = to; } /** @return true if both object logically represent the same range (even if they are two separate ByteRange instances) **/ public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof ByteRange) { ByteRange otherObj = (ByteRange)other; return ( this.to == otherObj.to && this.from == otherObj.from); } else { return false; } } public int hashCode() { return (int)(this.to + this.from); } /** copying constructor */ public ByteRange(ByteRange src) { this.copy(src); } private void copy(ByteRange other) { this.from = other.from; this.to = other.to; } public static final int THIS_BELOW = 1; public static final int ADJACENT = 2; public static final int THIS_SUPERSET = 3; public static final int THIS_SUBSET = 4; public static final int THIS_ABOVE = 5; /** If this range can be consolidated with the other one, modify this range so that it represents the result of merging this and the other range. The parameter object remains intact. Return value indicates what operation has been performed.
  • If the two ranges were separate, then this range will remain unchanged. The return value will be THIS_BELOW if this range is below the other range, or THIS_ABOVE in the other case.
  • If this range was a superset of the other, then this range remains unchanged and THIS_SUPERSET will be returned. A special case of this situation is when both ranges were equal.
  • If other range was a superset of this, OTHER_SUPERSET will be returned.
  • Otherwise ADJACENT is returned, meaning that merge was possible but no range is a superset of the other.
Note that two ranges are considered separate if there is at least one integer between them. For instance, "1-3" and "5-7" are separate but "1-3" and "4-7" are adjacent because merge is possible. **/ public int merge(final ByteRange other) { /* notation: t = this range o = other range - = the common subset of both Thus there are 13 cases: o t ot o-t o- o-o -t - -o t-t t- t-o to t o */ if (other.from < this.from) { if (other.to + 1 < this.from) { // o t return THIS_ABOVE; } this.from = other.from; if (this.to <= other.to) { // o- // o-o this.to = other.to; return THIS_SUBSET; } // ot // o-t } else { if (this.to + 1 < other.from) { // t o return THIS_BELOW; } if ( other.to <= this.to) { // -t // - // t-t // t- return THIS_SUPERSET; } this.to = other.to; if ( other.from == this.from) { // -o return THIS_SUBSET; } // t- //to } return ADJACENT; } public String toString() { return Long.toString(from) + "-" + Long.toString(to); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/ByteRangeList.java000066400000000000000000000135751241116057200303370ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Represents list of ranges of integers (ByteRange objects). The name reflects the fact that in FTP extended mode restart markers, such structure represent a list of ranges of transfered bytes. The list has following characteristic:
  • no ranges from the list are adjacent nor have any common subset. In other words, for any two list members, r1.merge(r2) always returns ByteRange.THIS_ABOVE or ByteRange.THIS_BELOW
  • ranges in the list are ordered by the value of "from" field (or "to" field; it's the same)
You cannot just add new ranges to the list, because that would violate the contract above. New ranges can be merge()d to the list. @see GridFTPRestartMarker **/ public class ByteRangeList implements RestartData { private static Log logger = LogFactory.getLog(ByteRangeList.class.getName()); /** vector of ByteRanges. It is guaranteed that any two ranges are not adjacent to each other, nor have a common subset. They are unordered, however. **/ protected Vector vector; public ByteRangeList() { vector = new Vector(); } /** @return true if this list logically represents the same range list, although the object instances may be different. **/ public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof ByteRangeList) { ByteRangeList otherObj = (ByteRangeList)other; if (this.vector.size() != otherObj.vector.size()) { return false; } for (int i=0; i
  • merge("10-15 30-35", "20-25") -> "10-15 20-25 30-35"
  • merge("10-15 30-35", "12-15") -> "10-15 20-25"
  • merge("10-15 30-35", "16-40") -> "10-40" **/ public void merge(final ByteRange range) { // always use copies of objects ByteRange newRange = new ByteRange(range); logger.debug( this.toFtpCmdArgument() + " + " + newRange.toString()); int oldSize = vector.size(); int index = 0; final int NOT_YET = -1; int merged = NOT_YET; if (oldSize == 0) { vector.add(newRange); return; } for (int i = 0; i < oldSize; i++) { int result = newRange.merge((ByteRange)vector.elementAt(index)); switch (result) { case ByteRange.THIS_ABOVE : //last_below = index; index ++; break; case ByteRange.ADJACENT : case ByteRange.THIS_SUBSET : case ByteRange.THIS_SUPERSET : if (merged == NOT_YET) { vector.remove(index); vector.add(index, newRange); merged = index; index++; } else { vector.remove(index); //do not augment index } break; case ByteRange.THIS_BELOW : if (merged == NOT_YET) { vector.add(index, newRange); } return; } } if (merged == NOT_YET) { vector.add(newRange); } } /** Merge into this list all the ranges contained in the given vector using merge(ByteRange). @param other the Vector of ByteRange objects **/ public void merge(final Vector other) { for(int i =0; i * Note: {@link Buffer#getOffset() buffer.getOffset()} might * return -1 if the transfer mode used does not support * data offsets, for example stream transfer mode. * * @param buffer the data buffer to write. * @throws IOException if an I/O error occurs. */ public void write(Buffer buffer) throws IOException; /** * Closes this data sink and releases any system * resources associated with this sink. * * @throws IOException if an I/O error occurs. */ public void close() throws IOException; } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/DataSinkStream.java000066400000000000000000000034541241116057200304700ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; import java.io.OutputStream; /** Reference implementation of DataSink. It can be used with non-parallel transfers. It cannot be used with Extended Block Mode because it uses implicit assumption that data arrives in correct sequence. It is not thread safe. **/ public class DataSinkStream implements DataSink { protected OutputStream out; protected boolean autoFlush; protected boolean ignoreOffset; protected long offset = 0; public DataSinkStream(OutputStream out) { this(out, false, false); } public DataSinkStream(OutputStream out, boolean autoFlush, boolean ignoreOffset) { this.out = out; this.autoFlush = autoFlush; this.ignoreOffset = ignoreOffset; } public void write(Buffer buffer) throws IOException { long bufOffset = buffer.getOffset(); if (ignoreOffset || bufOffset == -1 || bufOffset == offset) { out.write(buffer.getBuffer(), 0, buffer.getLength()); if (autoFlush) { out.flush(); } offset += buffer.getLength(); } else { throw new IOException("Random offsets not supported."); } } public void close() throws IOException { out.close(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/DataSource.java000066400000000000000000000033131241116057200276420ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; /** * Data channel uses this interface to read outgoing data. * Implement it to provide your own ways of reading data. * It must be thread safe; in parallel transfer mode several * streams may attempt to read. **/ public interface DataSource { /** * Reads a data buffer from this data source. * * @return The data buffer read. Null, if there is * no more data to be read. * @throws IOException if an I/O error occurs. */ public Buffer read() throws IOException; /** * Closes this data source and releases any system * resources associated with this source. * * @throws IOException if an I/O error occurs. */ public void close() throws IOException; /** * Optional operation. Returns the total size, in bytes, of the * data in this source. If the implementation is not able to * provide a total size for the data source, it should return * -1 * * @throws IOException if an I/O exception occurs */ public long totalSize() throws IOException; } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/DataSourceStream.java000066400000000000000000000033451241116057200310230ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; import java.io.InputStream; /** * Reference implementation of DataSource. It can be used with * non-parallel transfers. It cannot be used with Extended Block Mode because * it is not thread safe. **/ public class DataSourceStream implements DataSource { private static final int DEFAULT_BUFFER_SIZE = 16384; protected InputStream in; protected int bufferSize; protected long totalRead = 0; public DataSourceStream(InputStream in) { this(in, DEFAULT_BUFFER_SIZE); } public DataSourceStream(InputStream in, int bufferSize) { this.in = in; this.bufferSize = bufferSize; } public Buffer read() throws IOException { byte [] buf = new byte[bufferSize]; int read = in.read(buf); if (read == -1) { return null; } else { Buffer result = new Buffer(buf, read, totalRead); totalRead += read; return result; } } public void close() throws IOException { in.close(); } public long totalSize() { return -1; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/FTPClient.java000066400000000000000000002405451241116057200274120ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.BufferedReader; import java.io.StringReader; import java.io.File; import java.util.Date; import java.util.StringTokenizer; import java.util.Vector; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.TimeZone; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.text.SimpleDateFormat; import java.text.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.ServerException; import org.globus.ftp.exception.FTPReplyParseException; import org.globus.ftp.exception.UnexpectedReplyCodeException; import org.globus.ftp.exception.FTPException; import org.globus.ftp.vanilla.FTPControlChannel; import org.globus.ftp.vanilla.FTPServerFacade; import org.globus.ftp.vanilla.BasicClientControlChannel; import org.globus.ftp.vanilla.Command; import org.globus.ftp.vanilla.Reply; import org.globus.ftp.vanilla.TransferMonitor; import org.globus.ftp.vanilla.TransferState; /** * This is the main user interface for FTP operations. * Use this class for client - server or third party transfers * that do not require GridFTP extensions. * Consult the manual for general usage. *
    Note: If using with GridFTP servers operations like * {@link #setMode(int) setMode()}, {@link #setType(int) setType()} that * affect data channel settings must be called before passive * or active data channel mode is set. **/ public class FTPClient { private static Log logger = LogFactory.getLog(FTPClient.class.getName()); // represents the state of interaction with remote server protected Session session; protected FTPControlChannel controlChannel; // the local server handles data channels protected FTPServerFacade localServer; /* needed for last modified command */ protected SimpleDateFormat dateFormat = null; protected String username = null; /** * Whether to use ALLO with put()/asyncPut() or not */ protected boolean useAllo; /** * List of the checksum algorithms supported by the server as described in * GridFTP v2 Protocol Description */ protected List algorithms; /* for subclasses */ protected FTPClient() { } /** * Constructs client and connects it to the remote server. * @param host remote server host * @param port remote server port */ public FTPClient(String host, int port) throws IOException, ServerException { session = new Session(); controlChannel = new FTPControlChannel(host, port); controlChannel.open(); localServer = new FTPServerFacade(controlChannel); localServer.authorize(); } /* * @return host */ public String getHost() { return this.controlChannel.getHost(); } /* * @return port */ public int getPort() { return this.controlChannel.getPort(); } /** * Returns the last reply received from the server. This could * be used immediately after the call to the constructor to * get the initial server reply */ public Reply getLastReply() { return this.controlChannel.getLastReply(); } /** * Returns the remote file size. * * @param filename filename get the size for. * @return size of the file. * @exception ServerException if the file does not exist or * an error occured. */ public long getSize(String filename) throws IOException, ServerException { if (filename == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("SIZE", filename); Reply reply = null; try { reply = controlChannel.execute(cmd); return Long.parseLong(reply.getMessage()); } catch (NumberFormatException e) { throw ServerException.embedFTPReplyParseException( new FTPReplyParseException( FTPReplyParseException.MESSAGE_UNPARSABLE, "Could not parse size: " + reply.getMessage())); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } /** * Returns last modification time of the specifed file. * * @param filename filename get the last modification time for. * @return the time and date of the last modification. * @exception ServerException if the file does not exist or * an error occured. */ public Date getLastModified(String filename) throws IOException, ServerException { if (filename == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("MDTM", filename); Reply reply = null; try { reply = controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused changing transfer mode"); } if (dateFormat == null) { dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } try { return dateFormat.parse(reply.getMessage()); } catch (ParseException e) { throw ServerException.embedFTPReplyParseException( new FTPReplyParseException( 0, "Invalid file modification time reply: " + reply)); } } /** * Checks if given file/directory exists on the server. * * @param filename * file or directory name * @return true if the file exists, false otherwise. */ public boolean exists(String filename) throws IOException, ServerException { if (filename == null) { throw new IllegalArgumentException("Required argument missing"); } try { Reply reply = controlChannel.exchange(new Command("RNFR", filename)); if (Reply.isPositiveIntermediate(reply)) { controlChannel.execute(new Command("ABOR")); return true; } else { return false; } } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Abort failed"); } } /** * Changes the remote current working directory. */ public void changeDir(String dir) throws IOException, ServerException { if (dir == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("CWD", dir); try { controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused changing directory"); } } /** * Deletes the remote directory. */ public void deleteDir(String dir) throws IOException, ServerException { if (dir == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("RMD", dir); try { controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused deleting directory"); } } /** * Deletes the remote file. */ public void deleteFile(String filename) throws IOException, ServerException { if (filename == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("DELE", filename); try { controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused deleting file"); } } /** * Creates remote directory. */ public void makeDir(String dir) throws IOException, ServerException { if (dir == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("MKD", dir); try { controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused creating directory"); } } /** * Renames remote directory. */ public void rename(String oldName, String newName) throws IOException, ServerException { if (oldName == null || newName == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("RNFR", oldName); try { Reply reply = controlChannel.exchange(cmd); if (!Reply.isPositiveIntermediate(reply)) { throw new UnexpectedReplyCodeException(reply); } controlChannel.execute(new Command("RNTO", newName)); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused renaming file"); } } /** * Returns remote current working directory. * @return remote current working directory. */ public String getCurrentDir() throws IOException, ServerException { Reply reply = null; try { reply = controlChannel.execute(Command.PWD); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused returning current directory"); } String strReply = reply.getMessage(); if (strReply.length() > 0 && strReply.charAt(0) == '"') { return strReply.substring(1, strReply.indexOf('"', 1)); } else { throw ServerException.embedFTPReplyParseException( new FTPReplyParseException( 0, "Cannot parse 'PWD' reply: " + reply)); } } /** * Changes remote current working directory to the higher level. */ public void goUpDir() throws IOException, ServerException { try { controlChannel.execute(Command.CDUP); // alternative: changeDir(".."); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused changing current directory"); } } private class ByteArrayDataSink implements DataSink { private ByteArrayOutputStream received; public ByteArrayDataSink() { this.received = new ByteArrayOutputStream(1000); } public void write(Buffer buffer) throws IOException { if (logger.isDebugEnabled()) { logger.debug( "received " + buffer.getLength() + " bytes of directory listing"); } this.received.write(buffer.getBuffer(), 0, buffer.getLength()); } public void close() throws IOException { } public ByteArrayOutputStream getData() { return this.received; } } /** * Performs remote directory listing. Sends 'LIST -d *' command. * *
    Note: * This function can only parse Unix ls -d like output. Please * note that the LIST output is unspecified in the FTP standard and * each server might return slightly different output causing the * parsing to fail. * Also, if the ftp server does not accept -d option or support * wildcards, this method might fail. For example, this command will * fail on GridFTP server distributed with GT 4.0.0. * It is strongly recommended to use {@link #mlsd() mlsd()} * function instead. * * @return Vector list of {@link FileInfo FileInfo} objects, representing * remote files * @see #mlsd() */ public Vector list() throws ServerException, ClientException, IOException { return list("*"); } /** * Performs remote directory listing with the specified filter. * Sends 'LIST -d <filter>' command. * *
    Note: * This function can only parse Unix ls -d like output. Please * note that the LIST output is unspecified in the FTP standard and * each server might return slightly different output causing the * parsing to fail. * Also, if the ftp server does not accept -d option or support * wildcards, this method might fail. For example, this command will * fail on GridFTP server distributed with GT 4.0.0. * It is strongly recommended to use {@link #mlsd(String) mlsd()} * function instead. * * @param filter "*" for example, can be null. * @return Vector list of {@link FileInfo FileInfo} objects, representing * remote files * @see #mlsd(String) */ public Vector list(String filter) throws ServerException, ClientException, IOException { return list(filter, "-d"); } /** * Performs remote directory listing with the specified filter and * modifier. Sends 'LIST <modifier> <filter>' command. * *
    Note: * This function can only parse Unix ls -d like output. Please * note that the LIST output is unspecified in the FTP standard and * each server might return slightly different output causing the * parsing to fail. * Also, please keep in mind that the ftp server might not * recognize or support all the different modifiers or filters. * In fact, some servers such as GridFTP server distributed with * GT 4.0.0 does not support any modifiers or filters * (strict RFC 959 compliance). * It is strongly recommended to use {@link #mlsd(String) mlsd()} * function instead. * * @param filter "*" for example, can be null. * @param modifier "-d" for example, can be null. * @return Vector list of {@link FileInfo FileInfo} objects, representing * remote files * @see #mlsd(String) */ public Vector list(String filter, String modifier) throws ServerException, ClientException, IOException { ByteArrayDataSink sink = new ByteArrayDataSink(); list(filter, modifier, sink); ByteArrayOutputStream received = sink.getData(); // transfer done. Data is in received stream. // convert it to a vector. BufferedReader reader = new BufferedReader(new StringReader(received.toString())); Vector fileList = new Vector(); FileInfo fileInfo = null; String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (logger.isDebugEnabled()) { logger.debug("line ->" + line); } if(line.equals("")) { continue; } if (line.startsWith("total")) continue; try { fileInfo = new FileInfo(line); } catch (FTPException e) { ClientException ce = new ClientException( ClientException.UNSPECIFIED, "Could not create FileInfo"); ce.setRootCause(e); throw ce; } fileList.addElement(fileInfo); } return fileList; } /** * Performs directory listing and writes the result * to the supplied data sink. * This method is allowed in ASCII mode only. * *
    Note: * Please keep in mind that the ftp server might not * recognize or support all the different modifiers or filters. * In fact, some servers such as GridFTP server distributed with * GT 4.0.0 does not support any modifiers or filters * (strict RFC 959 compliance). * It is strongly recommended to use {@link #mlsd(String,DataSink) * mlsd()} function instead. * * @param filter remote list command file filter, eg. "*" * @param modifier remote list command modifier, eg. "-d" * @param sink data destination **/ public void list(String filter, String modifier, DataSink sink) throws ServerException, ClientException, IOException { String arg = null; if (modifier != null) { arg = modifier; } if (filter != null) { arg = (arg == null) ? filter : arg + " " + filter; } Command cmd = new Command("LIST", arg); performTransfer(cmd, sink); } /** * Performs remote directory listing of the current directory. * Sends 'NLST' command. * * @return Vector list of {@link FileInfo FileInfo} objects, representing * remote files */ public Vector nlist() throws ServerException, ClientException, IOException { return nlist(null); } /** * Performs remote directory listing on the given path. * Sends 'NLST <path>' command. * * @param path directory to perform listing of. If null, listing * of current directory will be performed. * @return Vector list of {@link FileInfo FileInfo} objects, representing * remote files */ public Vector nlist(String path) throws ServerException, ClientException, IOException { ByteArrayDataSink sink = new ByteArrayDataSink(); nlist(path, sink); ByteArrayOutputStream received = sink.getData(); // transfer done. Data is in received stream. // convert it to a vector. BufferedReader reader = new BufferedReader(new StringReader(received.toString())); Vector fileList = new Vector(); FileInfo fileInfo = null; String line = null; while ((line = reader.readLine()) != null) { if (logger.isDebugEnabled()) { logger.debug("line ->" + line); } fileInfo = new FileInfo(); fileInfo.setName(line); fileInfo.setFileType(FileInfo.UNKNOWN_TYPE); fileList.addElement(fileInfo); } return fileList; } /** * Performs remote directory listing on the given path. * Sends 'NLST <path>' command. * * @param path directory to perform listing of. If null, listing * of current directory will be performed. * @param sink sink to which the listing data will be written. */ public void nlist(String path, DataSink sink) throws ServerException, ClientException, IOException { Command cmd = (path == null) ? new Command("NLST") : new Command("NLST", path); performTransfer(cmd, sink); } /** * Get info of a certain remote file in Mlsx format. */ public MlsxEntry mlst(String fileName) throws IOException, ServerException { try { Reply reply = controlChannel.execute(new Command("MLST", fileName)); String replyMessage = reply.getMessage(); StringTokenizer replyLines = new StringTokenizer( replyMessage, System.getProperty("line.separator")); if (replyLines.hasMoreElements()) { replyLines.nextElement(); } else { throw new FTPException(FTPException.UNSPECIFIED, "Expected multiline reply"); } if (replyLines.hasMoreElements()) { String line = (String) replyLines.nextElement(); return new MlsxEntry(line); } else { throw new FTPException(FTPException.UNSPECIFIED, "Expected multiline reply"); } } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused MLST command"); } catch (FTPException e) { ServerException ce = new ServerException( ClientException.UNSPECIFIED, "Could not create MlsxEntry"); ce.setRootCause(e); throw ce; } } /** * Performs remote directory listing of the current directory. * Sends 'MLSD' command. * * @return Vector list of {@link MlsxEntry MlsxEntry} objects, representing * remote files */ public Vector mlsd() throws ServerException, ClientException, IOException { return mlsd(null); } /** * Performs remote directory listing on the given path. * Sends 'MLSD <path>' command. * * @param path directory to perform listing of. If null, listing * of current directory will be performed. * @return Vector list of {@link MlsxEntry MlsxEntry} objects, representing * remote files */ public Vector mlsd(String path) throws ServerException, ClientException, IOException { ByteArrayDataSink sink = new ByteArrayDataSink(); mlsd(path, sink); ByteArrayOutputStream received = sink.getData(); // transfer done. Data is in received stream. // convert it to a vector. BufferedReader reader = new BufferedReader(new StringReader(received.toString())); Vector fileList = new Vector(); MlsxEntry entry = null; String line = null; while ((line = reader.readLine()) != null) { if (logger.isDebugEnabled()) { logger.debug("line ->" + line); } try { entry = new MlsxEntry(line); } catch (FTPException e) { ClientException ce = new ClientException( ClientException.UNSPECIFIED, "Could not create MlsxEntry"); ce.setRootCause(e); throw ce; } fileList.addElement(entry); } return fileList; } /** * Performs remote directory listing on the given path. * Sends 'MLSD <path>' command. * * @param path directory to perform listing of. If null, listing * of current directory will be performed. * @param sink sink to which the listing data will be written. */ public void mlsd(String path, DataSink sink) throws ServerException, ClientException, IOException { Command cmd = (path == null) ? new Command("MLSD") : new Command("MLSD", path); performTransfer(cmd, sink); } /** * check performed at the beginning of list() **/ protected void listCheck() throws ClientException { if (session.transferType != Session.TYPE_ASCII) { throw new ClientException( ClientException.BAD_MODE, "list requires ASCII type"); } } protected void checkTransferParamsGet() throws ServerException, IOException, ClientException { checkTransferParams(); } protected void checkTransferParamsPut() throws ServerException, IOException, ClientException { checkTransferParams(); } protected void checkTransferParams() throws ServerException, IOException, ClientException { Session localSession = localServer.getSession(); session.matches(localSession); // if transfer modes have not been defined, // set this (dest) as active if (session.serverMode == Session.SERVER_DEFAULT) { // resulting HostPort stored in session setPassive(); // HostPort read from session setLocalActive(); } } protected void performTransfer(Command cmd, DataSink sink) throws ServerException, ClientException, IOException { listCheck(); checkTransferParamsGet(); controlChannel.write(cmd); localServer.store(sink); transferRunSingleThread(localServer.getControlChannel(), null); } /** Sets transfer type. * @param type should be {@link Session#TYPE_IMAGE TYPE_IMAGE}, * {@link Session#TYPE_ASCII TYPE_ASCII}, * {@link Session#TYPE_LOCAL TYPE_LOCAL}, * {@link Session#TYPE_EBCDIC TYPE_EBCDIC} **/ public void setType(int type) throws IOException, ServerException { localServer.setTransferType(type); String typeStr = null; switch (type) { case Session.TYPE_IMAGE : typeStr = "I"; break; case Session.TYPE_ASCII : typeStr = "A"; break; case Session.TYPE_LOCAL : typeStr = "E"; break; case Session.TYPE_EBCDIC : typeStr = "L"; break; default : throw new IllegalArgumentException("Bad type: " + type); } Command cmd = new Command("TYPE", typeStr); try { controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused changing transfer mode"); } this.session.transferType = type; } protected String getModeStr(int mode) { switch (mode) { case Session.MODE_STREAM : return "S"; case Session.MODE_BLOCK : return "B"; default : throw new IllegalArgumentException("Bad mode: " + mode); } } /** * Sets transfer mode. * @param mode should be {@link Session#MODE_STREAM MODE_STREAM}, * {@link Session#MODE_BLOCK MODE_BLOCK} **/ public void setMode(int mode) throws IOException, ServerException { actualSetMode(mode, getModeStr(mode)); } protected void actualSetMode(int mode, String modeStr) throws IOException, ServerException { localServer.setTransferMode(mode); Command cmd = new Command("MODE", modeStr); try { controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused changing transfer mode"); } this.session.transferMode = mode; } /** Sets protection buffer size (defined in RFC 2228) * @param size the size of buffer */ public void setProtectionBufferSize(int size) throws IOException, ServerException { if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } localServer.setProtectionBufferSize(size); try { Command cmd = new Command("PBSZ", Integer.toString(size)); controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused setting protection buffer size"); } this.session.protectionBufferSize = size; } /** Aborts the current transfer. FTPClient is not thread safe so be careful with using this procedure, which will typically happen in multi threaded environment. Especially during client-server two party transfer, calling abort() may result with exceptions being thrown in the thread that currently perform the transfer. **/ public void abort() throws IOException, ServerException { // TODO: This might need to be reimplemented to support // sending out of bounds urgent TCP messages try { controlChannel.execute(Command.ABOR); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused changing transfer mode"); } finally { localServer.abort(); } } /** Closes connection. Sends QUIT command and closes connection * even if the server reply was not positive. Also, closes * the local server. This function will block until the server * sends a reply to the QUIT command. **/ public void close() throws IOException, ServerException { close(false); } /** Closes connection. Sends QUIT and closes connection * even if the server reply was not positive. Also, closes * the local server. * * @param ignoreQuitReply if true the QUIT command * will be sent but the client will not wait for the * server's reply. If false, the client will block * for the server's reply. **/ public void close(boolean ignoreQuitReply) throws IOException, ServerException { try { if (ignoreQuitReply) { controlChannel.write(Command.QUIT); } else { controlChannel.execute(Command.QUIT); } } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused closing"); } finally { try { controlChannel.close(); } finally { localServer.close(); } } } /** * Returns true if the given feature is supported by remote server, * false otherwise. * * @return true if the given feature is supported by remote server, * false otherwise. */ public boolean isFeatureSupported(String feature) throws IOException, ServerException { return getFeatureList().contains(feature); } /** * Returns list of features supported by remote server. * @return list of features supported by remote server. */ public FeatureList getFeatureList() throws IOException, ServerException { if (this.session.featureList != null) { return this.session.featureList; } // TODO: this can also be optimized. Instead of parsing the // reply after it is reveiced, we can parse it as it is // received. Reply featReply = null; try { featReply = controlChannel.execute(Command.FEAT); if (featReply.getCode() != 211) { throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(featReply), "Server refused returning features"); } } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused returning features"); } this.session.featureList = new FeatureList(featReply.getMessage()); return session.featureList; } /** * Sets remote server to passive server mode. * @return the address at which the server is listening. */ public HostPort setPassive() throws IOException, ServerException { Reply reply = null; try { reply = controlChannel.execute( (controlChannel.isIPv6()) ? Command.EPSV : Command.PASV); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } String pasvReplyMsg = null; pasvReplyMsg = reply.getMessage(); int openBracket = pasvReplyMsg.indexOf("("); int closeBracket = pasvReplyMsg.indexOf(")", openBracket); String bracketContent = pasvReplyMsg.substring(openBracket + 1, closeBracket); this.session.serverMode = Session.SERVER_PASSIVE; HostPort hp = null; if (controlChannel.isIPv6()) { hp = new HostPort6(bracketContent); // since host information might be null // fill it it if (hp.getHost() == null) { ((HostPort6)hp).setVersion(HostPort6.IPv6); ((HostPort6)hp).setHost(controlChannel.getHost()); } } else { hp = new HostPort(bracketContent); } this.session.serverAddress = hp; return hp; } /** * Sets remote server active, telling it to connect to the given * address. * @param hostPort the address to which the server should connect */ public void setActive(HostPort hostPort) throws IOException, ServerException { Command cmd = new Command((controlChannel.isIPv6()) ? "EPRT" : "PORT", hostPort.toFtpCmdArgument()); try { controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } this.session.serverMode = Session.SERVER_ACTIVE; } /** Sets remote server active, telling it to connect to the client. setLocalPassive() must be called beforehand. **/ public void setActive() throws IOException, ServerException, ClientException { Session local = localServer.getSession(); if (local.serverAddress == null) { throw new ClientException(ClientException.CALL_PASSIVE_FIRST); } setActive(local.serverAddress); } /** Starts local server in active server mode. **/ public void setLocalActive() throws ClientException, IOException { if (session.serverAddress == null) { throw new ClientException(ClientException.CALL_PASSIVE_FIRST); } try { localServer.setActive(session.serverAddress); } catch (java.net.UnknownHostException e) { throw new ClientException(ClientException.UNKNOWN_HOST); } } /** Starts local server in passive server mode, with default parameters. In other words, behaves like setLocalPassive(FTPServerFacade.ANY_PORT, FTPServerFacade.DEFAULT_QUEUE) **/ public HostPort setLocalPassive() throws IOException { return localServer.setPassive(); } /** Starts the local server in passive server mode. @param port port at which local server should be listening; can be set to FTPServerFacade.ANY_PORT @param queue max size of queue of awaiting new connection requests @return the server address **/ public HostPort setLocalPassive(int port, int queue) throws IOException { return localServer.setPassive(port, queue); } /** Changes the default client timeout parameters. In the beginning of the transfer, the critical moment is the wait for the initial server reply. If it does not arrive after timeout, client assumes that the transfer could not start for some reason and aborts the operation. Default timeout in miliseconds is Session.DEFAULT_MAX_WAIT. During the waiting period, client polls the control channel once a certain period, which is by default set to Session.DEFAULT_WAIT_DELAY.
    Use this method to change these parameters. @param maxWait timeout in miliseconds @param waitDelay polling period **/ public void setClientWaitParams(int maxWait, int waitDelay) { if (maxWait <= 0 || waitDelay <= 0) { throw new IllegalArgumentException("Parameter is less than 0"); } this.session.maxWait = maxWait; this.session.waitDelay = waitDelay; } /** * Sets the supplied options to the server. */ public void setOptions(Options opts) throws IOException, ServerException { Command cmd = new Command("OPTS", opts.toFtpCmdArgument()); try { controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused setting options"); } localServer.setOptions(opts); } /** * Sets restart parameter of the next transfer. * * @param restartData marker to use * @exception ServerException if the file does not exist or * an error occured. */ public void setRestartMarker(RestartData restartData) throws IOException, ServerException { Command cmd = new Command("REST", restartData.toFtpCmdArgument()); Reply reply = null; try { reply = controlChannel.exchange(cmd); } catch (FTPReplyParseException e) { throw ServerException.embedFTPReplyParseException(e); } if (!Reply.isPositiveIntermediate(reply)) { throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(reply)); } } /** * Performs user authorization with specified * user and password. * * @param user username * @param password user password * @exception ServerException on server refusal */ public void authorize(String user, String password) throws IOException, ServerException { Reply userReply = null; try { userReply = controlChannel.exchange(new Command("USER", user)); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } if (Reply.isPositiveIntermediate(userReply)) { Reply passReply = null; try { passReply = controlChannel.exchange(new Command("PASS", password)); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } if (!Reply.isPositiveCompletion(passReply)) { throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(passReply), "Bad password."); } // i'm logged in } else if (Reply.isPositiveCompletion(userReply)) { // i'm logged in } else { throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(userReply), "Bad user."); } this.session.authorized = true; this.username = user; } public String getUserName() { return this.username; } /** Retrieves the file from the remote server. @param remoteFileName remote file name @param sink sink to which the data will be written @param mListener restart marker listener (currently not used) */ public void get(String remoteFileName, DataSink sink, MarkerListener mListener) throws IOException, ClientException, ServerException { checkTransferParamsGet(); localServer.store(sink); controlChannel.write(new Command("RETR", remoteFileName)); transferRunSingleThread(localServer.getControlChannel(), mListener); } /** Retrieves the file from the remote server. @param remoteFileName remote file name @param sink sink to which the data will be written @param mListener restart marker listener (currently not used) */ public TransferState asynchGet(String remoteFileName, DataSink sink, MarkerListener mListener) throws IOException, ClientException, ServerException { checkTransferParamsGet(); localServer.store(sink); controlChannel.write(new Command("RETR", remoteFileName)); return transferStart(localServer.getControlChannel(), mListener); } /** * Stores file at the remote server. * @param remoteFileName remote file name * @param source data will be read from here * @param mListener restart marker listener (currently not used) */ public void put(String remoteFileName, DataSource source, MarkerListener mListener) throws IOException, ServerException, ClientException { put(remoteFileName, source, mListener, false); } /** * Stores file at the remote server. * @param remoteFileName remote file name * @param source data will be read from here * @param mListener restart marker listener (currently not used) * @param append append to the end of file or overwrite */ public void put(String remoteFileName, DataSource source, MarkerListener mListener, boolean append) throws IOException, ServerException, ClientException { checkTransferParamsPut(); if (useAllo && source.totalSize() != -1) { allocate(source.totalSize()); } localServer.retrieve(source); if (append) { controlChannel.write(new Command("APPE", remoteFileName)); } else { controlChannel.write(new Command("STOR", remoteFileName)); } transferRunSingleThread(localServer.getControlChannel(), mListener); } /** * Stores file at the remote server. * @param remoteFileName remote file name * @param source data will be read from here * @param mListener restart marker listener (currently not used) */ public TransferState asynchPut(String remoteFileName, DataSource source, MarkerListener mListener) throws IOException, ServerException, ClientException { return asynchPut(remoteFileName, source, mListener, false); } /** * Stores file at the remote server. * @param remoteFileName remote file name * @param source data will be read from here * @param mListener restart marker listener (currently not used) * @param append append to the end of file or overwrite */ public TransferState asynchPut(String remoteFileName, DataSource source, MarkerListener mListener, boolean append) throws IOException, ServerException, ClientException { checkTransferParamsPut(); if (useAllo && source.totalSize() != -1) { allocate(source.totalSize()); } localServer.retrieve(source); if (append) { controlChannel.write(new Command("APPE", remoteFileName)); } else { controlChannel.write(new Command("STOR", remoteFileName)); } return transferStart(localServer.getControlChannel(), mListener); } /** * Performs third-party transfer between two servers. * * @param remoteSrcFile source filename * @param destination another client connected to destination server * @param remoteDstFile destination filename * @param append enables append mode; if true, * data will be appened to the remote file, otherwise * file will be overwritten. * @param mListener marker listener. * Can be set to null. */ public void transfer(String remoteSrcFile, FTPClient destination, String remoteDstFile, boolean append, MarkerListener mListener) throws IOException, ServerException, ClientException { session.matches(destination.session); // if transfer modes have not been defined, // set this (source) as active if (session.serverMode == Session.SERVER_DEFAULT) { HostPort hp = destination.setPassive(); setActive(hp); } destination.controlChannel.write( new Command((append) ? "APPE" : "STOR", remoteDstFile)); controlChannel.write(new Command("RETR", remoteSrcFile)); transferRunSingleThread(destination.controlChannel, mListener); } /** Actual transfer management. Transfer is controlled by two new threads listening to the two servers. **/ protected void transferRun(BasicClientControlChannel other, MarkerListener mListener) throws IOException, ServerException, ClientException { TransferState transferState = transferBegin(other, mListener); transferWait(transferState); } protected TransferState transferBegin(BasicClientControlChannel other, MarkerListener mListener) { // this structure will contain up to date information // about the state of transfer at both sides TransferState transferState = new TransferState(); // thread monitoring our server during transfer // (that is, the server associated with this FTPClient) TransferMonitor ourMonitor = new TransferMonitor( controlChannel, transferState, mListener, session.maxWait, session.waitDelay, TransferMonitor.LOCAL); // thread monitoring other server during transfer // (that is, the server associated with the other FTPClient) TransferMonitor otherMonitor = new TransferMonitor( other, transferState, mListener, session.maxWait, session.waitDelay, TransferMonitor.REMOTE); ourMonitor.setOther(otherMonitor); otherMonitor.setOther(ourMonitor); // start two threads controling the transfer ourMonitor.start(false); otherMonitor.start(false); return transferState; } protected TransferState transferStart(BasicClientControlChannel other, MarkerListener mListener) throws IOException, ServerException, ClientException { TransferState transferState = transferBegin(other, mListener); transferState.waitForStart(); return transferState; } protected void transferWait(TransferState transferState) throws IOException, ServerException, ClientException { transferState.waitForEnd(); } protected void transferRunSingleThread(BasicClientControlChannel other, MarkerListener mListener) throws IOException, ServerException, ClientException { // this structure will contain up to date information // about the state of transfer at both sides TransferState transferState = new TransferState(); // thread monitoring our server during transfer // (that is, the server associated with this FTPClient) TransferMonitor ourMonitor = new TransferMonitor( controlChannel, transferState, mListener, session.maxWait, session.waitDelay, TransferMonitor.LOCAL); // thread monitoring other server during transfer // (that is, the server associated with the other FTPClient) TransferMonitor otherMonitor = new TransferMonitor( other, transferState, mListener, session.maxWait, session.waitDelay, TransferMonitor.REMOTE); ourMonitor.setOther(otherMonitor); otherMonitor.setOther(ourMonitor); // controling the other connection - non-blocking otherMonitor.start(false); // control this connection - blocking ourMonitor.start(true); transferState.waitForEnd(); } /** * Executes arbitrary operation on the server. * *
    Note: This is potentially dangerous operation. * Depending on the command executed it might put the server in a * different state from the state the client is expecting. * * @param command command to execute * @exception IOException in case of I/O error. * @exception ServerException if operation failed. * @return the Reply to the operation. */ public Reply quote(String command) throws IOException, ServerException { Command cmd = new Command(command); return doCommand(cmd); } /** * Executes site-specific operation (using the SITE command). * *
    Note: This is potentially dangerous operation. * Depending on the command executed it might put the server in a * different state from the state the client is expecting. * * @param args parameters for the SITE operation. * @exception IOException in case of I/O error * @exception ServerException if operation failed. * @return the Reply to the operation. */ public Reply site(String args) throws IOException, ServerException { Command cmd = new Command("SITE", args); return doCommand(cmd); } private Reply doCommand(Command cmd) throws IOException, ServerException { try { return controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } /** * Reserve sufficient storage to accommodate the new file to be * transferred. * * @param size the amount of space to reserve * @exception ServerException if an error occured. */ public void allocate(long size) throws IOException, ServerException { Command cmd = new Command("ALLO", String.valueOf(size)); Reply reply = null; try { reply = controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } // basic compatibility API public long size(String filename) throws IOException, ServerException { return getSize(filename); } public Date lastModified(String filename) throws IOException, ServerException { return getLastModified(filename); } public void get(String remoteFileName, File localFile) throws IOException, ClientException, ServerException { DataSink sink = new DataSinkStream(new FileOutputStream(localFile)); get(remoteFileName, sink, null); } public void put(File localFile, String remoteFileName, boolean append) throws IOException, ServerException, ClientException { DataSource source = new DataSourceStream(new FileInputStream(localFile)); put(remoteFileName, source, null, append); } /** * Enables/disables passive data connections. * * @param passiveMode if true passive connections will be * established. If false, they will not. */ public void setPassiveMode(boolean passiveMode) throws IOException, ClientException, ServerException { if (passiveMode) { setPassive(); setLocalActive(); } else { setLocalPassive(); setActive(); } } public boolean isPassiveMode() { return (this.session.serverMode == Session.SERVER_PASSIVE); } ////////////////////////////////////////////////////////////////////// // Implementation of GFD.47 compliant GETPUT support. The reason // why this is implemented in FTPClient rather than GridFTPClient // is, that GFD.47 support is detected via feature strings and is // thus independent of GSI authentication. /** * Throws ServerException if GFD.47 GETPUT is not supported or * cannot be used. */ protected void checkGETPUTSupport() throws ServerException, IOException { if (!isFeatureSupported(FeatureList.GETPUT)) { throw new ServerException(ServerException.UNSUPPORTED_FEATURE); } if (controlChannel.isIPv6()) { throw new ServerException(ServerException.UNSUPPORTED_FEATURE, "Cannot use GridFTP2 with IP 6"); } } /** * Regular expression for matching the port information of a * GFD.47 127 reply. */ public static final Pattern portPattern = Pattern.compile("\\d+,\\d+,\\d+,\\d+,\\d+,\\d+"); /** * Reads a GFD.47 compliant 127 reply and extracts the port * information from it. */ protected HostPort get127Reply() throws ServerException, IOException, FTPReplyParseException { Reply reply = controlChannel.read(); if (Reply.isTransientNegativeCompletion(reply) || Reply.isPermanentNegativeCompletion(reply)) { throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(reply), reply.getMessage()); } if (reply.getCode() != 127) { throw new ServerException(ServerException.WRONG_PROTOCOL, reply.getMessage()); } Matcher matcher = portPattern.matcher(reply.getMessage()); if (!matcher.find()) { throw new ServerException(ServerException.WRONG_PROTOCOL, "Cannot parse 127 reply: " + reply.getMessage()); } return new HostPort(matcher.group()); } /** * Writes a GFD.47 compliant GET or PUT command to the control * channel. * * @param command Either "GET" or "PUT", depending on the command to issue * @param passive True if the "pasv" parameter should be used * @param port If passive is false, this is the port for * the "port" parameter * @param mode The value for the "mode" parameter, or 0 if the * parameter should not be specified * @param path The value for the "path" parameter */ private void issueGETPUT(String command, boolean passive, HostPort port, int mode, String path) throws IOException { Command cmd = new Command(command, (passive ? "pasv" : ("port=" + port.toFtpCmdArgument()) ) + ";" + "path=" + path + ";" + (mode > 0 ? "mode=" + getModeStr(mode) + ";" : "")); controlChannel.write(cmd); } /** * Retrieves a file using the GFD.47 (a.k.a GridFTP2) GET command. * * Notice that as a side effect this method may change the local * server facade passive/active mode setting. The caller should * not rely on this setting after call to get2. * * Even though the active/passive status of the current session is * ignored for the actual transfer, it still has to be in a * consistent state prior to calling gridftp2Get. * * @param remoteFileName file to retrieve * @param passive whether to configure the server to be passive * @param sink data sink to store the file * @param mListener marker listener **/ public void get2(String remoteFileName, boolean passive, DataSink sink, MarkerListener mListener) throws IOException, ClientException, ServerException { int serverMode = session.serverMode; HostPort serverAddress = session.serverAddress; try { // Can we use GETPUT? checkGETPUTSupport(); // Check sanity of arguments if (session.transferMode == GridFTPSession.MODE_EBLOCK && passive) { throw new IllegalArgumentException("Sender must be active in extended block mode"); } // All parameters set correctly (or still unset)? Session localSession = localServer.getSession(); session.matches(localSession); // Connection setup depends a lot on whether we use // passive or active mode. The passive party needs to be // configured before the active party. if (passive) { issueGETPUT("GET", true, null, 0, remoteFileName); session.serverMode = Session.SERVER_PASSIVE; session.serverAddress = get127Reply(); setLocalActive(); localServer.store(sink); } else { HostPort hp = setLocalPassive(); localServer.store(sink); issueGETPUT("GET", false, hp, 0, remoteFileName); session.serverMode = Session.SERVER_ACTIVE; } transferRunSingleThread(localServer.getControlChannel(), mListener); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } finally { session.serverMode = serverMode; session.serverAddress = serverAddress; } } /** * Retrieves a file asynchronously using the GFD.47 (a.k.a * GridFTP2) GET command. * * Notice that as a side effect this method may change the local * server facade passive/active mode setting. The caller should * not rely on this setting after call to gridftp2Get. * * Even though the active/passive status of the current session is * ignored for the actual transfer, it still has to be in a * consistent state prior to calling gridftp2Get. * * @param remoteFileName file to retrieve * @param passive whether to configure the server to be passive * @param sink data sink to store the file * @param mListener marker listener **/ public TransferState asynchGet2(String remoteFileName, boolean passive, DataSink sink, MarkerListener mListener) throws IOException, ClientException, ServerException { int serverMode = session.serverMode; HostPort serverAddress = session.serverAddress; try { // Can we use GETPUT? checkGETPUTSupport(); // Check sanity of arguments if (session.transferMode == GridFTPSession.MODE_EBLOCK && passive) { throw new IllegalArgumentException("Sender must be active in extended block mode"); } // All parameters set correctly (or still unset)? Session localSession = localServer.getSession(); session.matches(localSession); // Connection setup depends a lot on whether we use // passive or active mode. The passive party needs to be // configured before the active party. if (passive) { issueGETPUT("GET", true, null, 0, remoteFileName); session.serverMode = Session.SERVER_PASSIVE; session.serverAddress = get127Reply(); setLocalActive(); localServer.store(sink); } else { HostPort hp = setLocalPassive(); localServer.store(sink); issueGETPUT("GET", false, hp, 0, remoteFileName); session.serverMode = Session.SERVER_ACTIVE; } return transferStart(localServer.getControlChannel(), mListener); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } finally { // This might not be the most elegant or correct // solution. On the other hand, these parameters do not // seem to be used after transferStart() and it is much // easier to restore the old values now rather than when // the transfer completes. session.serverMode = serverMode; session.serverAddress = serverAddress; } } /** * Stores a file at the remote server using the GFD.47 (a.k.a * GridFTP2) PUT command. * * Notice that as a side effect this method may change the local * server facade passive/active mode setting. The caller should * not rely on this setting after call to gridftp2Get. * * Even though the active/passive status of the current session is * ignored for the actual transfer, it still has to be in a * consistent state prior to calling gridftp2Get. * * @param remoteFileName file to retrieve * @param passive whether to configure the server to be passive * @param source data will be read from here * @param mListener marker listener **/ public void put2(String remoteFileName, boolean passive, DataSource source, MarkerListener mListener) throws IOException, ClientException, ServerException { int serverMode = session.serverMode; HostPort serverAddress = session.serverAddress; try { // Can we use GETPUT? checkGETPUTSupport(); // Check sanity of arguments if (session.transferMode == GridFTPSession.MODE_EBLOCK && !passive) { throw new IllegalArgumentException("Sender must be active in extended block mode"); } // All parameters set correctly (or still unset)? Session localSession = localServer.getSession(); session.matches(localSession); // Connection setup depends a lot on whether we use // passive or active mode. The passive party needs to be // configured before the active party. if (passive) { issueGETPUT("PUT", true, null, 0, remoteFileName); session.serverMode = Session.SERVER_PASSIVE; session.serverAddress = get127Reply(); setLocalActive(); localServer.retrieve(source); } else { HostPort hp = setLocalPassive(); localServer.retrieve(source); issueGETPUT("PUT", false, hp, 0, remoteFileName); session.serverMode = Session.SERVER_ACTIVE; } transferRunSingleThread(localServer.getControlChannel(), mListener); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } finally { session.serverMode = serverMode; session.serverAddress = serverAddress; } } /** * Stores a file at the remote server using the GFD.47 (a.k.a * GridFTP2) PUT command. * * Notice that as a side effect this method may change the local * server facade passive/active mode setting. The caller should * not rely on this setting after call to gridftp2Get. * * Even though the active/passive status of the current session is * ignored for the actual transfer, it still has to be in a * consistent state prior to calling gridftp2Get. * * @param remoteFileName file to retrieve * @param passive whether to configure the server to be passive * @param source data will be read from here * @param mListener marker listener **/ public TransferState asynchPut2(String remoteFileName, boolean passive, DataSource source, MarkerListener mListener) throws IOException, ClientException, ServerException { int serverMode = session.serverMode; HostPort serverAddress = session.serverAddress; try { // Can we use GETPUT? checkGETPUTSupport(); // Check sanity of arguments if (session.transferMode == GridFTPSession.MODE_EBLOCK && !passive) { throw new IllegalArgumentException("Sender must be active in extended block mode"); } // All parameters set correctly (or still unset)? Session localSession = localServer.getSession(); session.matches(localSession); // Connection setup depends a lot on whether we use // passive or active mode. The passive party needs to be // configured before the active party. if (passive) { issueGETPUT("PUT", true, null, 0, remoteFileName); session.serverMode = Session.SERVER_PASSIVE; session.serverAddress = get127Reply(); setLocalActive(); localServer.retrieve(source); } else { HostPort hp = setLocalPassive(); localServer.retrieve(source); issueGETPUT("PUT", false, hp, 0, remoteFileName); session.serverMode = Session.SERVER_ACTIVE; } return transferStart(localServer.getControlChannel(), mListener); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } finally { // This might not be the most elegant or correct // solution. On the other hand, these parameters do not // seem to be used after transferStart() and it is much // easier to restore the old values now rather than when // the transfer completes. session.serverMode = serverMode; session.serverAddress = serverAddress; } } /** * Performs third-party transfer between two servers. If possibly, * GFD.47 (a.k.a GridFTP2) GET and PUT commands are used. * * @param source client connected to source server * @param remoteSrcFile source filename * @param destination client connected to destination server * @param remoteDstFile destination filename * @param mode data channel mode or 0 to use the current mode * @param mListener marker listener. * Can be set to null. */ static public void transfer(FTPClient source, String remoteSrcFile, FTPClient destination, String remoteDstFile, int mode, MarkerListener mListener) throws IOException, ServerException, ClientException { try { // Although neither mode nor passive setting from in the // session is used, we still perform this check, since // other things may be checked as well. source.session.matches(destination.session); HostPort hp; if (destination.isFeatureSupported(FeatureList.GETPUT)) { destination.issueGETPUT("PUT", true, null, mode, remoteDstFile); hp = ((GridFTPClient)destination).get127Reply(); } else { if (mode > 0) { destination.setMode(mode); } hp = destination.setPassive(); destination.controlChannel.write(new Command("STOR", remoteDstFile)); } if (source.isFeatureSupported(FeatureList.GETPUT)) { source.issueGETPUT("GET", false, hp, mode, remoteSrcFile); } else { if (mode > 0) { source.setMode(mode); } source.setActive(hp); source.controlChannel.write(new Command("RETR", remoteSrcFile)); } source.transferRunSingleThread(destination.controlChannel, mListener); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } public boolean isActiveMode() { return (this.session.serverMode == Session.SERVER_ACTIVE); } /** * Controls whether the client attempts to send an ALLO command * before a STOR request during the put/asyncPut calls. This is * disabled by default in the FTP client and enabled by default * in the GridFTP client. This setting will apply to all * subsequent transfers. * * @param useAllo true if the client should try * to send an ALLO command before a STOR request */ public void setUseAllo(boolean useAllo) { this.useAllo = useAllo; } /** * Determines whether this client is configured to send an ALLO * command before a STOR request in the put/asyncPut methods. */ public boolean getUseAllo() { return this.useAllo; } /** * According to * GridFTP v2 Protocol Description * checksum feature has the following syntax: *
         * CKSUM [, …]
         * 
    * getSupportedCksumAlgorithms parses checsum feauture parms and form a * list of checksum algorithms supported by the server * @return a list of checksum algorithms supported by the server in the order * specified by the server * @throws org.globus.ftp.exception.ClientException * @throws org.globus.ftp.org.globus.ftp.exception.ServerException * @throws java.io.IOException */ public List getSupportedCksumAlgorithms() throws ClientException, ServerException, IOException { if(algorithms != null) { return algorithms; } // check if the CKSUM algorithm is supported by the server List cksumFeature = getFeatureList().getFeature(FeatureList.CKSUM); if(cksumFeature == null) { algorithms = Collections.emptyList(); return algorithms; } algorithms = new ArrayList(); for(FeatureList.Feature feature:cksumFeature) { String[] parms = feature.getParms().split(","); for (String parm: parms) { algorithms.add(parm); } } return algorithms; } public boolean isCksumAlgorithmSupported(String algorithm) throws ClientException, ServerException, IOException { return getSupportedCksumAlgorithms().contains(algorithm.toUpperCase()); } private void checkCksumSupport(String algorithm) throws ClientException, ServerException, IOException { // check if the CKSUM is supported by the server if (! isFeatureSupported(FeatureList.CKSUM) ) { throw new ClientException( ClientException.OTHER, FeatureList.CKSUM+" is not supported by server"); } // check if the CKSUM algorithm is supported by the server if(! isCksumAlgorithmSupported(algorithm) ) { throw new ClientException( ClientException.OTHER, FeatureList.CKSUM+" algorithm "+algorithm+ " is not supported by server"); } } /** * implement GridFTP v2 CKSM command from * GridFTP v2 Protocol Description *
         * 5.1 CKSM
         * This command is used by the client to request checksum calculation over a portion or
         * whole file existing on the server. The syntax is:
         * CKSM     CRLF
         * Server executes this command by calculating specified type of checksum over
         * portion of the file starting at the offset and of the specified length. If length is –1,
         * the checksum will be calculated through the end of the file. On success, the server
         * replies with
         * 2xx 
         * Actual format of checksum value depends on the algorithm used, but generally,
         * hexadecimal representation should be used.
         * 
    * * @param algorithm ckeckum alorithm * @param offset * @param length * @param path * @return ckecksum value returned by the server * @throws org.globus.ftp.exception.ClientException * @throws org.globus.ftp.org.globus.ftp.exception.ServerException * @throws java.io.IOException */ public String getChecksum(String algorithm, long offset, long length, String path) throws ClientException, ServerException, IOException { // check if we the cksum commands and specific algorithm are supported checkCksumSupport(algorithm); // form CKSM command String parameters = String.format("%s %d %d %s",algorithm, offset,length,path); Command cmd = new Command("CKSM", parameters); // transfer command, obtain reply Reply cksumReply = doCommand(cmd); // check for error if( !Reply.isPositiveCompletion(cksumReply) ) { throw new ServerException(ServerException.SERVER_REFUSED, cksumReply.getMessage()); } return cksumReply.getMessage(); } /** * GridFTP v2 CKSM command for the whole file * @param algorithm ckeckum alorithm * @param path * @return ckecksum value returned by the server * @throws org.globus.ftp.exception.ClientException * @throws org.globus.ftp.org.globus.ftp.exception.ServerException * @throws java.io.IOException */ public String getChecksum(String algorithm, String path) throws ClientException, ServerException, IOException { return getChecksum(algorithm,0,-1,path); } /** * implement GridFTP v2 SCKS command as described in * GridFTP v2 Protocol Description *
         * 5.2 SCKS
         * This command is sent prior to upload command such as STOR, ESTO, PUT. It is used
         * to convey to the server that the checksum value for the file which is about to be
         * uploaded. At the end of transfer, server will calculate checksum for the received file,
         * and if it does not match, will consider the transfer to have failed. Syntax of the
         * command is:
         * SCKS   CRLF
         * Actual format of checksum value depends on the algorithm used, but generally,
         * hexadecimal representation should be used.
         * 
    * @param algorithm * @param value * @throws org.globus.ftp.exception.ClientException * @throws org.globus.ftp.org.globus.ftp.exception.ServerException * @throws java.io.IOException */ public void setChecksum(String algorithm, String value) throws ClientException, ServerException, IOException { // check if we the cksum commands and specific algorithm are supported checkCksumSupport(algorithm); // form CKSM command String parameters = String.format("%s %s",algorithm, value); Command cmd = new Command("SCKS", parameters); // transfer command, obtain reply Reply cksumReply = doCommand(cmd); // check for error if( !Reply.isPositiveCompletion(cksumReply) ) { throw new ServerException(ServerException.SERVER_REFUSED, cksumReply.getMessage()); } return; } } //FTPClient JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/FeatureList.java000066400000000000000000000140751241116057200300460ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; /** Represents features supported by server (as returned by FEAT command). Use the static members of this class to refer to well known feature names. Example: check if the server supports PARALLEL feature:
       FeatureList fl = new FeatureList(client.getFeatureList());
       if (fl.contains(FeatureList.PARALLEL)) {
           ...
       }
       
    **/ public class FeatureList { /** * RFC 2389 specified the following syntax for FEAT responce *
         * feat-response   = error-response / no-features / feature-listing
         *  no-features     = "211" SP *TCHAR CRLF
         *  feature-listing = "211-" *TCHAR CRLF
         *                    1*( SP feature CRLF )
         *                    "211 End" CRLF
         *  feature         = feature-label [ SP feature-parms ]
         *  feature-label   = 1*VCHAR
         *  feature-parms   = 1*TCHAR
         * 
    * Feature class represence each individual feature and contain two fields * required label and optional parms * */ public static final class Feature { private final String label; private final String parms; private Feature (String label) { if(label == null ) { throw new NullPointerException("label is null"); } this.label = label; this.parms = null; } private Feature (String label, String parms) { if(label == null ) { throw new NullPointerException("label is null"); } this.label = label; this.parms = parms; } /** * @return the name */ public String getLabel() { return label; } /** * @return the qualifiers, null if no qualifiers */ public String getParms() { return parms; } @Override public boolean equals(Object obj) { if( !(obj instanceof Feature)) { return false; } Feature aFeature = (Feature) obj; if( !label.equals(aFeature.label) ) { return false; } if( parms == null ) { return aFeature.parms == null; } return parms.equals( aFeature.parms); } } // well known labels public static final String SIZE = "SIZE"; public static final String MDTM = "MDTM"; public static final String PARALLEL = "PARALLEL"; public static final String ESTO = "ESTO"; public static final String ERET = "ERET"; public static final String SBUF = "SBUF"; public static final String ABUF = "ABUF"; public static final String DCAU = "DCAU"; public static final String PIPE = "PIPE"; public static final String MODEX = "MODEX"; public static final String GETPUT = "GETPUT"; public static final String CKSUM = "CKSUM"; protected final List features = new ArrayList(); public FeatureList(String featReplyMsg) { StringTokenizer responseTokenizer = new StringTokenizer(featReplyMsg, System.getProperty("line.separator")); // ignore the first part of the message if (responseTokenizer.hasMoreElements()) { responseTokenizer.nextToken(); } while ( responseTokenizer.hasMoreElements() ) { String line = (String) responseTokenizer.nextElement(); line = line.trim().toUpperCase(); if ( line.startsWith( "211 END" ) ) { break; } String[] splitFeature = line.split(" "); if( splitFeature.length ==2) { features.add(new Feature(splitFeature[0], splitFeature[1])); } else { features.add(new Feature(line)); } } } public boolean contains(String label) { if (label == null) { throw new IllegalArgumentException("label is null"); } //split argument using white space. String[] tokens = label.split(" ",2); if(tokens.length <1) { throw new IllegalArgumentException("label is empty"); } label = tokens[0].toUpperCase(); String parms = null; if(tokens.length >1) { parms = tokens[1]; } for( Feature feature:features ) { if(feature.getLabel().equals(label)) { if (parms == null) { //if parms are not specified as a part of the argument // string, we compare labels only return true; } else { //if parms are specified, we compare them as well Feature argFeature = new Feature(label, parms); if(argFeature.equals(feature)) { return true; } } } } return false; } /** * Get all features that have label equal to the argument * Note that RFC 2389 does not require a feature with a * given label to appear only once * @param label * @return List of found features with given label in the same order * as they were given to us by the server */ public List getFeature(String label) { if (label == null) { throw new IllegalArgumentException("feature label is null"); } label = label.toUpperCase(); List foundFeatures = new ArrayList(); for( Feature feature:features ) { if(feature.getLabel().equals(label)) { foundFeatures.add(feature); } } return foundFeatures; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/FileInfo.java000066400000000000000000000252441241116057200273120ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import org.globus.ftp.exception.FTPException; import java.util.StringTokenizer; /** * Represents the properties of a remote file * such as size, name, modification date and time, etc. * Can represent a regular file as well as a directory * or a soft link. */ public class FileInfo { public static final byte UNKNOWN_TYPE = 0; public static final byte FILE_TYPE = 1; public static final byte DIRECTORY_TYPE = 2; public static final byte SOFTLINK_TYPE = 3; public static final byte DEVICE_TYPE = 4; public static final String UNKNOWN_STRING = "?"; public static final int UNKNOWN_NUMBER = -1; private long size = UNKNOWN_NUMBER; private String name = UNKNOWN_STRING; private String date = UNKNOWN_STRING; private String time = UNKNOWN_STRING; private byte fileType; private int mode = 0; /** * Used internally by the FTPClient. */ public FileInfo() { } /** * Parses the file information from one line of response to * the FTP LIST command. Note: There is no commonly accepted * standard for the format of LIST response. * This parsing method only accepts * the most common Unix file listing formats: * System V or Berkeley (BSD) 'ls -l' * * @see #parseUnixListReply(String reply) * @param unixListReply a single line from ls -l command */ public FileInfo(String unixListReply) throws FTPException { parseUnixListReply(unixListReply); } /** * Given a line of reply received as the result of "LIST" command, * this method will set all the attributes(name,size,time,date and file type) * of the named file. This method requires the reply to be in * FTP server format, corresponding to either Unix System V or * Berkeley (BSD) output of 'ls -l'. For example, *
    drwxr-xr-x   2      guest  other  1536  Jan 31 15:15  run.bat
    * or *
    -rw-rw-r--   1      globus    117579 Nov 29 13:24 AdGriP.pdf
    * If the entry corresponds to a device file, only the file type * will be set and the other parameters will be set to UNKNOWN. * * @param reply reply of FTP server for "dir" command. * @exception FTPException if unable to parse the reply */ //protected void parseUnixListReply(String reply) public void parseUnixListReply(String reply) throws FTPException { if (reply == null) return; StringTokenizer tokens = new StringTokenizer(reply); String token, previousToken; int numTokens = tokens.countTokens(); if (numTokens < 8) { throw new FTPException(FTPException.UNSPECIFIED, "Invalid number of tokens in the list reply [" + reply + "]"); } token = tokens.nextToken(); // permissions switch( token.charAt(0) ) { case 'd': setFileType(DIRECTORY_TYPE); break; case '-': setFileType(FILE_TYPE); break; case 'l': setFileType(SOFTLINK_TYPE); break; case 'c': case 'b': // do not try to parse device entries; // they aren't important anyway setFileType(DEVICE_TYPE); return; default: setFileType(UNKNOWN_TYPE); } try { for(int i=1;i<=9;i++) { if (token.charAt(i) != '-') { mode += 1 << (9 - i); } } } catch (IndexOutOfBoundsException e) { throw new FTPException(FTPException.UNSPECIFIED, "Could not parse access permission bits"); } // ??? can ignore tokens.nextToken(); // next token is the owner tokens.nextToken(); // In ls from System V, next token is the group // In ls from Berkeley (BSD), group token is missing previousToken = tokens.nextToken(); // size token = tokens.nextToken(); /* * if the group is missing this will try to parse the date field * as an integer and will fail. if so, then the previous field is the size field * and the current token is part of the date. */ try { setSize( Long.parseLong(token) ); token = null; } catch(NumberFormatException e) { // this might mean that the group is missing // and this token is part of date. try { setSize( Long.parseLong(previousToken) ); } catch(NumberFormatException ee) { throw new FTPException(FTPException.UNSPECIFIED, "Invalid size number in the ftp reply [" + previousToken + ", " + token + "]"); } } // date - two fields together if (token == null) { token = tokens.nextToken(); } String month = token; setDate(token + " " + tokens.nextToken()); //next token is either date or time token = tokens.nextToken(); this.setTime(token); // this is to handle spaces in the filenames // as well filenames with dates in them int ps = reply.indexOf(month); if (ps == -1) { // this should never happen throw new FTPException(FTPException.UNSPECIFIED, "Could not find date token"); } else { ps = reply.indexOf(this.time, ps+month.length()); if (ps == -1) { // this should never happen throw new FTPException(FTPException.UNSPECIFIED, "Could not find time token"); } else { this.setName(reply.substring(1+ps+this.time.length())); } } } // -------------------------------- /** * Sets the file size. * * @param size size of the file */ public void setSize(long size) { this.size = size; } /** * Sets the file name. * * @param name name of the file. */ public void setName(String name) { this.name = name; } /** * Sets the file date. * * @param date date of the file. */ public void setDate(String date) { this.date = date; } /** * Sets modification time of the file. * * @param time time of the file. */ public void setTime(String time) { this.time = time; } /** * Sets the file type. * * @param type one of the file types, * e.g. FILE_TYPE, DIRECTORY_TYPE * */ public void setFileType(byte type) { this.fileType = type; } // --------------------------------- /** * Returns size of the file. * * @return size of the file in bytes */ public long getSize() { return size; } /** * Returns name of the file. * * @return name of the file. */ public String getName() { return name; } /** * Returns date of the file. * * @return date of the file. */ public String getDate() { return date; } /** * Returns modification time of the file. * * @return time of the file. */ public String getTime() { return time; } /** * Tests if this file is a file. * * @return true if this represents a file, * otherwise, false. */ public boolean isFile() { return (fileType == FILE_TYPE); } /** * Tests if this file is a directory. * * @return true if this reprensets a directory, * otherwise, false. */ public boolean isDirectory() { return (fileType == DIRECTORY_TYPE); } /** * Tests if this file is a softlink. * * @return true if this reprensets a softlink, * otherwise, false. */ public boolean isSoftLink() { return (fileType == SOFTLINK_TYPE); } /** * Tests if this file is a device. */ public boolean isDevice() { return (fileType == DEVICE_TYPE); } public int getMode() { return mode; } public String getModeAsString() { StringBuffer modeStr = new StringBuffer(); for(int j=2;j>=0;j--) { int oct = 0; for(int i=2;i>=0;i--) { if ((mode & (1 << j*3+i)) != 0) { oct += (int)Math.pow(2,i); } } modeStr.append(String.valueOf(oct)); } return modeStr.toString(); } public boolean userCanRead() { return ((mode & (1 << 8)) != 0); } public boolean userCanWrite() { return ((mode & (1 << 7)) != 0); } public boolean userCanExecute() { return ((mode & (1 << 6)) != 0); } public boolean groupCanRead() { return ((mode & (1 << 5)) != 0); } public boolean groupCanWrite() { return ((mode & (1 << 4)) != 0); } public boolean groupCanExecute() { return ((mode & (1 << 3)) != 0); } public boolean allCanRead() { return ((mode & (1 << 2)) != 0); } public boolean allCanWrite() { return ((mode & (1 << 1)) != 0); } public boolean allCanExecute() { return ((mode & (1 << 0)) != 0); } // -------------------------------- public String toString() { StringBuffer buf = new StringBuffer(); buf.append("FileInfo: "); buf.append(getName() + " "); buf.append(getSize() + " "); buf.append(getDate() + " "); buf.append(getTime() + " "); switch( fileType ) { case DIRECTORY_TYPE: buf.append("directory"); break; case FILE_TYPE: buf.append("file"); break; case SOFTLINK_TYPE: buf.append("softlink"); break; default: buf.append("unknown type"); } buf.append(" "+getModeAsString()); return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/FileRandomIO.java000066400000000000000000000052641241116057200300670ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; import java.io.RandomAccessFile; /** Thread safe reference implementation of DataSink and DataSource. Implements reading and writing data to a local file. Note: Does not work with {@link Session#MODE_STREAM Session.STREAM} transfer mode, only with {@link GridFTPSession#MODE_EBLOCK GridFTPSession.EBLOCK} mode. */ public class FileRandomIO implements DataSink, DataSource { public static final int DEFAULT_BUFFER_SIZE = 16384; protected int bufferSize; protected RandomAccessFile file; protected long offset; /** Behave like FileRandomIO(file, DEFAULT_BUFFER_SIZE) @param file local file that will be be used as data source or destination */ public FileRandomIO(RandomAccessFile file) { this(file, DEFAULT_BUFFER_SIZE); } /** @param file local file that will be be used as data source or destination @param bufferSize size of the buffer returned during single read operation */ public FileRandomIO(RandomAccessFile file, int bufferSize) { this.file = file; this.bufferSize = bufferSize; } public synchronized void write(Buffer buffer) throws IOException { long bufOffset = buffer.getOffset(); if (bufOffset == -1) { if (file.getFilePointer() != this.offset) { throw new IOException("Invalid offset: " + bufOffset); } } else { file.seek(bufOffset); } file.write(buffer.getBuffer(), 0, buffer.getLength()); this.offset += buffer.getLength(); } /** In this implementation, each read() returns data sequentially. */ public synchronized Buffer read() throws IOException { long offset = file.getFilePointer(); byte [] buf = new byte[bufferSize]; int read = file.read(buf); if (read == -1) { return null; } else { return new Buffer(buf, read, offset); } } /** Closes the underlying file */ public synchronized void close() throws IOException { file.close(); } public long totalSize() throws IOException { return file.length(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/GridFTPClient.java000066400000000000000000001200341241116057200302060ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; import java.io.File; import java.io.RandomAccessFile; import java.util.Vector; import java.net.UnknownHostException; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.ServerException; import org.globus.ftp.exception.FTPReplyParseException; import org.globus.ftp.exception.UnexpectedReplyCodeException; import org.globus.ftp.vanilla.Command; import org.globus.ftp.vanilla.Reply; import org.globus.ftp.vanilla.TransferState; import org.globus.ftp.vanilla.FTPControlChannel; import org.globus.ftp.extended.GridFTPServerFacade; import org.globus.ftp.extended.GridFTPControlChannel; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.ftp.MultipleTransferComplete; import org.globus.ftp.MultipleTransferCompleteListener; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.common.Version; import java.io.ByteArrayOutputStream; import java.text.DecimalFormat; import org.globus.ftp.exception.FTPException; /** * This is the main user interface for GridFTP operations. * Use this class for client - server or third party transfers * with mode E, parallelism, markers, striping or GSI authentication. * Consult the manual for general usage. *
    Note: If using with GridFTP servers operations like * {@link #setMode(int) setMode()}, {@link #setType(int) setType()}, * {@link #setDataChannelProtection(int) setDataChannelProtection()}, * and {@link #setDataChannelAuthentication(DataChannelAuthentication) * setDataChannelAuthentication()} that affect data channel settings * must be called before passive or active data channel mode is set. **/ public class GridFTPClient extends FTPClient { private static Log logger = LogFactory.getLog(GridFTPClient.class.getName()); //utility alias to session and localServer protected GridFTPSession gSession; protected GridFTPServerFacade gLocalServer; protected String usageString; /** * Constructs client and connects it to the remote server. * * @param host remote server host * @param port remote server port */ public GridFTPClient(String host, int port) throws IOException, ServerException { gSession = new GridFTPSession(); session = gSession; controlChannel = new GridFTPControlChannel(host, port); controlChannel.open(); gLocalServer = new GridFTPServerFacade((GridFTPControlChannel)controlChannel); localServer = gLocalServer; gLocalServer.authorize(); this.useAllo = true; setUsageInformation("CoG", Version.getVersion()); } /** * Performs authentication with specified user credentials. * * @param credential user credentials to use. * @throws IOException on i/o error * @throws ServerException on server refusal or faulty server behavior */ public void authenticate(GSSCredential credential) throws IOException, ServerException { authenticate(credential, null); } public void setUsageInformation( String appName, String appVer) { usageString = new String( "CLIENTINFO appname=" + appName +";appver=" + appVer + ";schema=gsiftp;"); } /** * Performs authentication with specified user credentials and * a specific username (assuming the user dn maps to the passed username). * * @param credential user credentials to use. * @param username specific username to authenticate as. * @throws IOException on i/o error * @throws ServerException on server refusal or faulty server behavior */ public void authenticate(GSSCredential credential, String username) throws IOException, ServerException { ((GridFTPControlChannel)controlChannel).authenticate(credential, username); gLocalServer.setCredential(credential); gSession.authorized = true; this.username = username; // quietly send version information to the server. // ignore errors try { String version = Version.getVersion(); this.site(usageString); } catch (Exception ex) { } } /** * Performs remote directory listing like * {@link FTPClient#list(String,String) FTPClient.list()}. * Note: This method cannot be used * in conjunction with parallelism or striping; set parallelism to * 1 before calling it. Otherwise, use * {@link FTPClient#list(String,String,DataSink) FTPClient.list()}. * Unlike in vanilla FTP, here IMAGE mode is allowed. * For more documentation, look at FTPClient. */ public Vector list(String filter, String modifier) throws ServerException, ClientException, IOException { if (gSession.parallel > 1) { throw new ClientException( ClientException.BAD_MODE, "list cannot be called with parallelism"); } return super.list(filter, modifier); } /** * Performs remote directory listing like * {@link FTPClient#nlist(String) FTPClient.nlist()}. * Note: This method cannot be used * in conjunction with parallelism or striping; set parallelism to * 1 before calling it. Otherwise, use * {@link FTPClient#nlist(String,DataSink) FTPClient.nlist()}. * Unlike in vanilla FTP, here IMAGE mode is allowed. * For more documentation, look at FTPClient. */ public Vector nlist(String path) throws ServerException, ClientException, IOException { if (gSession.parallel > 1) { throw new ClientException( ClientException.BAD_MODE, "nlist cannot be called with parallelism"); } return super.nlist(path); } /** * Performs remote directory listing like * {@link FTPClient#mlsd(String) FTPClient.mlsd()}. * Note: This method cannot be used * in conjunction with parallelism or striping; set parallelism to * 1 before calling it. Otherwise, use * {@link FTPClient#mlsd(String,DataSink) FTPClient.mlsd()}. * Unlike in vanilla FTP, here IMAGE mode is allowed. * For more documentation, look at FTPClient. */ public Vector mlsd(String filter) throws ServerException, ClientException, IOException { if (gSession.parallel > 1) { throw new ClientException( ClientException.BAD_MODE, "mlsd cannot be called with parallelism"); } return super.mlsd(filter); } protected void listCheck() throws ClientException { // do nothing } protected void checkTransferParamsGet() throws ServerException, IOException, ClientException { Session localSession = localServer.getSession(); session.matches(localSession); // if transfer modes have not been defined, // set this (dest) as active if (session.serverMode == Session.SERVER_DEFAULT) { HostPort hp = setLocalPassive(); setActive(hp); } } protected String getModeStr(int mode) { switch (mode) { case Session.MODE_STREAM: return "S"; case Session.MODE_BLOCK: return "B"; case GridFTPSession.MODE_EBLOCK: return "E"; default: throw new IllegalArgumentException("Bad mode: " + mode); } } /** * Sets remote server TCP buffer size, in the following way: * First see if server supports "SBUF" and if so, use it. * If not, try the following commands until success: * "SITE RETRBUFSIZE", "SITE RBUFSZ", "SITE RBUFSIZ", * "SITE STORBUFSIZE", "SITE SBUFSZ", "SITE SBUFSIZ", * "SITE BUFSIZE". * Returns normally if the server confirms successfull setting of the * remote buffer size, both for sending and for receiving data. * Otherwise, throws ServerException. **/ public void setTCPBufferSize(int size) throws IOException, ServerException { if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } try { boolean succeeded = false; String sizeString = Integer.toString(size); FeatureList feat = getFeatureList(); if (feat.contains(FeatureList.SBUF)) { succeeded = tryExecutingCommand( new Command("SBUF", sizeString)); } if (!succeeded) { succeeded = tryExecutingCommand( new Command("SITE BUFSIZE", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RETRBUFSIZE", sizeString), new Command("SITE STORBUFSIZE", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RBUFSZ", sizeString), new Command("SITE SBUFSZ", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RBUFSIZ", sizeString), new Command("SITE SBUFSIZ", sizeString)); } if (succeeded) { this.gSession.TCPBufferSize = size; } else { throw new ServerException(ServerException.SERVER_REFUSED, "Server refused setting TCP buffer size with any of the known commands."); } } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } private boolean tryExecutingTwoCommands(Command cmd1, Command cmd2) throws IOException, FTPReplyParseException, ServerException { boolean result = tryExecutingCommand(cmd1); if (result) { result = tryExecutingCommand(cmd2); } return result; } /* * This is like controlChannel.executeCommand, only that negative reply it * returns "false" rather than throwing exception */ private boolean tryExecutingCommand(Command cmd) throws IOException, FTPReplyParseException, ServerException { Reply reply = controlChannel.exchange(cmd); return Reply.isPositiveCompletion(reply); } /** * Sets local TCP buffer size (for both receiving and sending). **/ public void setLocalTCPBufferSize(int size) throws ClientException { if (size <=0 ) { throw new IllegalArgumentException("size <= 0"); } gLocalServer.setTCPBufferSize(size); } /** * Sets remote server to striped passive server mode (SPAS). **/ public HostPortList setStripedPassive() throws IOException, ServerException { Command cmd = new Command("SPAS", (controlChannel.isIPv6()) ? "2" : null); Reply reply = null; try { reply = controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch(FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } this.gSession.serverMode = GridFTPSession.SERVER_EPAS; if (controlChannel.isIPv6()) { gSession.serverAddressList = HostPortList.parseIPv6Format(reply.getMessage()); int size = gSession.serverAddressList.size(); for (int i=0;i 1) { throw new ClientException( ClientException.BAD_MODE, "mlsr cannot be called with parallelism"); } Command cmd = (path == null) ? new Command("MLSR") : new Command("MLSR", path); MlsxParserDataSink sink = new MlsxParserDataSink(writer); performTransfer(cmd, sink); } private class MlsxParserDataSink implements DataSink { private MlsxEntryWriter writer; private byte[] buf = new byte[4096]; private int pos = 0; public MlsxParserDataSink(MlsxEntryWriter w) { writer = w; } public void write(Buffer buffer) throws IOException { byte[] data = buffer.getBuffer(); int len = buffer.getLength(); int i = 0; while (i < len && pos < buf.length) { if (data[i] == '\r' || data[i] == '\n') { if (pos > 0) { try { writer.write(new MlsxEntry(new String(buf, 0, pos))); } catch (FTPException ex) { throw new IOException(); } } pos = 0; while (i < len && data[i] < ' ') ++i; } else { buf[pos++] = data[i++]; } } } public void close() throws IOException { writer.close(); } } /** * Change the Unix group membership of a file. * * @param group the name or ID of the group * @param file the file whose group membership should be changed * @exception ServerException if an error occurred. */ public void changeGroup(String group, String file) throws IOException, ServerException { String arguments = group + " " + file; Command cmd = new Command("SITE CHGRP", arguments); try { controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } /** * Change the modification time of a file. * * @param year Modifcation year * @param month Modification month (1-12) * @param day Modification day (1-31) * @param hour Modification hour (0-23) * @param min Modification minutes (0-59) * @param sec Modification seconds (0-59) * @param file file whose modification time should be changed * @throws IOException * @throws ServerException if an error occurred. */ public void changeModificationTime(int year, int month, int day, int hour, int min, int sec, String file) throws IOException, ServerException { DecimalFormat df2 = new DecimalFormat("00"); DecimalFormat df4 = new DecimalFormat("0000"); String arguments = df4.format(year) + df2.format(month) + df2.format(day) + df2.format(hour) + df2.format(min) + df2.format(sec) + " " + file; Command cmd = new Command("SITE UTIME", arguments); try { controlChannel.execute(cmd); }catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } /** * Create a symbolic link on the FTP server. * * @param link_target the path to which the symbolic link should point * @param link_name the path of the symbolic link to create * @throws IOException * @throws ServerException if an error occurred. */ public void createSymbolicLink(String link_target, String link_name) throws IOException, ServerException { String arguments = link_target.replaceAll(" ", "%20") + " " + link_name; Command cmd = new Command("SITE SYMLINK", arguments); try { controlChannel.execute(cmd); }catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/GridFTPRestartMarker.java000066400000000000000000000072771241116057200315730ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.util.Vector; import java.util.StringTokenizer; import java.util.NoSuchElementException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Represents GridFTP restart marker, which contains unordered set of byte ranges representing transferred data. The ranges are preserved exactly as received from the server, which may not be very useful. For additional processing on byte ranges, use ByteRangeList. Typical usage:
       list = new ByteRangeList();
       marker = new GridFTPRestartMarker(reply.getMessage());
       list.merge(marker.getVector());
       
    @see ByteRangeList **/ public class GridFTPRestartMarker implements Marker { private static Log logger = LogFactory.getLog(GridFTPRestartMarker.class.getName()); Vector vector; /** Constructs the restart marker by parsing the parameter string. @param msg The string in the format of FTP reply 111 message, for instance "Range Marker 0-29,30-89" @throws IllegalArgumentException if the parameter is in bad format **/ public GridFTPRestartMarker(String msg) throws IllegalArgumentException{ // expecting msg like "Range Marker 0-29,30-89" vector = new Vector(); StringTokenizer tokens = new StringTokenizer(msg); if (! tokens.hasMoreTokens()) { badMsg("message empty", msg); } if (! tokens.nextToken(" ").equals("Range")) { badMsg("should start with Range Marker", msg); } if (! tokens.nextToken(" ").equals("Marker")) { badMsg("should start with Range Marker", msg); } while(tokens.hasMoreTokens()) { long from =0; long to =0; try { String rangeStr = tokens.nextToken(","); StringTokenizer rangeTok = new StringTokenizer(rangeStr, "-"); from = Long.parseLong(rangeTok.nextToken().trim()); to = Long.parseLong(rangeTok.nextToken().trim()); if (rangeTok.hasMoreElements()) { badMsg("A range is followed by '-'", msg); } } catch(NoSuchElementException nse) { // range does not look like "from-to" badMsg("one of the ranges is malformatted", msg); } catch (NumberFormatException nfe) { badMsg("one of the integers is malformatted", msg); } try { vector.add(new ByteRange(from, to)); } catch(IllegalArgumentException iae) { // to < from badMsg("range beginning > range end", msg); } } //vector now contains all ranges if (vector.size() == 0 ) { badMsg("empty range list", msg); } }; private void badMsg(String why, String msg) { throw new IllegalArgumentException( "argument is not FTP 111 reply message (" + why + ": ->" + msg + "<-"); } /** Returns Vector representation of this object. Its elements are be ByteRange objects. They are in the order exactly as received in the FTP reply; no additional processing has been done on them. To order and merge them, use ByteRangeList. Subsequent calls of this method will return the same Vector object. @return Vector representation of this object. **/ public Vector toVector() { return vector; }; } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/GridFTPSession.java000066400000000000000000000126401241116057200304160ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import org.globus.ftp.exception.ClientException; import org.ietf.jgss.GSSCredential; /** * Represents parameters of an FTP session between a client and a server. */ public class GridFTPSession extends Session { /** * Indicates Extended Block Mode for data transfer. Used with * {@link GridFTPClient#setMode(int) GridFTPClient.setMode()}. */ public static final int MODE_EBLOCK = 3; /** * server in extended passive mode */ public static final int SERVER_EPAS = 3; /** * server in extended active mode */ public static final int SERVER_EACT = 4; /** * Indicates that the data channel will carry the raw data of the file * transfer, with no security applied. Used with * {@link GridFTPClient#setDataChannelProtection(int) * setDataChannelProtection()}. */ public static final int PROTECTION_CLEAR = 1; /** * Indicates that the data will be integrity protected. Used with * {@link GridFTPClient#setDataChannelProtection(int) * setDataChannelProtection()}. */ public static final int PROTECTION_SAFE = 2; /** * Indicates that the data will be confidentiality protected (Currently, not * support by GridFTP servers). Used with * {@link GridFTPClient#setDataChannelProtection(int) * setDataChannelProtection()}. */ public static final int PROTECTION_CONFIDENTIAL = 3; /** * Indicates that the data will be integrity and confidentiality protected. * Used with {@link GridFTPClient#setDataChannelProtection(int) * setDataChannelProtection()}. */ public static final int PROTECTION_PRIVATE = 4; /* default in gridftp - not in gsiftp */ public DataChannelAuthentication dataChannelAuthentication = DataChannelAuthentication.SELF; public int dataChannelProtection = PROTECTION_CLEAR; public GSSCredential credential = null; public int parallel = 1; public int TCPBufferSize = SERVER_DEFAULT; /** * This concerns local server. if in SERVER_EPAS mode, the server listener * socket list is stored here. If in SERVER_PASV mode, the server listener * sockets is stored in serverAddress variable. */ public HostPortList serverAddressList = null; /** * Sets maxWait to twice the time of DEFAULT_MAX_WAIT */ public GridFTPSession() { maxWait = 2 * DEFAULT_MAX_WAIT; } /** * In addition to the inherited functionality, this method also (1) checks * if extended active / passive server modes are set correctly, (2) checks * if Mode E is needed, and if so, checks whether it has been set. If not, * ClientException is thrown. */ public void matches(Session other) throws ClientException { compareTransferParams(other); compareServerMode(other); if (needsGridFTP() && transferMode != MODE_EBLOCK) { throw new ClientException(ClientException.BAD_MODE, "Extended block mode necessary"); } if (other instanceof GridFTPSession && ((GridFTPSession) other).needsGridFTP() && transferMode != MODE_EBLOCK) { throw new ClientException(ClientException.BAD_MODE, "Extended block mode necessary"); } } // called by inherited matches() method protected void compareServerMode(Session other) throws ClientException { if (transferMode != MODE_EBLOCK) { super.compareServerMode(other); } else { if (serverMode == SERVER_DEFAULT && other.serverMode == SERVER_DEFAULT) { // this is OK } else { // active and passive side had already been set; // make sure that it has been done correctly. // in mode E, source must be active and dest passive if (!((serverMode == SERVER_EACT && other.serverMode == SERVER_EPAS) || (serverMode == SERVER_EPAS && other.serverMode == SERVER_EACT) || (serverMode == SERVER_ACTIVE && other.serverMode == SERVER_PASSIVE) || (serverMode == SERVER_PASSIVE && other.serverMode == SERVER_ACTIVE))) { throw new ClientException(ClientException.BAD_SERVER_MODE, "One server must be active" + " and other must be passive"); } } } } // compareServerMode /** * @return true if this session requires GridFTP extensions; false if it * only requires vanilla FTP. */ public boolean needsGridFTP() { return (parallel > 1 || transferMode == MODE_EBLOCK || (serverMode == GridFTPSession.SERVER_EPAS || serverMode == GridFTPSession.SERVER_EACT)); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/HostPort.java000066400000000000000000000061561241116057200274020ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.util.StringTokenizer; import java.net.InetAddress; /** * Utility class for parsing and converting host-port information from PASV * and PORT ftp commands. */ public class HostPort { private int [] datainfo; protected HostPort() { } /** * Parses host-port from passive mode reply message. * Note that the argument is not the whole message, but * only the content of the brackets: * h1,h2,h3,h4,p1,p2 * * @param passiveReplyMessage reply message for the PASV command */ public HostPort(String passiveReplyMessage) { datainfo = new int[6]; int i = 0; StringTokenizer tokens = new StringTokenizer(passiveReplyMessage, ","); while(tokens.hasMoreTokens()) { datainfo[i] = Integer.parseInt( tokens.nextToken().trim() ); i++; } } /** * Creates the HostPort object from specified ip address * and port number. * * @param addr ip address * @param port port number */ public HostPort(InetAddress addr, int port) { this(addr.getHostAddress(), port); } /** * Creates the HostPort object from specified ip address * and port number. * @param ipAddress ip address * @param port port number */ public HostPort(String ipAddress, int port) { datainfo = new int[6]; int i = 0; StringTokenizer tokens = new StringTokenizer(ipAddress, "."); while(tokens.hasMoreTokens()) { datainfo[i] = Integer.parseInt( (String)tokens.nextToken() ); i++; } if (i != 4) { throw new IllegalArgumentException("Invalid ip address: " + ipAddress); } datainfo[4] = port/256; datainfo[5] = port - datainfo[4]*256; } /** * Returns the port number * * @return port number */ public int getPort() { return datainfo[4]*256 + datainfo[5]; } /** * Returns the ip address in the form "h1.h2.h3.h4" * * @return ip address */ public String getHost() { return datainfo[0] + "." + datainfo[1] + "." + datainfo[2] + "." + datainfo[3]; } /** * Returns the host-port information in the * format used by PORT command. * (h1,h2,h3,h4,p1,p2) * * @return host-port information in PORT command * representation. */ public String toFtpCmdArgument() { StringBuffer msg = new StringBuffer(); for (int i=0;i * * @param passiveReplyMessage reply message for the EPSV command */ public HostPort6(String passiveReplyMessage) { Parser tokens = new Parser(passiveReplyMessage); String token = null; token = tokens.nextToken().trim(); if (token.length() == 0) { // do nothing assume the same as control channel } else if (token.equals(IPv4)) { this.version = IPv4; } else if (token.equals(IPv6)) { this.version = IPv6; } else { throw new IllegalArgumentException("Invalid network protocol: " + token); } token = tokens.nextToken().trim(); if (token.length() == 0) { // do nothing assume the same as control channel } else { this.host = token; } token = tokens.nextToken().trim(); if (token.length() == 0) { throw new IllegalArgumentException("Port number is required"); } this.port = Integer.parseInt(token); } private static class Parser { String line; int offset = 0; public Parser(String line) { this.line = line; } public String nextToken() { int start = line.indexOf('|', this.offset); if (start == -1) { throw new IllegalArgumentException("Formatting error"); } int end = line.indexOf('|', start+1); if (end == -1) { throw new IllegalArgumentException("Formatting error"); } this.offset = end; return line.substring(start+1, end); } } /** * Returns the port number * * @return port number */ public int getPort() { return this.port; } /** * Sets the host address * * @param host the host address */ public void setHost(String host) { this.host = host; } /** * Returns the host address * * @return host address */ public String getHost() { return this.host; } /** * Returns the address version * * @return address version */ public String getVersion() { return this.version; } /** * Sets the address version * * @param version the address version */ public void setVersion(String version) { this.version = version; } /** * Returns the host-port information in the * format used by EPRT command. * * * @return host-port information in EPRT command * representation. */ public String toFtpCmdArgument() { StringBuffer msg = new StringBuffer(); msg.append("|"); if (this.version != null) { msg.append(this.version); } msg.append("|"); if (this.host != null) { msg.append(this.host); } msg.append("|"); msg.append(String.valueOf(this.port)); msg.append("|"); return msg.toString(); } public static String getIPAddressVersion(String address) { return (address.indexOf(':') == -1) ? IPv4 : IPv6; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/HostPortList.java000066400000000000000000000127541241116057200302370ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; import java.io.StringReader; import java.io.BufferedReader; import java.util.Vector; /** * Utility class for parsing * and converting host-port information from SPAS * and SPOR FTP commands. Represents a list of host-port pairs. */ public class HostPortList { /* This class is internally represented as String or as vector. In case of third party transfer, there is no need to convert the String to vector, since we receive a string from server A and send a similar string to server B. However in client-server transfer, we do need internal vector representation. Internally, if the constructor gets string as parameter, the default representation remains string. Whenever you call a modifier method like add(), the string becomes out of date and then the vector is used. The string can become up to date again if updateString() called. The vector is not usable until updateVector() is first called, and then it always remains up to date. */ //internal string, in form of parameters to SPOR command private String sporCommandParam; private Vector vector = null; /** * Parses host-port from the reply to SPAS command. * * @param spasReplyMsg reply message for the SPAS command */ public HostPortList(String spasReplyMsg) { try { parseFormat(spasReplyMsg, false); } catch (IOException e) { // this should never happen } } /** * Creates an empty list **/ public HostPortList() { } /** * Adds an element to the list **/ public void add(HostPort hp) { if (this.vector == null) { this.vector = new Vector(); } this.vector.add(hp); this.sporCommandParam = null; } /** * @return number of elements in the list **/ public int size() { return (this.vector == null) ? 0 : this.vector.size(); } /** * @return element of the specified index **/ public HostPort get(int index) { return (this.vector == null) ? null : (HostPort)this.vector.elementAt(index); } /** * Returns the host-port infromation in the * format used by SPOR command. * * @return host-port information in SPOR command parameter * representation. */ public String toFtpCmdArgument() { if (this.sporCommandParam == null && this.vector != null) { StringBuffer cmd = new StringBuffer(); for (int i = 0; i < this.vector.size(); i ++) { HostPort hp = (HostPort)this.vector.get(i); if (i != 0) { cmd.append(' '); } cmd.append(hp.toFtpCmdArgument()); } this.sporCommandParam = cmd.toString(); } return this.sporCommandParam; } private void parseFormat(String msg, boolean ipv6) throws IOException { BufferedReader reader = new BufferedReader(new StringReader(msg)); StringBuffer command = null; String line = null; line = reader.readLine(); while( (line = reader.readLine()) != null) { if (!line.startsWith(" ")) { if (line.startsWith("229")) { break; } else { throw new IllegalArgumentException( "Not a proper reply message " + "->" + line + "<-"); } } line = line.trim(); if (line.startsWith("229")) { break; } if (this.vector == null) { this.vector = new Vector(); } if (ipv6) { this.vector.add(new HostPort6(line)); } else { this.vector.add(new HostPort(line)); } if (command == null) { command = new StringBuffer(); } else { command.append(' '); } command.append(line); } if (this.vector == null) { throw new IllegalArgumentException( "Not a proper reply message " + "->" + line + "<-"); } this.sporCommandParam = command.toString(); } public static HostPortList parseIPv6Format(String message) { HostPortList list = new HostPortList(); try { list.parseFormat(message, true); } catch (IOException e) { // this should never happen } return list; } public static HostPortList parseIPv4Format(String message) { HostPortList list = new HostPortList(); try { list.parseFormat(message, false); } catch (IOException e) { // this should never happen } return list; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/InputStreamDataSink.java000066400000000000000000000062101241116057200315010ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; import java.io.InputStream; import java.io.EOFException; import java.io.InterruptedIOException; import org.globus.util.CircularBuffer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // if write() blocked, it will not be unblocked by close public class InputStreamDataSink implements DataSink { protected CircularBuffer buffers = null; private DataInputStream in; private boolean closed = false; public InputStreamDataSink() { this.buffers = new CircularBuffer(5); this.in = new DataInputStream(); } public void write(Buffer buffer) throws IOException { if (isClosed()) { throw new EOFException(); } try { if (!buffers.put(buffer)) { throw new EOFException(); } } catch (InterruptedException e) { throw new InterruptedIOException(); } } public void close() throws IOException { // will let get run until it returns null // and will throe EOFException on next put call // but existing put calls will not be interrupted setClosed(); this.buffers.closePut(); } private synchronized void setClosed() { this.closed = true; } private synchronized boolean isClosed() { return this.closed; } public InputStream getInputStream() { return this.in; } class DataInputStream extends InputStream { protected byte[] buff; protected int index; protected int length; public synchronized int read(byte [] data) throws IOException { return read(data, 0, data.length); } public synchronized int read(byte[] data, int off, int len) throws IOException { if (!ensureData()) { return -1; } int max = (index + len > length) ? length - index : len; System.arraycopy(buff, index, data, off, max); index += max; return max; } public synchronized int read() throws IOException { if (!ensureData()) { return -1; } return buff[index++] & 0xff; } public void close() throws IOException { buffers.interruptBoth(); } protected synchronized boolean ensureData() throws IOException { if (buffers.isGetInterrupted()) { return false; } if (this.length == this.index) { try { Buffer buf = (Buffer)buffers.get(); if (buf == null) { return false; } this.index = 0; this.length = buf.getLength(); this.buff = buf.getBuffer(); } catch (InterruptedException e) { // that should never happen throw new InterruptedIOException(); } } return true; } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/Marker.java000066400000000000000000000013731241116057200270350ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** FTP and GridFTP markers (restart markers, performance markers) all extend this interface. **/ public interface Marker {} JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/MarkerListener.java000066400000000000000000000021601241116057200305360ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** Represents an entity capable of receiving incoming markers. Implement it to provide your own methods of analyzing markers. @see FTPClient#transfer(String, FTPClient, String, boolean, MarkerListener) @see GridFTPClient#extendedTransfer(String, GridFTPClient, String, MarkerListener) **/ public interface MarkerListener{ /** When writing your implementation, assume this method being called whenever a marker arrives. **/ public void markerArrived(Marker m); } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/MlsxEntry.java000066400000000000000000000112211241116057200275520ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.TimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.ftp.exception.FTPException; /** * * * * * */ public class MlsxEntry { private static Log logger = LogFactory.getLog(MlsxEntry.class.getName()); private static SimpleDateFormat dateFormatter = null; public static final String SIZE = "size"; public static final String MODIFY = "modify"; public static final String CREATE = "create"; public static final String TYPE = "type"; public static final String UNIQUE = "unique"; public static final String PERM = "perm"; public static final String LANG = "lang"; public static final String MEDIA_TYPE = "media-type"; public static final String CHARSET = "charset"; public static final String UNIX_MODE = "unix.mode"; public static final String UNIX_OWNER = "unix.owner"; public static final String UNIX_GROUP = "unix.group"; public static final String UNIX_SLINK = "unix.slink"; public static final String UNIX_UID = "unix.uid"; public static final String UNIX_GID = "unix.gid"; public static final String ERROR = "error"; public static final String TYPE_FILE = "file"; public static final String TYPE_CDIR = "cdir"; public static final String TYPE_PDIR = "pdir"; public static final String TYPE_DIR = "dir"; public static final String TYPE_SLINK = "slink"; public static final String ERROR_OPENFAILED = "OpenFailed"; public static final String ERROR_INVALIDLINK = "InvalidLink"; private String fileName = null; private Hashtable facts = new Hashtable(); /** * Constructor for MlsxEntry. * @param mlsxEntry * @throws FTPException */ public MlsxEntry(String mlsxEntry) throws FTPException { this.parse(mlsxEntry); } /** * Method parse. * @param mlsxEntry */ private void parse(String mlsxEntry) { StringTokenizer tokenizer = new StringTokenizer(mlsxEntry, ";"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) { //next fact String fact = token; logger.debug("fact: " + fact); int equalSign = fact.indexOf('='); String factName = fact.substring(0, equalSign).trim().toLowerCase(); String factValue = fact.substring(equalSign + 1, fact.length()); facts.put(factName, factValue); } else { // name: trim leading space this.fileName = token.substring(1, token.length()); logger.debug("name: " + fileName); } } } public void set(String factName, String factValue) { facts.put(factName, factValue); } public String getFileName() { return this.fileName; } public String get(String factName) { return (String) facts.get(factName); } public Date getDate(String factName) { Date d = null; synchronized (dateFormatter) { try { d = dateFormatter.parse((String)facts.get(factName)); } catch (ParseException e) { d = null; } } return d; } public String toString() { StringBuffer buf = new StringBuffer(); Enumeration e = facts.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = (String)facts.get(key); buf.append( key + "=" + value +";"); } buf.append( " " + fileName); return buf.toString(); } static { dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss"); dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/MlsxEntryWriter.java000066400000000000000000000010131241116057200307450ustar00rootroot00000000000000package org.globus.ftp; import java.io.IOException; /** * The MlsxEntryWriter provides a callback interface for writing * individual MlsxEntry items from a long directory listing (for * example, using the MLSR command). * */ public interface MlsxEntryWriter { /** * Writes a single entry from the stream. * * @param entry the file/directory entry */ public void write(MlsxEntry entry) throws IOException; /** * Notifies the writer that the stream of entries has ended. * */ public void close(); } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/MultipleTransferComplete.java000066400000000000000000000014511241116057200326020ustar00rootroot00000000000000package org.globus.ftp; public class MultipleTransferComplete { public String remoteSrcFile; public String remoteDstFile; public GridFTPClient source; public GridFTPClient destination; public int index; public MultipleTransferComplete( String remoteSrcFile, String remoteDstFile, GridFTPClient source, GridFTPClient destination, int index) { this.remoteSrcFile = remoteSrcFile; this.remoteDstFile = remoteDstFile; this.source = source; this.destination = destination; this.index = index; } } MultipleTransferCompleteListener.java000066400000000000000000000013661241116057200342360ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** **/ public interface MultipleTransferCompleteListener { public void transferComplete(MultipleTransferComplete mtc); } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/Options.java000066400000000000000000000023321241116057200272430ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** Represents FTP command options, as defined in RFC 2389. */ public abstract class Options { protected String command; /** @param cmd command whose options are represent by this object */ public Options(String cmd) { command = cmd; } public String toFtpCmdArgument() { return command + " " + getArgument(); } /** Subclasses should implement this method. It should return the right side of the options line, in the format of OPTS command. It should not include the command name. */ public abstract String getArgument(); } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/OutputStreamDataSource.java000066400000000000000000000071311241116057200322410ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import java.io.IOException; import java.io.OutputStream; import java.io.EOFException; import java.io.InterruptedIOException; import org.globus.util.CircularBuffer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class OutputStreamDataSource implements DataSource { protected CircularBuffer buffers = null; private DataOutputStream out; public OutputStreamDataSource(int size) { this.buffers = new CircularBuffer(5); this.out = new DataOutputStream(size); } // returns null if EOF public Buffer read() throws IOException { try { return (Buffer)this.buffers.get(); } catch (InterruptedException e) { // that should not happen throw new InterruptedIOException(); } } public void close() throws IOException { this.buffers.interruptBoth(); this.out.setClosed(); } public OutputStream getOutputStream() { return this.out; } public long totalSize() throws IOException { return -1; } // if write() is blocked, it will not be unblocked by close() class DataOutputStream extends OutputStream { protected byte[] buff; protected int index; private boolean closed = false; public DataOutputStream(int size) { this.buff = new byte[size]; this.index = 0; } public void write(byte[] data) throws IOException { write(data, 0, data.length); } public synchronized void write(byte[] data, int off, int len) throws IOException { if (isClosed()) { throw new EOFException(); } int max; while (len > 0) { if (this.index + len > this.buff.length) { max = (this.buff.length - this.index); System.arraycopy(data, off, this.buff, this.index, max); this.index += max; flush(); len -= max; off += max; } else { System.arraycopy(data, off, this.buff, this.index, len); this.index += len; break; } } } public synchronized void write(int b) throws IOException { if (isClosed()) { throw new EOFException(); } if (this.index == this.buff.length) { flush(); } buff[index++] = (byte)b; } public synchronized void flush() throws IOException { if (this.index == 0) { return; } byte [] data = new byte[this.index]; System.arraycopy(this.buff, 0, data, 0, this.index); Buffer b = new Buffer(data, this.index); try { if (!buffers.put(b)) { throw new EOFException(); } } catch (InterruptedException e) { // that should never happen throw new InterruptedIOException(); } this.index = 0; } public void close() throws IOException { flush(); // will let get run until it returns null // and will throe EOFException on next put call // but existing put calls will not be interrupted setClosed(); buffers.closePut(); } protected synchronized void setClosed() { this.closed = true; } private synchronized boolean isClosed() { return this.closed; } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/PerfMarker.java000066400000000000000000000114361241116057200276530ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import org.globus.ftp.exception.PerfMarkerException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.StringTokenizer; /** Represents GridFTP performance marker. Use getter methods to access its parameters. **/ public class PerfMarker implements Marker { private static Log logger = LogFactory.getLog(PerfMarker.class.getName()); protected final String nl = System.getProperty("line.separator"); protected final static int UNDEFINED = -1; // must have timeStamp protected boolean hasTimeStamp = false; protected double timeStamp = UNDEFINED; protected boolean hasStripeIndex = false; protected long stripeIndex = UNDEFINED; protected boolean hasStripeBytesTransferred = false; protected long stripeBytesTransferred = UNDEFINED; protected boolean hasTotalStripeCount = false; protected long totalStripeCount = UNDEFINED; /** @param msg an FTP reply message containing the perf marker (not the reply itself!) **/ public PerfMarker(String msg) throws IllegalArgumentException{ StringTokenizer tokens = new StringTokenizer(msg, nl); if (! tokens.nextToken().trim().equals("Perf Marker")) { badMsg("should start with Perf Marker'", msg); } if (! tokens.hasMoreTokens()) { badMsg("No parameters", msg); } //traverse lines while(tokens.hasMoreTokens()) { //line = "name : value" StringTokenizer line = new StringTokenizer(tokens.nextToken(), ":"); if (! line.hasMoreTokens()) { badMsg("one of lines empty", msg); } // name String name = line.nextToken(); if (! name.startsWith(" ")) { //last line if (! name.startsWith("112")) { //that wasn't a 112 message! logger.debug("ending line: ->" + name +"<-"); badMsg("No ending '112' line", msg); } break; } name = name.trim(); if (! line.hasMoreTokens()) { badMsg("one of parameters has no value", msg); } // value String value = line.nextToken().trim(); if(name.equals( "Timestamp")) { try { timeStamp = Double.parseDouble(value); hasTimeStamp = true; } catch ( NumberFormatException e) { badMsg("Not double value:" + value, msg); } } else if (name.equals("Stripe Index")) { try { stripeIndex = Long.parseLong(value); hasStripeIndex = true; } catch ( NumberFormatException e) { badMsg("Not long value:" + value, msg); } } else if (name.equals("Stripe Bytes Transferred")) { try { stripeBytesTransferred = Long.parseLong(value); hasStripeBytesTransferred = true; } catch ( NumberFormatException e) { badMsg("Not long value:" + value, msg); } } else if (name.equals("Total Stripe Count")) { try { totalStripeCount = Long.parseLong(value); hasTotalStripeCount = true; } catch ( NumberFormatException e) { badMsg("Not long value:" + value, msg); } } }//traverse lines //marker must contain time stamp if (!hasTimeStamp) { badMsg("no timestamp", msg); } }//PerfMarker private void badMsg(String why, String msg) { throw new IllegalArgumentException( "argument is not FTP 112 reply message (" + why + ": ->" + msg + "<-"); } public boolean hasStripeIndex() { return hasStripeIndex; } public boolean hasStripeBytesTransferred() { return hasStripeBytesTransferred; } public boolean hasTotalStripeCount() { return hasTotalStripeCount; } public double getTimeStamp() { return timeStamp; } public long getStripeIndex() throws PerfMarkerException { if (! hasStripeIndex) { throw new PerfMarkerException( PerfMarkerException.NO_SUCH_PARAMETER); } return stripeIndex; } public long getStripeBytesTransferred() throws PerfMarkerException { if (! hasStripeBytesTransferred) { throw new PerfMarkerException( PerfMarkerException.NO_SUCH_PARAMETER); } return stripeBytesTransferred; } public long getTotalStripeCount() throws PerfMarkerException { if (! hasTotalStripeCount) { throw new PerfMarkerException( PerfMarkerException.NO_SUCH_PARAMETER); } return totalStripeCount; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/RestartData.java000066400000000000000000000017031241116057200300270ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** Represents a container for restart data capable for representing it in the format of FTP REST command argument. **/ public interface RestartData { /** @return the restart data in the format of REST command argument. For instance (in GridFTP) "4-50,62-75" **/ public String toFtpCmdArgument(); } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/RestartMarker.java000066400000000000000000000013201241116057200303720ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; public interface RestartMarker extends Marker{ public String toFtpCmdArgument(); } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/RetrieveOptions.java000066400000000000000000000042171241116057200307550ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** Options to the command RETR, as defined in GridFTP. In client-server transfers, this implementation does not support starting/min/max parallelism. All three values must be equal. In third party transfers, this is not necessary. */ public class RetrieveOptions extends Options { protected int startParallelism; protected int minParallelism; protected int maxParallelism; public RetrieveOptions() { this(1); } /** @param parallelism required min, max, and starting parallelism */ public RetrieveOptions(int parallelism) { super("RETR"); this.startParallelism = parallelism; this.minParallelism = parallelism; this.maxParallelism = parallelism; } /** Use only in third party mode. */ public void setStartingParallelism(int startParallelism) { this.startParallelism = startParallelism; } /** Use only in third party mode. */ public void setMinParallelism(int minParallelism) { this.minParallelism = minParallelism; } /** Use only in third party mode. */ public void setMaxParallelism(int maxParallelism) { this.maxParallelism = maxParallelism; } public int getStartingParallelism() { return this.startParallelism; } public int getMinParallelism() { return this.minParallelism; } public int getMaxParallelism() { return this.maxParallelism; } public String getArgument() { return "Parallelism=" + startParallelism + "," + minParallelism + "," + maxParallelism + ";"; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/Session.java000066400000000000000000000137761241116057200272510ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; import org.globus.ftp.exception.ClientException; /** * Represents parameters of an FTP session between a client and a server. For * instance, a third party transfer will be represented by two sessions: one * between the client and the server A, and the other between the client and the * server B.
    * Public static variables are interpreted as follows: *
      *
    • prefix TYPE denotes transfer type *
    • prefix MODE denotes transfer mode *
    • prefix SERVER denotes server mode *
    */ public class Session { public static final int TYPE_IMAGE = 1; public static final int TYPE_ASCII = 2; public static final int TYPE_LOCAL = 3; public static final int TYPE_EBCDIC = 4; public static final int MODE_STREAM = 1; public static final int MODE_BLOCK = 2; public static final int SERVER_PASSIVE = 1; public static final int SERVER_ACTIVE = 2; // may apply anywhere where // the variables above do apply public static final int SERVER_DEFAULT = -1; // variables that hold server state; // used mostly in complex functions like 3rd party transfer // equal to MODE_xxx public int transferMode = MODE_STREAM; // equal to TYPE_xxx public int transferType = TYPE_ASCII; /** * Can be SERVER_PASSIVE, SERVER_ACTIVE, or SERVER_DEFAULT. The latter means * that the mode has not been set explicitly, so the server should act as * default: passive on the standard port L-1. */ public int serverMode = SERVER_DEFAULT; public int protectionBufferSize = SERVER_DEFAULT; public boolean authorized = false; /* caches FEAT command reply */ public FeatureList featureList = null; public HostPort serverAddress = null; public static final int DEFAULT_MAX_WAIT = 1000 * 300; // 300 secs public static final int DEFAULT_WAIT_DELAY = 2000; /** * This variable directly affects only the client. After requesting data * transfer, client will wait on the control channel maxWait miliseconds, * polling for replies every waitDelay seconds. If reply does not arrive * after maxWait, client will abort. */ public int maxWait = DEFAULT_MAX_WAIT; /** * This variable directly affects only the client. After requesting data * transfer, client will wait on the control channel maxWait miliseconds, * polling for replies every waitDelay seconds. If reply does not arrive * after maxWait, client will abort. */ public int waitDelay = DEFAULT_WAIT_DELAY; /** * Ensures that settings of 2 servers match each other so that the servers * are capable of performing a transfer between themselves. The parameters * of both sessions must either both be set correctly, or both undefined. *
    * Detailed rules: Two sessions match if their transfer type, mode, and * protection buffer sizes match. Additionally, if one party is passive, the * other must be active. If any of the variables are set to SERVER_DEFAULT, * sessions are considered matching. * * @throws ClientException * if sessions do not match */ public void matches(Session other) throws ClientException { compareTransferParams(other); compareServerMode(other); } /** * defines how to compare parameters: authorized, PBSZ, MODE, TYPE */ protected void compareTransferParams(Session other) throws ClientException { if (!this.authorized || !other.authorized) throw new ClientException(ClientException.NOT_AUTHORIZED, "Need to perform authorization first"); // synchronize protection buffer size if (this.protectionBufferSize != other.protectionBufferSize) { throw new ClientException(ClientException.PBSZ_DIFFER); } // synchronize type if (this.transferType != other.transferType) { throw new ClientException(ClientException.TRANSFER_TYPE_DIFFER); } // synchronize type if (this.transferMode != other.transferMode) { throw new ClientException(ClientException.TRANSFER_MODE_DIFFER); } } /** * checks that active / passive sides are correctly set */ protected void compareServerMode(Session other) throws ClientException { if (serverMode == SERVER_DEFAULT && other.serverMode == SERVER_DEFAULT) { // this is OK } else { // active and passive side had already been set; // make sure that it has been done correctly: // either server can be active // providing that the other is passive // if this server mode has been defined, // but the other has not, we can't proceed if (this.serverMode == SERVER_DEFAULT || other.serverMode == SERVER_DEFAULT) { throw new ClientException(ClientException.BAD_SERVER_MODE, "Only one server has been defined as active or passive"); } // both servers cannot have the same mode if (other.serverMode == this.serverMode) { String modeStr = (this.serverMode == SERVER_PASSIVE) ? "passive" : "active"; throw new ClientException(ClientException.BAD_SERVER_MODE, "Both servers are " + modeStr); } } }// compareServerMode } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/StreamModeRestartMarker.java000066400000000000000000000017271241116057200323660ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** Represents FTP stream mode restart marker, as defined in RFC 959. Not used. */ public class StreamModeRestartMarker implements Marker, RestartData { protected long offset; public StreamModeRestartMarker(long offset) { this.offset = offset; } public String toFtpCmdArgument() { return String.valueOf(offset); } } SubjectDataChannelAuthentication.java000066400000000000000000000017171241116057200341210ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp; /** Represents subject data channel authentication. */ public class SubjectDataChannelAuthentication extends DataChannelAuthentication { public SubjectDataChannelAuthentication(String subject) { super(); if (subject == null) { throw new IllegalArgumentException("Subject is null"); } setArgument("S " + subject); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/app/000077500000000000000000000000001241116057200255255ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/app/Transfer.java000066400000000000000000000203121241116057200301520ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.app; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.ftp.GridFTPSession; import org.globus.ftp.HostPort; import org.globus.ftp.GridFTPClient; import org.globus.ftp.HostPortList; import org.globus.ftp.RetrieveOptions; import org.globus.ftp.Session; import org.globus.ftp.exception.ServerException; import org.globus.ftp.exception.ClientException; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.HostAuthorization; import org.globus.gsi.gssapi.auth.IdentityAuthorization; /** Represents a single act of a third party transfer of one file. The transfer is performed in the constructor. This class will not be very efficient for transferring many files, because each transfer builds its own control channel connection. Instead, it is appropriate to use this class instances for transfers of single files, or for testing server's capabilities. @see TransferParams */ public class Transfer { static Log logger = LogFactory.getLog(Transfer.class.getName()); public static void main(String[] args) { String sourceServer = null, sourceDir = null, sourceFile = null, destServer = null, destDir= null, destFile= null; int sourcePort = 0, destPort = 0; try { if ( args.length < 8) { throw new Exception(); } sourceServer = args[0]; sourcePort = Integer.parseInt(args[1]); sourceDir = args[2]; sourceFile = args[3]; destServer = args[4]; destPort = Integer.parseInt(args[5]); destDir = args[6]; destFile = args[7]; } catch (Exception e) { System.err.println("\nUsage:"); System.err.println("Transfer \\"); System.err.println("sourceServer sourcePort sourceDir sourceFile \\"); System.err.println("destServer destPort destDir destFile"); System.exit(-1); } try { logger.info("starting"); TransferParams params = new TransferParams(); Transfer transfer = new Transfer(sourceServer, sourcePort, sourceDir, sourceFile, destServer, destPort, destDir, destFile, params); } catch (Exception e) { System.err.println("Transfer failed: " + e.getMessage()); e.printStackTrace(); System.exit(-1); } } /** Constructor, performing a single third party transfer from (grid)ftp://sourceServer:sourcePort/sourceDir/sourceFile to (grid)ftp://destServer:destPort/destDir/destFile. Any protocol related parameters should be passed in the params object. If params is null, default GridFTP parameters are assumed. */ public Transfer(String sourceServer, int sourcePort, String sourceDir, String sourceFile, String destServer, int destPort, String destDir, String destFile, TransferParams params) throws IOException, ServerException, ClientException { this(sourceServer, sourcePort, (String)null, sourceDir, sourceFile, destServer, destPort, (String)null, destDir, destFile, params); } /** Constructor, performing a single third party transfer from (grid)ftp://sourceServer:sourcePort/sourceDir/sourceFile to (grid)ftp://destServer:destPort/destDir/destFile. Any protocol related parameters should be passed in the params object. If params is null, default GridFTP parameters are assumed. */ public Transfer(String sourceServer, int sourcePort, String sourceSubject, String sourceDir, String sourceFile, String destServer, int destPort, String destSubject, String destDir, String destFile, TransferParams params) throws IOException, ServerException, ClientException { this(sourceServer, sourcePort, getAuthorization(sourceSubject), sourceDir + "/" + sourceFile, destServer, destPort, getAuthorization(destSubject), destDir + "/" + destFile, params); } /** Constructor, performing a single third party transfer from (grid)ftp://sourceServer:sourcePort/absoluteSourceFile to (grid)ftp://destServer:destPort/absoluteDestFile. Any protocol related parameters should be passed in the params object. If params is null, default GridFTP parameters are assumed. */ public Transfer(String sourceServer, int sourcePort, Authorization sourceSubject, String absoluteSourceFile, String destServer, int destPort, Authorization destSubject, String absoluteDestFile, TransferParams params) throws IOException, ServerException, ClientException{ if (params == null) { params = new TransferParams(); //with default values } GridFTPClient source = new GridFTPClient(sourceServer, sourcePort); source.setAuthorization(sourceSubject); GridFTPClient dest = new GridFTPClient(destServer, destPort); dest.setAuthorization(destSubject); setParams(source, params); setParams(dest, params); GridFTPClient active, passive; if (params.serverMode != Session.SERVER_PASSIVE) { // default active = source; passive = dest; } else { // non default active = dest; passive = source; } if (!params.doStriping) { HostPort hp = passive.setPassive(); active.setActive(hp); } else { HostPortList hpl = passive.setStripedPassive(); active.setStripedActive(hpl); } if (params.transferMode != GridFTPSession.MODE_EBLOCK) { source.transfer(absoluteSourceFile, dest, absoluteDestFile, false, params.markerListener); } else { source.extendedTransfer(absoluteSourceFile, dest, absoluteDestFile, params.markerListener); /* String remoteSrcFile[]; long remoteSrcFileOffset[]; long remoteSrcFileLength[]; String remoteDstFile[]; long remoteDstFileOffset[]; int its = 1000; remoteSrcFile = new String[its]; remoteDstFile = new String[its]; for(int i = 0; i < its; i++) { remoteSrcFile[i] = "/etc/group"; remoteDstFile[i] = "/home/bresnaha/TEST/grp" + new Integer(i).toString(); } source.extendedMultipleTransfer( remoteSrcFile, dest, remoteDstFile, params.markerListener, null); */ } } private static Authorization getAuthorization(String subject) { if (subject == null) { return HostAuthorization.getInstance(); } else { return new IdentityAuthorization(subject); } } private void setParams(GridFTPClient client, final TransferParams params) throws IOException, ServerException{ client.authenticate(params.credential); //okay if null if (params.transferType != Session.SERVER_DEFAULT) { client.setType(params.transferType); } if (params.transferMode != Session.SERVER_DEFAULT) { client.setMode(params.transferMode); } if (params.parallel != Session.SERVER_DEFAULT) { client.setOptions(new RetrieveOptions(params.parallel)); } if (params.protectionBufferSize != Session.SERVER_DEFAULT) { client.setProtectionBufferSize( params.protectionBufferSize); } if (params.dataChannelAuthentication != null) { client.setDataChannelAuthentication( params.dataChannelAuthentication); } if (params.dataChannelProtection != Session.SERVER_DEFAULT) { client.setDataChannelProtection( params.dataChannelProtection); } if (params.TCPBufferSize != Session.SERVER_DEFAULT) { client.setTCPBufferSize(params.TCPBufferSize); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/app/TransferParams.java000066400000000000000000000072761241116057200313340ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.app; import org.globus.ftp.GridFTPSession; import org.globus.ftp.MarkerListener; /** Represents parameters of a transfer. This class should be used in conjunction with class Transfer. You first configure a TransferParams object by setting values directly (parameters are public, there's no getter/setter methods). Then pass this object to a Transfer constructor that will perform the transfer as required.

    In general, the meaning of a parameter values is as follows. A value of SERVER_DEFAULT (in case of integer values) or null (in case of objects) indicate that this parameter should not be explicitly set to the server, and the server will use its defaults. Any other value will be explicitly requested from the server on the control channel.

    For example, if transferMode is set to SERVER_DEFAULT, client will not directly request any transfer mode, and the server should use its default which is stream mode. If transferMode is set to MODE_STREAM, stream mode will be explicitly requested from the server, so it will also use stream mode. To request extended block mode, set transferMode to MODE_EBLOCK.

    Below is a list of parameters that can be set to TransferParams and can affect the transfer:

    • credential - user's credential; use null for default user's credential
    • transferMode - transfer mode
    • transferType - transfer type
    • serverMode - SERVER_ACTIVE (default) if the sending server should be active, otherwise SERVER_PASSIVE (this is illegal with Mode E)
    • parallel - parallelism (integer number of parallel streams)
    • doStriping - set to true to request striping, otherwise false (default)
    • protectionBufferSize - protection buffer size; in GridFTP must be set to something
    • dataChannelAuthentication - DataChannelAuthentication.SELF (default) or DataChannelAuthentication.NONE
    • dataChannelProtection - PROTECTION_CLEAR (default), PROTECTION_SAFE, ...
    • TCPBufferSize - TCP buffer size, default is usually 64 KB
    • markerListener - an object listening for performance and restart markers, null by default
    @see Transfer */ public class TransferParams extends GridFTPSession { public boolean doStriping = false; public MarkerListener markerListener; /** This constructor sets parameters to the GridFTP defaults. If possible, a parameter is not explicitly set, but server defaults are assumed. */ public TransferParams() { credential = null; // use default credential transferMode = MODE_EBLOCK; // must be set; server default would be MODE_STREAM transferType = TYPE_IMAGE; serverMode = SERVER_DEFAULT; parallel = SERVER_DEFAULT; // server default = SERVER_ACTIVE doStriping = false; protectionBufferSize = 16384; // must set to something dataChannelAuthentication =null; // server default = DataChannelAuthentication.SELF; dataChannelProtection = SERVER_DEFAULT; // server default = PROTECTION_CLEAR; TCPBufferSize = SERVER_DEFAULT; markerListener = null; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/000077500000000000000000000000001241116057200253335ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/AbstractDataChannel.java000066400000000000000000000134221241116057200320260ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.util.Map; import java.util.HashMap; import org.globus.ftp.GridFTPSession; import org.globus.ftp.Session; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class AbstractDataChannel implements DataChannel { private static Log logger = LogFactory.getLog(AbstractDataChannel.class.getName()); protected Session session; protected static Map dataHandlers; private static final int SOURCE = 1; private static final int SINK = 2; static { try { // Stream [Image/Ascii] Reader and Writer support registerHandler(Session.MODE_STREAM, Session.TYPE_IMAGE, SOURCE, StreamImageDCReader.class); registerHandler(Session.MODE_STREAM, Session.TYPE_ASCII, SOURCE, StreamAsciiDCReader.class); registerHandler(Session.MODE_STREAM, Session.TYPE_IMAGE, SINK, StreamImageDCWriter.class); registerHandler(Session.MODE_STREAM, Session.TYPE_ASCII, SINK, StreamAsciiDCWriter.class); // EBlock registerHandler(GridFTPSession.MODE_EBLOCK, Session.TYPE_IMAGE, SOURCE, EBlockImageDCReader.class); registerHandler(GridFTPSession.MODE_EBLOCK, Session.TYPE_IMAGE, SINK, EBlockImageDCWriter.class); // EBlock ASCII modes not supported } catch (Exception e) { throw new RuntimeException("Failed to install default data channel handlers: " + e.getMessage()); } } public AbstractDataChannel(Session session) { this.session = session; } public static void registerHandler(int transferMode, int transferType, int type, Class clazz) throws Exception { switch (type) { case SOURCE: if (!DataChannelReader.class.isAssignableFrom(clazz)) { throw new Exception("Incorrect type"); } break; case SINK: if (!DataChannelWriter.class.isAssignableFrom(clazz)) { throw new Exception("Incorrect type"); } break; default: throw new IllegalArgumentException("Type not supported: " + type); } String id = getHandlerID(transferMode, transferType, type); if (dataHandlers == null) { dataHandlers = new HashMap(); } // Allow for overwrites /* if (dataHandlers.get(id) != null) { throw new Exception("Handler already registered."); } */ logger.debug("registering handler for class " + clazz.toString() + "; id = " + id); dataHandlers.put(id, clazz); } /** * Tests if the client supports specified transfer type and mode * (the client can read data in specific type & mode from the * data connection) */ public boolean isDataSourceModeSupported() { String id = getHandlerID(session.transferMode, session.transferType, SOURCE); return (dataHandlers.get(id) != null); } /** * Tests if the client supports specified transfer type and mode * (the client can write data in specific type & mode to the * data connection) */ public boolean isDataSinkModeSupported() { String id = getHandlerID(session.transferMode, session.transferType, SINK); return (dataHandlers.get(id) != null); } // currently context is only needed in case of EBlock mode public DataChannelReader getDataChannelSource(TransferContext context) throws Exception { String id = getHandlerID(session.transferMode, session.transferType, SOURCE); logger.debug("type/mode: " + id); Class clazz = (Class)dataHandlers.get(id); if (clazz == null) { throw new Exception("No data reader for type/mode" + id); } DataChannelReader reader = (DataChannelReader)clazz.newInstance(); if (reader instanceof EBlockAware) { ((EBlockAware)reader).setTransferContext((EBlockParallelTransferContext)context); } return reader; } public DataChannelWriter getDataChannelSink(TransferContext context) throws Exception { String id = getHandlerID(session.transferMode, session.transferType, SINK); Class clazz = (Class)dataHandlers.get(id); if (clazz == null) { throw new Exception("No data reader for type/mode"); } DataChannelWriter writer = (DataChannelWriter)clazz.newInstance(); if (writer instanceof EBlockAware) { ((EBlockAware)writer).setTransferContext((EBlockParallelTransferContext)context); } return writer; } // it is important for this method to handle all possible // mode/transfer types private static String getHandlerID(int transferMode, int transferType, int type) { String id = ""; switch (transferMode) { case Session.MODE_STREAM: id += "S-"; break; case GridFTPSession.MODE_EBLOCK: id += "E-"; break; default: throw new IllegalArgumentException("Mode not supported: " + transferMode); } switch (transferType) { case Session.TYPE_IMAGE: id += "I-"; break; case Session.TYPE_ASCII: id += "A-"; break; default: throw new IllegalArgumentException("Type not supported: " + transferType); } switch (type) { case SOURCE: id += "R"; break; case SINK: id += "W"; break; default: throw new IllegalArgumentException("Type not supported: " + type); } if (id.equals("")) { return null; } return id; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/ActiveConnectTask.java000066400000000000000000000114441241116057200315520ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.globus.ftp.HostPort; import org.globus.ftp.Session; import org.globus.ftp.DataSource; import org.globus.ftp.DataSink; import org.globus.ftp.vanilla.FTPServerFacade; import org.globus.ftp.vanilla.BasicServerControlChannel; import org.globus.net.SocketFactory; import java.net.Socket; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Makes a connection to a remote data channel (FTPClient use only). **/ public class ActiveConnectTask extends Task { protected static Log logger = LogFactory.getLog(ActiveConnectTask.class.getName()); protected HostPort hostPort; protected SocketBox mySocketBox; protected DataSink sink; protected DataSource source; protected BasicServerControlChannel control; protected Session session; protected DataChannelFactory factory; protected TransferContext context; public ActiveConnectTask(HostPort hostPort, DataSink sink, BasicServerControlChannel control, Session session, DataChannelFactory factory, TransferContext context) { this.sink = sink; init(hostPort, control, session, factory, context); } public ActiveConnectTask(HostPort hostPort, DataSource source, BasicServerControlChannel control, Session session, DataChannelFactory factory, TransferContext context) { this.source = source; init(hostPort, control, session, factory, context); } private void init(HostPort hostPort, BasicServerControlChannel control, Session session, DataChannelFactory factory, TransferContext context) { this.hostPort = hostPort; this.session = session; this.control = control; this.factory = factory; this.context = context; } public void execute() { try { DataChannel dataChannel = null; mySocketBox = null; try { mySocketBox = openSocket(); } catch (Exception e) { FTPServerFacade.exceptionToControlChannel( e, "active connection failed", control); return; } try { dataChannel = factory.getDataChannel(session, mySocketBox); if (sink != null) { logger.debug("starting sink data channel"); dataChannel.startTransfer(sink, control, context); } else if (source != null) { logger.debug("starting source data channel"); dataChannel.startTransfer(source, control, context); } else { logger.error("not set"); } } catch (Exception e) { FTPServerFacade.exceptionToControlChannel( e, "active connection to server failed", control); if (dataChannel != null) { dataChannel.close(); } } } catch (Exception e) { FTPServerFacade.cannotPropagateError(e); } } /** Override this to implement authentication **/ protected SocketBox openSocket() throws Exception { SocketBox sBox = new SimpleSocketBox(); SocketFactory factory = SocketFactory.getDefault(); Socket mySocket = factory.createSocket(this.hostPort.getHost(), this.hostPort.getPort()); sBox.setSocket(mySocket); return sBox; } private void close() { // server will by closed by the FTPServerFacade. //try { server.close(); } catch (Exception ignore) {} } public void stop() { close(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/ActiveStartTransferTask.java000066400000000000000000000065421241116057200327660ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.globus.ftp.vanilla.BasicServerControlChannel; import org.globus.ftp.vanilla.FTPServerFacade; import org.globus.ftp.Session; import org.globus.ftp.DataSource; import org.globus.ftp.DataSink; import org.globus.ftp.HostPort; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** This task will start the transfer on the supplied socket. The socket is assumed to have been already connected to the remote server (for instance, by active connect task). It is little tricky: it will cause data channel to start a new thread. By the time this task completes, the new thread is running the transfer. Any resulting exceptions are piped to the local control channel. **/ public class ActiveStartTransferTask extends Task { static Log logger = LogFactory.getLog(ActiveStartTransferTask.class.getName()); HostPort hostPort; BasicServerControlChannel control; protected static final int STOR = 1, RETR = 2; int operation; DataSink sink; DataSource source; SocketBox box; Session session; DataChannelFactory factory; TransferContext context; public ActiveStartTransferTask( DataSink sink, BasicServerControlChannel control, SocketBox box, Session session, DataChannelFactory factory, TransferContext context) { this.sink = sink; init(STOR, control, box, session, factory, context); } public ActiveStartTransferTask( DataSource source, BasicServerControlChannel control, SocketBox box, Session session, DataChannelFactory factory, TransferContext context) { this.source = source; init(RETR, control, box, session, factory, context); } private void init( int operation, BasicServerControlChannel control, SocketBox box, Session session, DataChannelFactory factory, TransferContext context) { if (box == null) { throw new IllegalArgumentException("Socket box is null"); } if (control == null) { throw new IllegalArgumentException("Control channel is null"); } this.factory = factory; this.session = session; this.operation = operation; this.control = control; this.box = box; this.context = context; } public void execute() { try { try { if (box.getSocket() == null) { throw new IllegalArgumentException("socket is null"); } logger.debug("active start transfer task executing"); DataChannel dChannel = factory.getDataChannel(session, box); if (operation == STOR) { dChannel.startTransfer(sink, control, context); } else { dChannel.startTransfer(source, control, context); } } catch (Exception e) { FTPServerFacade.exceptionToControlChannel( e, "startTransfer() failed", control); } } catch (Exception e) { FTPServerFacade.cannotPropagateError(e); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/AsciiTranslator.java000066400000000000000000000054641241116057200313110ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.io.ByteArrayOutputStream; import org.globus.ftp.Buffer; public class AsciiTranslator { public static final byte[] CRLF = {'\r', '\n'}; protected boolean possibleBreak = false; /* enables checking for \r\n */ protected boolean rnSep; /* enables checking for \n */ protected boolean nSep; protected byte[] lineSep; protected final static byte[] systemLineSep; static { systemLineSep = System.getProperty("line.separator").getBytes(); } /** * Output tokens with system specific line separators */ public AsciiTranslator(boolean rnSep, boolean nSep) { this(rnSep, nSep, systemLineSep); } public AsciiTranslator(boolean rnSep, boolean nSep, byte[] lineSeparator) { this.rnSep = rnSep; this.nSep = nSep; this.lineSep = lineSeparator; } public Buffer translate(Buffer buffer) { // TODO: This can be optimized if destination line separator // is the same byte[] buf = buffer.getBuffer(); int len = buffer.getLength(); int bufLastPos = 0; ByteArrayOutputStream byteArray = new ByteArrayOutputStream(len); if (possibleBreak) { if (len > 0 && buf[0] == '\n') { byteArray.write(lineSep, 0, lineSep.length); bufLastPos = 1; } else { byteArray.write('\r'); } possibleBreak = false; } byte ch; for (int i=bufLastPos;i In previous version, the data channel would perform socket initialization (server.accept() etc.). This is now done by the facade's manager thread, so it can start several data channels. **/ public class SimpleDataChannel extends AbstractDataChannel { protected static Log logger = LogFactory.getLog(SimpleDataChannel.class.getName()); protected SocketBox socketBox; protected TransferThread transferThread; protected TransferThreadFactory transferThreadFactory; /** @param socketBox should be opened and ready for comunication **/ public SimpleDataChannel(Session session, SocketBox socketBox) { super(session); if (socketBox == null) { throw new IllegalArgumentException("socketBox is null"); } if (socketBox.getSocket() == null) { throw new IllegalArgumentException("socket is null"); } if (session == null) { throw new IllegalArgumentException("session is null"); } this.socketBox = socketBox; this.transferThreadFactory = new SimpleTransferThreadFactory(); } public void close() throws IOException { if (transferThread != null) { transferThread.interrupt(); // wait till thread dies try { transferThread.join(); } catch (InterruptedException e) { } } // thread should clean up after itself, // but let's check it socketBox.setSocket(null); } public void startTransfer(DataSink sink, BasicServerControlChannel localControlChannel, TransferContext context) throws Exception { transferThread = transferThreadFactory.getTransferSinkThread(this, socketBox, sink, localControlChannel, context); transferThread.start(); } public void startTransfer(DataSource source, BasicServerControlChannel localControlChannel, TransferContext context) throws Exception { transferThread = transferThreadFactory.getTransferSourceThread(this, socketBox, source, localControlChannel, context); transferThread.start(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/SimpleDataChannelFactory.java000066400000000000000000000015471241116057200330510ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.globus.ftp.Session; public class SimpleDataChannelFactory implements DataChannelFactory { public DataChannel getDataChannel(Session state, SocketBox socketBox) { return new SimpleDataChannel(state, socketBox); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/SimpleSocketBox.java000066400000000000000000000027501241116057200312550ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.io.IOException; import java.net.Socket; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SimpleSocketBox implements SocketBox { private static Log logger = LogFactory.getLog(SimpleSocketBox.class.getName()); protected Socket socket; /** * @see org.globus.ftp.dc.SocketBox#setSocket(Socket) */ public void setSocket(Socket newSocket) { if (newSocket == null) { logger.debug("Setting socket to null"); closeSocket(); } else { logger.debug("Setting socket"); } this.socket = newSocket; } public Socket getSocket() { return this.socket; } private void closeSocket() { if (this.socket != null) { try { this.socket.close(); } catch (IOException e) {} } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/SimpleTransferContext.java000066400000000000000000000021471241116057200325050ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; /** transfer context for single threaded transfers using 1 data channel. **/ public class SimpleTransferContext implements TransferContext { private static SimpleTransferContext singleton = new SimpleTransferContext(); /** return the default instance of this class **/ public static TransferContext getDefault() { return singleton; } /** @return always non-null **/ public Object getQuitToken() { return new Object(); } } SimpleTransferThreadFactory.java000066400000000000000000000031001241116057200335270ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.globus.ftp.DataSource; import org.globus.ftp.DataSink; import org.globus.ftp.vanilla.BasicServerControlChannel; public class SimpleTransferThreadFactory implements TransferThreadFactory { public TransferThread getTransferSinkThread(DataChannel dataChannel, SocketBox socketBox, DataSink sink, BasicServerControlChannel localControlChannel, TransferContext context) throws Exception { return new TransferSinkThread((SimpleDataChannel)dataChannel, socketBox, sink, localControlChannel, context); } public TransferThread getTransferSourceThread(DataChannel dataChannel, SocketBox socketBox, DataSource source, BasicServerControlChannel localControlChannel, TransferContext context) throws Exception { return new TransferSourceThread((SimpleDataChannel)dataChannel, socketBox, source, localControlChannel, context); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/SocketBox.java000066400000000000000000000013721241116057200301020ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.net.Socket; public interface SocketBox { public void setSocket(Socket s); public Socket getSocket(); } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/SocketOperator.java000066400000000000000000000014251241116057200311440ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; /** Callback operating on a socketBox. Used in SocketPool. */ public interface SocketOperator { public void operate(SocketBox s) throws Exception; } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/SocketPool.java000066400000000000000000000150041241116057200302600ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Represents a set of open sockets that are being cached for subsequent transfers. * CheckIn() a socket to add it to the pool. Other threads can use it. CheckOut() a socket to mark it busy; it will remain in the pool but noone * else can check it out. Finally, you can remove a socket from the pool, in which case the pool will remove it from all its references. */ public class SocketPool { private static Log logger = LogFactory.getLog(SocketPool.class.getName()); protected Hashtable allSockets = new Hashtable(); protected Hashtable freeSockets = new Hashtable(); protected Hashtable busySockets = new Hashtable(); /** * Constructor for SocketPool. */ public SocketPool() { } /** add socketBox to the pool. Depending on its state, it will be added to free or busy sockets. */ public synchronized void add(SocketBox sb) { int status = ((ManagedSocketBox) sb).getStatus(); if (allSockets.containsKey(sb)) { throw new IllegalArgumentException("This socket already exists in the socket pool."); } allSockets.put(sb, sb); if (status == ManagedSocketBox.FREE) { if (freeSockets.containsKey(sb)) { throw new IllegalArgumentException("This socket already exists in the pool of free sockets."); } logger.debug("adding a free socket"); freeSockets.put(sb, sb); } else { if (busySockets.containsKey(sb)) { throw new IllegalArgumentException("This socket already exists in the pool of busy sockets."); } logger.debug("adding a busy socket"); busySockets.put(sb, sb); } } /** remove socketBox from the pool, remove all references to it*/ public synchronized void remove(SocketBox sb) { int status = ((ManagedSocketBox) sb).getStatus(); if (!allSockets.containsKey(sb)) { throw new IllegalArgumentException("This socket does not seem to exist in the socket pool."); } allSockets.remove(sb); if (status == ManagedSocketBox.FREE) { if (!freeSockets.containsKey(sb)) { throw new IllegalArgumentException("This socket is marked free, but does not exist in the pool of free sockets."); } freeSockets.remove(sb); } else { if (!busySockets.containsKey(sb)) { throw new IllegalArgumentException("This socket is marked busy, but does not exist in the pool of busy sockets."); } busySockets.remove(sb); } } /** checks out the next free socket and returns it, or returns null if there aren't any. * Before calling this method, the socket needs to be first add()ed to the pool. * */ public synchronized SocketBox checkOut() { Enumeration e = freeSockets.keys(); if (e.hasMoreElements()) { SocketBox sb = (SocketBox)e.nextElement(); if (busySockets.containsKey(sb)) { throw new IllegalArgumentException("This socket is marked free, but already exists in the pool of busy sockets."); } ((ManagedSocketBox) sb).setStatus(ManagedSocketBox.BUSY); freeSockets.remove(sb); busySockets.put(sb, sb); return sb; } else { return null; } } /** Before calling this method, the socket needs to be first add()ed to the pool and checked out. Note: checking in a * socket that is not reusable will cause its removal from the pool. */ public synchronized void checkIn(SocketBox sb) { if (((ManagedSocketBox) sb).getStatus() != ManagedSocketBox.BUSY) { throw new IllegalArgumentException("The socket is already marked free, cannot check it in twice."); } if (!busySockets.containsKey(sb)) { throw new IllegalArgumentException("This socket does not exist in the pool of busy sockets."); } if (freeSockets.containsKey(sb)) { throw new IllegalArgumentException("This socket already exists in the pool of free sockets."); } if (! ((ManagedSocketBox)sb).isReusable()) { throw new IllegalArgumentException("This socket is not reusable; cannot check in."); } ((ManagedSocketBox) sb).setStatus(ManagedSocketBox.FREE); busySockets.remove(sb); freeSockets.put(sb, sb); } /** @return number of all cached sockets */ public int count() { return allSockets.size(); } /** @return number of free sockets */ public int countFree() { return freeSockets.size(); } /** @return number of busy sockets */ public int countBusy() { return busySockets.size(); } /** @return true if there is at least 1 free socket */ public boolean hasFree() { return (countFree() > 0); } /** Apply the suplied callback to all socketBoxes.*/ public synchronized void applyToAll(SocketOperator op) throws Exception { Enumeration keys = allSockets.keys(); while (keys.hasMoreElements()) { SocketBox myBox = (SocketBox) keys.nextElement(); op.operate(myBox); } } /** * Forcibly close all sockets, and remove them from the pool. * */ public synchronized void flush() throws IOException { Enumeration keys = allSockets.keys(); // close all sockets before removing them while (keys.hasMoreElements()) { SocketBox myBox = (SocketBox) keys.nextElement(); if (myBox != null) { myBox.setSocket(null); } } allSockets.clear(); freeSockets.clear(); busySockets.clear(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/StreamAsciiDCReader.java000066400000000000000000000022121241116057200317310ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.io.IOException; import org.globus.ftp.Buffer; public class StreamAsciiDCReader extends StreamImageDCReader { protected AsciiTranslator translator; public StreamAsciiDCReader() { // only check for \r\n separators - others are ignored // output tokens with system specific line separators translator = new AsciiTranslator(true, false); } public Buffer read() throws IOException { Buffer buf = super.read(); if (buf == null) { return null; } return translator.translate(buf); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/StreamAsciiDCWriter.java000066400000000000000000000021601241116057200320050ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.io.IOException; import org.globus.ftp.Buffer; public class StreamAsciiDCWriter extends StreamImageDCWriter { protected AsciiTranslator translator; public StreamAsciiDCWriter() { // check for \r\n and \n separators // output tokens with \r\n line separators translator = new AsciiTranslator(true, true, AsciiTranslator.CRLF); } public void write(Buffer buffer) throws IOException { if (buffer == null) return; super.write( translator.translate(buffer) ); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/StreamImageDCReader.java000066400000000000000000000023421241116057200317270ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.io.InputStream; import java.io.IOException; import org.globus.ftp.Buffer; public class StreamImageDCReader implements DataChannelReader { public static final int BUF_SIZE = 512000; protected int bufferSize = BUF_SIZE; protected InputStream input; public void setDataStream(InputStream in) { input = in; } public Buffer read() throws IOException { byte[] bt = new byte[bufferSize]; int read = input.read(bt); if (read == -1) { return null; } else { return new Buffer(bt, read); } } public void close() throws IOException { input.close(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/StreamImageDCWriter.java000066400000000000000000000021561241116057200320040ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.io.OutputStream; import java.io.IOException; import org.globus.ftp.Buffer; public class StreamImageDCWriter implements DataChannelWriter { protected OutputStream output; public void setDataStream(OutputStream out) { output = out; } public void write(Buffer buf) throws IOException { output.write(buf.getBuffer(), 0, buf.getLength()); } public void endOfData() throws IOException {}; public void close() throws IOException { output.close(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/StripeContextManager.java000066400000000000000000000062721241116057200323130ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.globus.ftp.extended.GridFTPServerFacade; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class StripeContextManager { static Log logger = LogFactory.getLog(StripeContextManager.class.getName()); protected int stripes; protected StripeTransferContext contextList[]; protected int stripeQuitTokens = 0; protected Object contextQuitToken = new Object(); public StripeContextManager(int stripes, SocketPool pool, GridFTPServerFacade facade) { this.stripes = stripes; contextList = new StripeTransferContext[stripes]; for (int i = 0; i < stripes; i++) { contextList[i] = new StripeTransferContext(this); contextList[i].setSocketPool(pool); contextList[i].setTransferThreadManager( facade.createTransferThreadManager()); } } /** return number of stripes **/ public int getStripes() { return stripes; } public EBlockParallelTransferContext getStripeContext(int stripe) { return contextList[stripe]; } public Object getQuitToken() { int i = 0; while (i < stripes) { logger.debug("examining stripe " + i); if (contextList[i].getStripeQuitToken() != null) { // obtained quit token from one stripe. stripeQuitTokens ++; logger.debug("obtained stripe quit token. Total = " + stripeQuitTokens + "; total needed = " + stripes); } i ++; } if (stripeQuitTokens == stripes) { // obtained quit tokens from all stripes. // ready to release the quit token. But make sure not to do it twice. // This section only returns non-nul the first time it is entered. if (contextQuitToken == null) { logger.debug("not releasing the quit token."); } else { logger.debug("releasing the quit token."); } Object myToken = contextQuitToken; contextQuitToken = null; return myToken; } else { // not all stripes ready to quit logger.debug("not releasing the quit token. "); return null; } } class StripeTransferContext extends EBlockParallelTransferContext { StripeContextManager mgr; public StripeTransferContext(StripeContextManager mgr) { this.mgr = mgr; } /** @return non-null if this stripe received or sent all the EODs **/ public Object getStripeQuitToken() { Object token = super.getQuitToken(); StripeContextManager.logger.debug( (token != null) ? "stripe released the quit token" : "stripe did not release the quit token"); return token; } /** @return non-null if all EODs in all stripes have been transferred. **/ public Object getQuitToken() { return mgr.getQuitToken(); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/Task.java000066400000000000000000000021151241116057200270770ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; public abstract class Task { protected boolean complete = false; protected Exception exception; public abstract void execute() throws Exception; public void stop() { } public synchronized void setComplete(Exception e) { complete = true; exception = e; notify(); } public synchronized Exception waitFor() { while (!complete) { try { wait(); } catch (Exception e) { return e; } } return exception; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/TaskThread.java000066400000000000000000000066131241116057200302360ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class TaskThread implements Runnable { static final int MAX_TASK_QUEUE = 100; protected static Log logger = LogFactory.getLog(TaskThread.class.getName()); protected Buffer buffer; protected boolean stop; protected Thread thread; public TaskThread() { buffer = new Buffer(MAX_TASK_QUEUE); } public synchronized void start() { if (thread == null) { thread = new Thread(this); thread.setName("Task" + thread.getName()); thread.setDaemon(true); thread.start(); } } public void runTask(Task task) { start(); try { buffer.put(task); } catch (Exception e) { } } public Task getNextTask() { try { return (Task)buffer.get(); } catch (Exception e) { return null; } } public void run() { stop = false; Exception exception; Task task; while(!stop) { task = getNextTask(); if (task == null) break; exception = null; try { logger.debug("executing task: " + task.toString()); task.execute(); logger.debug("finished task: " + task.toString()); } catch (Exception e) { exception = e; } task.setComplete(exception); } } public synchronized void stop() { stop = true; buffer.release(); } public void join() { if (thread != null) { try { thread.join(); } catch (InterruptedException e) { } } } class Buffer { protected Object[] buf; protected int in = 0; protected int out= 0; protected int count= 0; protected int size; public Buffer(int size) { this.size = size; buf = new Object[size]; } public synchronized void put(Object o) throws InterruptedException { while (count==size) { wait(); if (stop) return; } buf[in] = o; ++count; in=(in+1) % size; notify(); } public synchronized Object get() throws InterruptedException { while (count==0) { wait(); if (stop) return null; } Object o =buf[out]; buf[out]=null; --count; out=(out+1) % size; notify(); return (o); } public synchronized void release() { notify(); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/TransferContext.java000066400000000000000000000024131241116057200313270ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; /** Represents an environment shared by all data channels performing the same transfer. **/ public interface TransferContext { /** * A thread can ask for a quit token to perform the operations associated with closing the transfer. * The token is interpreted as a permission to perform these operations. The reason for such policy * lies mainly in the nature of multithreaded transfer, where there are many transfer threads sharing * the same context, but the closing should be done only once. @return a non-null token is a permission for closing, null means no permission. **/ public Object getQuitToken(); } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/TransferSinkThread.java000066400000000000000000000073341241116057200317460ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.globus.ftp.Buffer; import org.globus.ftp.DataSink; import org.globus.ftp.vanilla.FTPServerFacade; import org.globus.ftp.vanilla.BasicServerControlChannel; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Implements incoming transfer. While the transfer is in progress, replies are sent to the local control channel. Also any failure messages go there in the form of a negative reply. **/ public class TransferSinkThread extends TransferThread { protected static Log logger = LogFactory.getLog(TransferSinkThread.class.getName()); protected DataChannelReader reader; protected DataSink sink; protected BasicServerControlChannel localControlChannel; protected TransferContext context; protected SocketBox socketBox; public TransferSinkThread(AbstractDataChannel dataChannel, SocketBox socketBox, DataSink sink, BasicServerControlChannel localControlChannel, TransferContext context) throws Exception { this.socketBox = socketBox; this.sink = sink; this.localControlChannel = localControlChannel; this.context = context; this.reader = dataChannel.getDataChannelSource(context); reader.setDataStream(socketBox.getSocket().getInputStream()); } public void run() { boolean error = false; Object quitToken = null; logger.debug("TransferSinkThread executing"); try { startup(); try { copy(); } catch (Exception e) { error = true; FTPServerFacade.exceptionToControlChannel( e, "exception during TransferSinkThread", localControlChannel); } finally { // attempt to obtain permission to close resources quitToken = context.getQuitToken(); shutdown(quitToken); } if (!error) { // local control channel is shared by all data channels // so only the last one exiting may send "226 transfer complete" if (quitToken != null) { localControlChannel.write(new LocalReply(226)); } } } catch (Exception e) { // exception occurred when trying to write to local // control channel. So there is no way to inform // the user. FTPServerFacade.cannotPropagateError(e); } } protected void startup() throws Exception { //send initial reply only if nothing has yet been sent synchronized(localControlChannel) { if (localControlChannel.getReplyCount() == 0) { // 125 Data connection already open; transfer starting localControlChannel.write(new LocalReply(125)); } } } protected void copy() throws Exception { Buffer buf; long transferred = 0; while ((buf = reader.read()) != null) { transferred += buf.getLength(); sink.write(buf); } logger.debug("finished receiving data; received " + transferred + " bytes"); } protected void shutdown(Object quitToken) throws IOException { logger.debug("shutdown"); reader.close(); // garbage collect the socket socketBox.setSocket(null); // data sink is shared by all data channels, // so should be closed by the last one exiting if (quitToken != null) { sink.close(); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/TransferSourceThread.java000066400000000000000000000071321241116057200322760ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.globus.ftp.Buffer; import org.globus.ftp.DataSource; import org.globus.ftp.vanilla.FTPServerFacade; import org.globus.ftp.vanilla.BasicServerControlChannel; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Implements outgoing transfer. While the transfer is in progress, replies are sent to the local control channel. Also any failure messages go there in the form of a negative reply. **/ public class TransferSourceThread extends TransferThread { protected static Log logger = LogFactory.getLog(TransferSourceThread.class.getName()); protected DataChannelWriter writer; protected DataSource source; protected BasicServerControlChannel localControlChannel; protected TransferContext context; protected SocketBox socketBox = null; public TransferSourceThread(AbstractDataChannel dataChannel, SocketBox socketBox, DataSource source, BasicServerControlChannel localControlChannel, TransferContext context) throws Exception { this.socketBox = socketBox; this.source = source; this.localControlChannel = localControlChannel; this.context = context; this.writer = dataChannel.getDataChannelSink(context); logger.debug("using socket " + socketBox.getSocket().toString()); writer.setDataStream(socketBox.getSocket().getOutputStream()); } public void run() { Buffer buf; long transferred = 0; boolean error = false; logger.debug("TransferSourceThread executing"); try { startup(); try { while ((buf = source.read()) != null) { transferred += buf.getLength(); writer.write(buf); } logger.debug("finished sending data; sent " + transferred + " bytes"); } catch (Exception e) { // this happens also if thread gets interrupted error = true; FTPServerFacade.exceptionToControlChannel( e, "exception during TransferSourceThread", localControlChannel); } Object quitToken = shutdown(); if (!error && (quitToken != null)) { //226 Transfer complete localControlChannel.write(new LocalReply(226)); } } catch (Exception e) { FTPServerFacade.cannotPropagateError(e); } } protected void startup() { //send initial reply only if nothing has yet been sent synchronized(localControlChannel) { if (localControlChannel.getReplyCount() == 0) { // 125 Data connection already open; transfer starting localControlChannel.write(new LocalReply(125)); } } } // called after the transfer completes, before 226 protected Object shutdown() throws IOException { logger.debug("shutdown"); // close the socket writer.close(); // garbage collect the socket socketBox.setSocket(null); // attempt to obtain permission to close data source Object quitToken = context.getQuitToken(); // data source is shared by all data channels, // so should be closed by the last one exiting if (quitToken != null) { source.close(); } return quitToken; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/TransferThread.java000066400000000000000000000012631241116057200311140ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; public abstract class TransferThread extends Thread { } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/TransferThreadFactory.java000066400000000000000000000023561241116057200324500ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import org.globus.ftp.DataSource; import org.globus.ftp.DataSink; import org.globus.ftp.vanilla.BasicServerControlChannel; public interface TransferThreadFactory { public TransferThread getTransferSinkThread(DataChannel dataChannel, SocketBox socketBox, DataSink sink, BasicServerControlChannel localControlChannel, TransferContext context) throws Exception; public TransferThread getTransferSourceThread(DataChannel dataChannel, SocketBox socketBox, DataSource source, BasicServerControlChannel localControlChannel, TransferContext context) throws Exception; } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/dc/TransferThreadManager.java000066400000000000000000000267411241116057200324170ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.dc; import java.net.ServerSocket; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.ftp.DataSink; import org.globus.ftp.DataSource; import org.globus.ftp.GridFTPSession; import org.globus.ftp.HostPort; import org.globus.ftp.exception.ServerException; import org.globus.ftp.extended.GridFTPServerFacade; import org.globus.ftp.vanilla.BasicServerControlChannel; import org.globus.ftp.vanilla.FTPServerFacade; public class TransferThreadManager { static Log logger = LogFactory.getLog(TransferThreadManager.class.getName()); protected SocketPool socketPool; protected GridFTPServerFacade facade; protected BasicServerControlChannel localControlChannel; protected GridFTPSession gSession; protected TaskThread taskThread; protected int transferThreadCount = 0; protected DataChannelFactory dataChannelFactory; public TransferThreadManager(SocketPool socketPool, GridFTPServerFacade facade, BasicServerControlChannel myControlChannel, GridFTPSession gSession) { this.socketPool = socketPool; this.facade = facade; this.gSession = gSession; this.localControlChannel = myControlChannel; this.dataChannelFactory = new GridFTPDataChannelFactory(); } /** * Act as the active side. Connect to the server and * store the newly connected sockets in the socketPool. */ public void activeConnect(HostPort hp, int connections) { for (int i = 0; i < connections; i++) { SocketBox sbox = new ManagedSocketBox(); logger.debug("adding new empty socketBox to the socket pool"); socketPool.add(sbox); logger.debug( "connecting active socket " + i + "; total cached sockets = " + socketPool.count()); Task task = new GridFTPActiveConnectTask( hp, localControlChannel, sbox, gSession); runTask(task); } } /** use only in mode E */ public void activeClose(TransferContext context, int connections) { try { //this could be improved; for symmetry and performance, //make it a separate task class and pass to the taskThread for (int i = 0; i < connections; i++) { SocketBox sbox = socketPool.checkOut(); try { GridFTPDataChannel dc = new GridFTPDataChannel(gSession, sbox); EBlockImageDCWriter writer = (EBlockImageDCWriter)dc.getDataChannelSink(context); writer.setDataStream(sbox.getSocket().getOutputStream()); // close the socket writer.close(); } finally { // do not reuse the socket socketPool.remove(sbox); sbox.setSocket(null); } } } catch (Exception e) { FTPServerFacade.exceptionToControlChannel( e, "closing of a reused connection failed", localControlChannel); } } /** * This should be used once the remote active server connected to us. * This method starts transfer threads that will * read data from the source and send. * * @param reusable if set to false, the sockets will not be reused after * the transfer */ public synchronized void startTransfer(DataSource source, TransferContext context, int connections, boolean reusable) throws ServerException { // things would get messed up if more than 1 file was transfered // simultaneously with the same transfer manager if (transferThreadCount != 0) { throw new ServerException( ServerException.PREVIOUS_TRANSFER_ACTIVE); } for (int i = 0; i < connections; i++) { logger.debug( "checking out a socket; total cached sockets = " + socketPool.count() + "; free = " + socketPool.countFree() + "; busy = " + socketPool.countBusy()); SocketBox sbox = socketPool.checkOut(); if (sbox == null) { logger.debug("No free sockets available, aborting."); return; } ((ManagedSocketBox) sbox).setReusable(reusable); Task task = new ActiveStartTransferTask(source, localControlChannel, sbox, gSession, dataChannelFactory, context); runTask(task); } } /** * This should be used once the remote active server connected to us. * This method starts transfer threads that will * receive the data and store them in the sink. * Because of transfer direction, this method cannot be used with EBLOCK. * Therefore the number of connections is fixed at 1. * * @param reusable if set to false, the sockets will not be reused after * the transfer */ public synchronized void startTransfer(DataSink sink, TransferContext context, int connections, boolean reusable) throws ServerException { // things would get messed up if more than 1 file was transfered // simultaneously with the same transfer manager if (transferThreadCount != 0) { throw new ServerException( ServerException.PREVIOUS_TRANSFER_ACTIVE); } for (int i = 0; i < connections; i++) { logger.debug( "checking out a socket; total cached sockets = " + socketPool.count() + "; free = " + socketPool.countFree() + "; busy = " + socketPool.countBusy()); SocketBox sbox = socketPool.checkOut(); if (sbox == null) { logger.debug("No free sockets available, aborting."); return; } ((ManagedSocketBox) sbox).setReusable(reusable); Task task = new ActiveStartTransferTask( sink, localControlChannel, sbox, gSession, dataChannelFactory, context); runTask(task); } } /** * Accept connections from the remote server, * and start transfer threads that will read incoming data and store * in the sink. * * @param connections the number of expected connections */ public synchronized void passiveConnect(DataSink sink, TransferContext context, int connections, ServerSocket serverSocket) throws ServerException { // things would get messed up if more than 1 file was transfered // simultaneously with the same transfer manager if (transferThreadCount != 0) { throw new ServerException( ServerException.PREVIOUS_TRANSFER_ACTIVE); } for (int i = 0; i < connections; i++) { Task task = new GridFTPPassiveConnectTask( serverSocket, sink, localControlChannel, gSession, dataChannelFactory, (EBlockParallelTransferContext) context); runTask(task); } } /** * Accept connection from the remote server * and start transfer thread that will read incoming data and store in * the sink. This method, because of direction of transfer, cannot be * used with EBlock. Therefore it is fixed to create only 1 connection. */ public synchronized void passiveConnect(DataSource source, TransferContext context, ServerSocket serverSocket) throws ServerException { // things would get messed up if more than 1 file was transfered // simultaneously with the same transfer manager if (transferThreadCount != 0) { throw new ServerException( ServerException.PREVIOUS_TRANSFER_ACTIVE); } Task task = new GridFTPPassiveConnectTask( serverSocket, source, localControlChannel, gSession, dataChannelFactory, (EBlockParallelTransferContext) context); runTask(task); } public synchronized int getTransferThreadCount() { return transferThreadCount; } public synchronized void transferThreadStarting() { transferThreadCount++; logger.debug("one transfer started, total active = " + transferThreadCount); } public synchronized void transferThreadTerminating() { transferThreadCount--; logger.debug("one transfer terminated, total active = " + transferThreadCount); } /** Use this as an interface to the local manager thread. This submits the task to the thread queue. The thread will perform it when it's ready with other waiting tasks. **/ private synchronized void runTask(Task task) { if (taskThread == null) { taskThread = new TaskThread(); } taskThread.runTask(task); } public synchronized void stopTaskThread() { if (taskThread != null) { taskThread.stop(); taskThread.join(); taskThread = null; } } public void close() { stopTaskThread(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/examples/000077500000000000000000000000001241116057200265635ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/examples/FTPGet.java000066400000000000000000000040021241116057200305130ustar00rootroot00000000000000package org.globus.ftp.examples; import org.globus.ftp.FTPClient; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.ServerException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.globus.ftp.DataSink; import org.globus.ftp.DataSinkStream; class FTPGet { public static void main(String[] args) { FTPClient ftp = null; String hostname = "localhost"; int port = 5555; String username = "anonymous"; String password = "anonymous"; try { ftp = new FTPClient(hostname, port); } catch(ServerException e) { System.out.println("Server exception: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error instantiating FTP client: " + e.toString()); System.exit(1); } File localFile = new File("passwd"); String remoteFile = "/etc/passwd"; DataSink sink = null; try { sink = new DataSinkStream(new FileOutputStream(localFile)); } catch(FileNotFoundException e) { System.out.println("could not access client destination: " + e.toString()); System.exit(1); } try { ftp.authorize(username, password); } catch(ServerException e) { System.out.println("Server exception authorizing: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error authorizing: " + e.toString()); System.exit(1); } try { // third parameter is an optional MarkerListener ftp.get(remoteFile, sink, null); } catch(ServerException e) { System.out.println("Server exception getting file: " + e.getMessage()); System.exit(1); } catch(ClientException e) { System.out.println("Client exception getting file: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error getting file: " + e.toString()); System.exit(1); } try { ftp.close(); } catch(Exception e) { } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/examples/FTPPut.java000066400000000000000000000040311241116057200305460ustar00rootroot00000000000000package org.globus.ftp.examples; import org.globus.ftp.FTPClient; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.ServerException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileInputStream; import org.globus.ftp.DataSource; import org.globus.ftp.DataSourceStream; class FTPPut { public static void main(String[] args) { FTPClient ftp = null; String hostname = "localhost"; int port = 5555; String username = "anonymous"; String password = "anonymous"; try { ftp = new FTPClient(hostname, port); } catch(ServerException e) { System.out.println("Server exception: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error instantiating FTP client: " + e.toString()); System.exit(1); } File localFile = new File("/etc/passwd"); String remoteDestination = "mypasswd"; DataSource source = null; try { source = new DataSourceStream(new FileInputStream(localFile)); } catch(FileNotFoundException e) { System.out.println("could not access client source: " + e.toString()); System.exit(1); } try { ftp.authorize(username, password); } catch(ServerException e) { System.out.println("Server exception authorizing: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error authorizing: " + e.toString()); System.exit(1); } try { // third parameter is an optional MarkerListener ftp.put(remoteDestination, source, null); } catch(ServerException e) { System.out.println("Server exception putting file: " + e.getMessage()); System.exit(1); } catch(ClientException e) { System.out.println("Client exception putting file: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error putting file: " + e.toString()); System.exit(1); } try { ftp.close(); } catch(Exception e) { } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/examples/FTPThirdParty.java000066400000000000000000000037501241116057200320770ustar00rootroot00000000000000package org.globus.ftp.examples; import org.globus.ftp.FTPClient; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.ServerException; class FTPThirdParty { public static void main(String[] args) { FTPClient ftp1 = null; FTPClient ftp2 = null; // first host String hostname1 = "localhost"; int port1 = 5555; String username1 = "anonymous"; String password1 = "anonymous"; // second host String hostname2 = "localhost"; int port2 = 5556; String username2 = "anonymous"; String password2 = "anonymous"; String remoteSource = "/etc/passwd"; String remoteDest = "/tmp/mypasswd"; boolean append = false; try { ftp1 = new FTPClient(hostname1, port1); ftp2 = new FTPClient(hostname2, port2); } catch(ServerException e) { System.out.println("Server exception: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error instantiating FTP client: " + e.toString()); System.exit(1); } try { ftp1.authorize(username1, password1); ftp2.authorize(username2, password2); } catch(ServerException e) { System.out.println("Server exception authorizing: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error authorizing: " + e.toString()); System.exit(1); } try { // fifth parameter is an optional MarkerListener ftp1.transfer(remoteSource, ftp2, remoteDest, append, null); } catch(ServerException e) { System.out.println("Server exception transferring file: " + e.getMessage()); System.exit(1); } catch(ClientException e) { System.out.println("Client exception transferring file: " + e.getMessage()); System.exit(1); } // must be an IOException catch(Exception e) { System.out.println("error transferring file: " + e.toString()); System.exit(1); } try { ftp1.close(); ftp2.close(); } catch(Exception e) { } } } LocalCredentialHelper.java000066400000000000000000000025201241116057200335330ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/examplespackage org.globus.ftp.examples; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.util.ConfigUtil; import org.gridforum.jgss.ExtendedGSSCredential; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class LocalCredentialHelper { private Log log = LogFactory.getLog(LocalCredentialHelper.class); public GSSCredential getDefaultCredential() throws IOException, GSSException { System.out.println("Proxy Location "+ ConfigUtil.discoverProxyLocation()); return this.getCredential(new File(ConfigUtil.discoverProxyLocation())); } public GSSCredential getCredential(File proxyFile) throws IOException, GSSException { byte[] proxyBytes = new byte[(int) proxyFile.length()]; FileInputStream in = new FileInputStream(proxyFile); try { in.read(proxyBytes); } finally { in.close(); } ExtendedGSSManager manager = (ExtendedGSSManager) ExtendedGSSManager.getInstance(); return manager.createCredential(proxyBytes, ExtendedGSSCredential.IMPEXP_OPAQUE, GSSCredential.DEFAULT_LIFETIME, null, GSSCredential.INITIATE_AND_ACCEPT); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/examples/TwoPartyTransfer.java000066400000000000000000000064421241116057200327320ustar00rootroot00000000000000package org.globus.ftp.examples; import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; //import org.birncommunity.sample.proxy.LocalCredentialHelper; import org.globus.ftp.GridFTPClient; import org.globus.ftp.Session; import org.globus.gsi.gssapi.auth.IdentityAuthorization; public class TwoPartyTransfer { private static Log log = LogFactory.getLog(TwoPartyTransfer.class); private String host; private int port; private String source; private String dest; private String direction; public static void main(String[] args) throws Exception { /* if (args.length != 5 || args[0].equals("-h") || args[0].equals("--help")) { log.error("Usage: java " + TwoPartyTransfer.class.getName() + " "); log.error("host: GridFTP server hostname"); log.error("port: GridFTP server port"); log.error("direction: \"download\" || \"upload\""); log.error("sourceFile: source file"); log.error("destFile: destination file"); log.error(""); log.error("A user proxy certificate needs to be in place in /tmp"); log.error(""); log.error("Example: java " + TwoPartyTransfer.class.getName() + " chi-vm-4.isi.edu 2811 download /tmp/testfile /tmp/testfile"); log.error("This will transfer chi-vm-4.isi.edu/tmp/testfile into /tmp/testfile"); System.exit(1); } */ String host = "localhost";//args[0]; int port = 50500;//new Integer(args[1]).intValue(); String direction = "download";//args[2]; String source = "~/test/test1";///test/args[3]; String dest = "/tmp/testx";//args[4]; new TwoPartyTransfer(host, port, source, dest, direction).doTransfer(); } public TwoPartyTransfer(String host, int port, String source, String dest, String direction) { if (!direction.equals("download") && !direction.equals("upload")) { throw new IllegalArgumentException("Invalid direction: \"download\" || \"upload\""); } this.host = host; this.port = port; this.source = source; this.dest = dest; this.direction = direction; } public void doTransfer() throws Exception { GridFTPClient client = null; try { client = new GridFTPClient(host, port); // Change the authorization from the output of identity from grid-proxy-init client.setAuthorization(new IdentityAuthorization("/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand")); client.authenticate(new LocalCredentialHelper().getDefaultCredential()); client.setType(Session.TYPE_IMAGE); client.setPassive(); client.setLocalActive(); if (direction.equals("download")) { client.get(source, new File(dest)); } else { client.put(new File(source), dest, false); } } finally { try { if (client != null) { client.close(true); } } catch (Exception e) { log.error("Can't close connection.",e); } } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/000077500000000000000000000000001241116057200267435ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/ClientException.java000066400000000000000000000052171241116057200327100ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.exception; /** Indicates a local client side problem that has not been caused by remote server nor the local data channel. **/ public class ClientException extends FTPException { //public static final int UNSPECIFIED = 0; public static final int NOT_AUTHORIZED = 1; public static final int PBSZ_DIFFER = 2; public static final int TRANSFER_MODE_DIFFER = 3; public static final int TRANSFER_TYPE_DIFFER = 4; public static final int BAD_SERVER_MODE = 5; public static final int REPLY_TIMEOUT = 6; public static final int THREAD_KILLED = 7; public static final int BAD_MODE = 8; public static final int MARK_NOT_SUPPORTED = 9; public static final int CALL_PASSIVE_FIRST = 10; public static final int LOCAL_TRANSFER = 11; public static final int UNKNOWN_HOST = 12; public static final int BAD_TYPE = 13; public static final int SOCKET_OP_FAILED = 14; public static final int OTHER = 15; private static String[] codeExplained; static { codeExplained = new String[] {"Unspecified category.", "Server authorization has not been performed.", "Servers have been set up with different protection buffer sizes.", "Servers have been set up with different transfer modes.", "Servers have been set up with different transfer types.", "One server should be have been set active and the other passive.", "Reply wait timeout.", "Transfer thread has been killed.", "Server has been set to wrong transfer mode.", "Client's BufferedReader implementation does not support mark().", "Set one server to passive before setting other to active.", "Local transfer problem.", "Cannot connect - unknown remote host.", "Server has been set to wrong transfer type.", "Socket operation failed." }; } public String getCodeExplanation(int code) { if (codeExplained.length > code) return codeExplained[code]; else return ""; } public ClientException(int code, String message) { super(code, message); } public ClientException(int code) { super(code); } } DataChannelException.java000066400000000000000000000032051241116057200335500ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.exception; /** Indicates data channel problems. Thrown by local server at layer 2. **/ public class DataChannelException extends FTPException { //public static final int UNSPECIFIED = 0; public static final int UNDEFINED_SERVER_MODE = 1; public static final int BAD_SERVER_MODE = 2; private static String[] codeExplained; static { codeExplained = new String[] {"Unspecified category.", "Undefined server mode (active or passive?)", "setPassive() must match store() and setActive() - retrieve() " }; } public String getCodeExplanation(int code) { if (codeExplained.length > code) return codeExplained[code]; else return ""; } //this message is not just explanation of the code. //it is a custom message informing of particular //conditions of the error. protected String customMessage; public DataChannelException(int code, String message) { super(code, message); customMessage = message; } public DataChannelException(int code) { super(code); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/FTPException.java000066400000000000000000000102351241116057200321170ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.exception; /** Most exceptions used by ftp package are subclasses of FTPException and inherit its features:
    • exception code can be used to more precisely identify the problem. Exception codes are defined within each exception class (look at the source code). For example, in ClientException, code 8 (ClientException.BAD_MODE) indicates that client refused operation because of bad transfer mode, while code 13 (ClientException.BAD_TYPE) indicates that the same thing was caused by bad transfer type. To programmatically retrieve the exception code, use exception.getCode().
    • exception nesting can be used to track the root of the exceptions that come from lower software layers. Use getRootCause().
    */ public class FTPException extends Exception { public static final int UNSPECIFIED = 0; protected int code = UNSPECIFIED; private static String[] codeExplained = {"Unspecified category."}; public String getCodeExplanation(int code) { if (codeExplained.length > code) return codeExplained[code]; else return ""; } //the exception that caused this exception, if any protected Exception cause; //this message is not just explanation of the code. //it is a custom message informing of particular //conditions of the error. protected String customMessage; public FTPException(int code, String message) { super(); this.code = code; customMessage = message; } public FTPException(int code) { this.code = code; } public void setRootCause(Exception c) { this.cause = c; } /** Retrieve the nested lower layer exception. */ public Exception getRootCause() { return cause; } public void setCode(int c) { this.code = c; } public int getCode() { return code; } public void setCustomMessage(String m) { customMessage = m; } public String getCustomMessage() { return customMessage; } //overwriting inherited public String getMessage() { StringBuffer buf = new StringBuffer(); if (code != UNSPECIFIED) { buf.append(getCodeExplanation(code)); } if (customMessage != null) { buf.append(" Custom message: "); buf.append(customMessage); } if (code != UNSPECIFIED) { buf.append(" (error code ").append(String.valueOf(code)).append(")"); } if (cause != null) { buf.append(" [Nested exception message: "); buf.append(cause.getMessage()); buf.append("]"); } return buf.toString(); } public String toString() { String answer = super.toString(); if (cause != null && cause != this) { answer += " [Nested exception is " + cause.toString() + "]"; } return answer; } public void printStackTrace() { printStackTrace( System.err ); } public void printStackTrace(java.io.PrintStream ps) { if ( cause != null ) { String superString = super.toString(); synchronized ( ps ) { ps.print(superString + (superString.endsWith(".") ? "" : ".") + " Nested exception is "); cause.printStackTrace( ps ); } } else { super.printStackTrace( ps ); } } public void printStackTrace(java.io.PrintWriter pw) { if ( cause != null ) { String superString = super.toString(); synchronized (pw) { pw.print(superString + (superString.endsWith(".") ? "" : ".") + " Nested exception is "); cause.printStackTrace( pw ); } } else { super.printStackTrace( pw ); } } } FTPReplyParseException.java000066400000000000000000000030761241116057200340540ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.exception; /** Indicates that the reply received from server failed to parse. */ public class FTPReplyParseException extends FTPException { //public static final int UNSPECIFIED = 0; public static final int STRING_TOO_SHORT = 1; public static final int FIRST_3_CHARS = 2; public static final int UNEXPECTED_4TH_CHAR = 3; public static final int MESSAGE_UNPARSABLE = 4; private static String[] codeExplained; static { codeExplained =new String[]{ "Unspecified exception.", "Reply string too short.", "First 3 characters are not digits.", "Unexpected 4th character.", "Reply message unparsable" }; } public String getCodeExplanation(int code) { if (codeExplained.length > code) return codeExplained[code]; else return ""; } public FTPReplyParseException(int code) { super(code); } public FTPReplyParseException(int code, String message) { super(code, message); } } NotImplementedException.java000066400000000000000000000016441241116057200343370ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.exception; /** Not used. This exception should be thrown on an attempt of accessing functionality that has not been implemented. **/ public class NotImplementedException extends RuntimeException { public NotImplementedException() { super("This method has not been implemented."); } } PerfMarkerException.java000066400000000000000000000027511241116057200334510ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.exception; /** thrown by PerformanceMarker, mostly during construction. **/ public class PerfMarkerException extends FTPException { /** **/ public static final int NO_SUCH_PARAMETER = 1; private static String[] codeExplained; static { codeExplained = new String[] {"Unspecified category.", "Marker does not contain the requested parameter." }; } public String getCodeExplanation(int code) { if (codeExplained.length > code) return codeExplained[code]; else return ""; } //this message is not just explanation of the code. //it is a custom message informing of particular //conditions of the error. protected String customMessage; public PerfMarkerException(int code, String message) { super(code, message); customMessage = message; } public PerfMarkerException(int code) { super(code); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/ServerException.java000066400000000000000000000064211241116057200327360ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.exception; /** Indicates that operation failed because of conditions on the server, independent from the client. For instance, the server did not understand command, or could not read file. Note that here "server" can mean either a remote server, or the local internal server (FTPServerFacade). **/ public class ServerException extends FTPException { /** Server refused performing the request **/ public static final int SERVER_REFUSED = 1; /** The communication from the server was not understood, possibly because of incompatible protocol. **/ public static final int WRONG_PROTOCOL = 2; public static final int UNSUPPORTED_FEATURE = 3; public static final int REPLY_TIMEOUT = 4; public static final int PREVIOUS_TRANSFER_ACTIVE = 5; private static String[] codeExplained; static { codeExplained = new String[] {"Unspecified category.", "Server refused performing the request.", "The server uses unknown communication protool.", "Server does not support feature.", "Reply wait timeout.", "Refusing to start transfer before previous transfer completes"}; } public String getCodeExplanation(int code) { if (codeExplained.length > code) return codeExplained[code]; else return ""; } //this message is not just explanation of the code. //it is a custom message informing of particular //conditions of the error. protected String customMessage; public ServerException(int code, String message) { super(code, message); customMessage = message; } public ServerException(int code) { super(code); } /** Constructs server exception with FTPReplyParseException nested in it. **/ public static ServerException embedFTPReplyParseException( FTPReplyParseException rpe, String message) { ServerException se = new ServerException( WRONG_PROTOCOL, message); se.setRootCause(rpe); return se; } public static ServerException embedFTPReplyParseException( FTPReplyParseException rpe) { return embedFTPReplyParseException(rpe, ""); } /** Constructs server exception with UnexpectedReplyCodeException nested in it. **/ public static ServerException embedUnexpectedReplyCodeException( UnexpectedReplyCodeException urce, String message) { ServerException se = new ServerException( SERVER_REFUSED, message); se.setRootCause(urce); return se; } public static ServerException embedUnexpectedReplyCodeException( UnexpectedReplyCodeException urce) { return embedUnexpectedReplyCodeException(urce, ""); } } UnexpectedReplyCodeException.java000066400000000000000000000022311241116057200353170ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/exception/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.exception; import org.globus.ftp.vanilla.Reply; /** Indicates that the received reply had different code than it had been expected. */ public class UnexpectedReplyCodeException extends FTPException { private Reply reply; public UnexpectedReplyCodeException(int code, String msg, Reply r) { super(code,msg); this.reply = r; } public UnexpectedReplyCodeException(Reply r) { super(FTPException.UNSPECIFIED, "Unexpected reply: " + r); this.reply = r; } public Reply getReply() { return reply; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/extended/000077500000000000000000000000001241116057200265455ustar00rootroot00000000000000GridFTPControlChannel.java000066400000000000000000000246551241116057200334360ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/extended/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.extended; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.globus.ftp.GridFTPSession; import org.globus.ftp.exception.ServerException; import org.globus.ftp.exception.UnexpectedReplyCodeException; import org.globus.ftp.exception.FTPReplyParseException; import org.globus.ftp.vanilla.Reply; import org.globus.ftp.vanilla.FTPControlChannel; import org.globus.ftp.vanilla.Command; import org.globus.common.ChainedIOException; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.GSSAuthorization; import org.globus.gsi.gssapi.auth.HostAuthorization; import org.globus.gsi.gssapi.auth.AuthorizationException; import org.globus.gsi.gssapi.GSSConstants; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** GridFTP control channel, unlike the vanilla control channel, uses GSI autentication. **/ public class GridFTPControlChannel extends FTPControlChannel { private static Log logger = LogFactory.getLog(GridFTPControlChannel.class.getName()); protected static final int TIMEOUT = 120000; //maybe this is useless protected GSSCredential credentials = null; protected Authorization authorization = HostAuthorization.getInstance(); protected int protection = GridFTPSession.PROTECTION_PRIVATE; public GridFTPControlChannel(String host, int port) { super(host,port); } public GridFTPControlChannel(InputStream in, OutputStream out) { super(in, out); } /** * Sets data channel protection level. * * @param protection should be * {@link GridFTPSession#PROTECTION_CLEAR CLEAR}, * {@link GridFTPSession#PROTECTION_SAFE SAFE}, or * {@link GridFTPSession#PROTECTION_PRIVATE PRIVATE}, or * {@link GridFTPSession#PROTECTION_CONFIDENTIAL CONFIDENTIAL}. **/ public void setProtection(int protection) { switch(protection) { case GridFTPSession.PROTECTION_CLEAR: throw new IllegalArgumentException("Unsupported protection: " + protection); case GridFTPSession.PROTECTION_SAFE: case GridFTPSession.PROTECTION_CONFIDENTIAL: case GridFTPSession.PROTECTION_PRIVATE: break; default: throw new IllegalArgumentException("Bad protection: " + protection); } this.protection = protection; } /** * Returns control channel protection level. * * @return control channel protection level: * {@link GridFTPSession#PROTECTION_CLEAR CLEAR}, * {@link GridFTPSession#PROTECTION_SAFE SAFE}, or * {@link GridFTPSession#PROTECTION_PRIVATE PRIVATE}, or * {@link GridFTPSession#PROTECTION_CONFIDENTIAL CONFIDENTIAL}. **/ public int getProtection() { return this.protection; } /** * Sets authorization method for the control channel. * * @param authorization authorization method. */ public void setAuthorization(Authorization authorization) { this.authorization = authorization; } /** * Returns authorization method for the control channel. * * @return authorization method performed on the control channel. */ public Authorization getAuthorization() { return this.authorization; } /** * Performs authentication with specified user credentials. * * @param credential user credentials to use. * @throws IOException on i/o error * @throws ServerException on server refusal or faulty server behavior */ public void authenticate(GSSCredential credential) throws IOException, ServerException { authenticate(credential, null); } /** * Performs authentication with specified user credentials and * a specific username (assuming the user dn maps to the passed username). * * @param credential user credentials to use. * @param username specific username to authenticate as. * @throws IOException on i/o error * @throws ServerException on server refusal or faulty server behavior */ public void authenticate(GSSCredential credential, String username) throws IOException, ServerException { setCredentials( credential ); write(new Command("AUTH", "GSSAPI")); Reply reply0 = null; try { reply0 = read(); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException( rpe, "Received faulty reply to AUTH GSSAPI"); } if (! Reply.isPositiveIntermediate(reply0)) { close(); throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(reply0), "Server refused GSSAPI authentication."); } GSSManager manager = ExtendedGSSManager.getInstance(); GSSContext context = null; GridFTPOutputStream gssout = null; GridFTPInputStream gssin = null; try { String host = this.socket.getInetAddress().getHostAddress(); GSSName expectedName = null; if (this.authorization instanceof GSSAuthorization) { GSSAuthorization auth = (GSSAuthorization)this.authorization; expectedName = auth.getExpectedName(credential, host); } context = manager.createContext(expectedName, GSSConstants.MECH_OID, credential, GSSContext.DEFAULT_LIFETIME); context.requestCredDeleg(true); context.requestConf(this.protection == GridFTPSession.PROTECTION_PRIVATE); gssout = new GridFTPOutputStream(ftpOut, context); gssin = new GridFTPInputStream(rawFtpIn, context); byte [] inToken = new byte[0]; byte [] outToken = null; while( !context.isEstablished() ) { outToken = context.initSecContext(inToken, 0, inToken.length); if (outToken != null) { gssout.writeHandshakeToken(outToken); } if (!context.isEstablished()) { inToken = gssin.readHandshakeToken(); } } } catch (GSSException e) { throw new ChainedIOException("Authentication failed", e); } if (this.authorization != null) { try { this.authorization.authorize(context, host); } catch (AuthorizationException e) { throw new ChainedIOException("Authorization failed", e); } } // this should be authentication success msg (plain) // 234 (ok, no further data required) Reply reply1 = null; try { reply1 = read(); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException( rpe, "Received faulty reply to authentication"); } if ( ! Reply.isPositiveCompletion(reply1)) { close(); throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(reply1), "GSSAPI authentication failed."); } // enter secure mode - send MIC commands setInputStream(gssin); setOutputStream(gssout); //from now on, the commands and replies //are protected and pass through gsi wrapped socket write(new Command("USER", (username == null) ? ":globus-mapping:" : username)); Reply reply2 = null; try { reply2 = read(); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException( rpe, "Received faulty reply to USER command"); } if (Reply.isPositiveCompletion(reply2) || Reply.isPositiveIntermediate(reply2)) { // wu-gsiftp sends intermediate code while // gssftp send completion reply code } else { close(); throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(reply2), "User authorization failed."); } write(new Command("PASS", "dummy")); Reply reply3 = null; try { reply3=read(); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException( rpe, "Received faulty reply to PASS command"); } if (!Reply.isPositiveCompletion(reply3)) { close(); throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(reply3), "Bad password."); } } protected void setCredentials( GSSCredential credentials ) { this.credentials = credentials; } protected GSSCredential getCredentials() { return credentials; } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/extended/GridFTPInputStream.java000066400000000000000000000067231241116057200330530ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.extended; import java.io.InputStream; import java.io.BufferedInputStream; import java.io.IOException; import java.io.EOFException; import org.globus.gsi.gssapi.net.GssInputStream; import org.bouncycastle.util.encoders.Base64; import org.ietf.jgss.GSSContext; public class GridFTPInputStream extends GssInputStream { public GridFTPInputStream(InputStream in, GSSContext context) { super(new BufferedInputStream(in), context); } private String readLine() throws IOException { int c = this.in.read(); if (c == -1) { return null; } StringBuffer buf = new StringBuffer(); buf.append((char)c); while( (c = this.in.read()) != -1 ) { if (c == '\r') { c = this.in.read(); if (c == '\n' || c == -1) { break; } else { throw new IOException("bad format"); } } else { buf.append( (char)c); } } return buf.toString(); } public byte[] readHandshakeToken() throws IOException { String line = readLine(); if (line == null) { throw new EOFException(); } if (line.startsWith("335 ADAT=") || line.startsWith("334 ADAT=") ) { // TODO: this can be optimized return Base64.decode(line.substring(9).getBytes()); } else if ( line.startsWith("335 more data needed") ) { return new byte[0]; } else { throw new IOException(handleReply(line)); } } private String handleReply(String line) throws IOException { line = line.trim(); if (line.length() > 4 && line.charAt(3) == '-') { String lineSeparator = System.getProperty("line.separator"); String lastLineStarts = line.substring(0, 3) + ' '; StringBuffer buf = new StringBuffer(); buf.append(line); for (;;) { line = readLine(); if (line == null) { throw new EOFException(); } line = line.trim(); buf.append(lineSeparator).append(line); if (line.startsWith(lastLineStarts)) { break; } } return buf.toString(); } else { return line; } } protected void readMsg() throws IOException { String line = readLine(); if (line == null) { throw new EOFException(); } if (line.charAt(0) == '6') { this.buff = unwrap(Base64.decode(line.substring(4).getBytes())); this.index = 0; /** * This is a fix for messages that are not * \r\n terminated */ byte last = this.buff[this.buff.length-1]; if (last == 0) { // this is a bug in older gridftp servers // line should be terminated with \r\n0 if (this.buff[this.buff.length-2] != 10) { this.buff[this.buff.length-1] = 10; } } else if (last != 10) { byte [] newBuff = new byte[this.buff.length+1]; System.arraycopy(buff, 0, newBuff, 0, this.buff.length); newBuff[this.buff.length]=10; this.buff = newBuff; } } else { throw new IOException(line); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/extended/GridFTPOutputStream.java000066400000000000000000000035071241116057200332510ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.extended; import java.io.OutputStream; import java.io.BufferedOutputStream; import java.io.IOException; import org.globus.gsi.gssapi.net.GssOutputStream; //import org.globus.util.Base64; import org.bouncycastle.util.encoders.Base64; import org.ietf.jgss.GSSContext; public class GridFTPOutputStream extends GssOutputStream { private static final byte[] CRLF = "\r\n".getBytes(); private static final byte[] ADAT = "ADAT ".getBytes(); private static final byte[] MIC = "MIC ".getBytes(); private static final byte[] ENC = "ENC ".getBytes(); public GridFTPOutputStream(OutputStream out, GSSContext context) { super(new BufferedOutputStream(out), context); } public void flush() throws IOException { if (this.index == 0) return; if (this.context.getConfState()) { writeToken(ENC, wrap()); } else { writeToken(MIC, wrap()); } this.index = 0; } public void writeHandshakeToken(byte [] token) throws IOException { writeToken(ADAT, token); } private void writeToken(byte[] header, byte[] token) throws IOException { this.out.write(header); this.out.write(Base64.encode(token)); this.out.write(CRLF); this.out.flush(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/extended/GridFTPServerFacade.java000066400000000000000000000523241241116057200331300ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.extended; import java.net.Socket; import java.net.UnknownHostException; import java.io.IOException; import java.io.DataOutputStream; import org.globus.util.Util; import org.globus.net.ServerSocketFactory; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.globus.gsi.gssapi.auth.IdentityAuthorization; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.GSIConstants; import org.globus.ftp.GridFTPSession; import org.globus.ftp.HostPort; import org.globus.ftp.HostPort6; import org.globus.ftp.HostPortList; import org.globus.ftp.RetrieveOptions; import org.globus.ftp.DataSink; import org.globus.ftp.DataSource; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.Options; import org.globus.ftp.Session; import org.globus.ftp.dc.EBlockParallelTransferContext; import org.globus.ftp.dc.ManagedSocketBox; import org.globus.ftp.dc.SocketBox; import org.globus.ftp.dc.SocketOperator; import org.globus.ftp.dc.SocketPool; import org.globus.ftp.dc.TransferContext; import org.globus.ftp.dc.StripeContextManager; import org.globus.ftp.dc.EBlockImageDCWriter; import org.globus.ftp.dc.TransferThreadManager; import org.globus.ftp.exception.DataChannelException; import org.globus.ftp.exception.ClientException; import org.globus.ftp.vanilla.FTPServerFacade; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class GridFTPServerFacade extends FTPServerFacade { private static Log logger = LogFactory.getLog(GridFTPServerFacade.class.getName()); // utility alias to session protected GridFTPSession gSession = null; protected SocketPool socketPool = null; protected TransferThreadManager transferThreadManager = null; // current transfer, if striped retrieve, is associated to this manager // (striped store does not suffer for EOD complications and don't need // manager) protected StripeContextManager stripeRetrContextManager = null; public GridFTPServerFacade(GridFTPControlChannel remoteControlChannel) { super(remoteControlChannel); gSession = new GridFTPSession(); session = gSession; // make sure this doesn't get used dataChannelFactory = null; socketPool = new SocketPool(); transferThreadManager = createTransferThreadManager(); } public void setCredential(GSSCredential cred) { gSession.credential = cred; } public void setDataChannelProtection(int protection) { gSession.dataChannelProtection = protection; } public void setDataChannelAuthentication(DataChannelAuthentication authentication) { gSession.dataChannelAuthentication = authentication; } public void setOptions(Options opts) { if (opts instanceof RetrieveOptions) { gSession.parallel = ((RetrieveOptions) opts).getStartingParallelism(); logger.debug("parallelism set to " + gSession.parallel); } } /** This method needs to be called BEFORE the local socket(s) get created. In other words, before setActive(), setPassive(), get(), put(), etc. **/ public void setTCPBufferSize(final int size) throws ClientException { logger.debug("Changing local TCP buffer setting to " + size); gSession.TCPBufferSize = size; SocketOperator op = new SocketOperator() { public void operate(SocketBox s) throws Exception { // synchronize to prevent race condition against // the socket initialization code that also sets // TCP buffer (GridFTPActiveConnectTask) synchronized (s) { logger.debug( "Changing local socket's TCP buffer to " + size); Socket mySocket = s.getSocket(); if (mySocket != null) { mySocket.setReceiveBufferSize(size); mySocket.setSendBufferSize(size); } else { logger.debug( "the socket is null. probably being initialized"); } } } }; try { socketPool.applyToAll(op); } catch (Exception e) { ClientException ce = new ClientException(ClientException.SOCKET_OP_FAILED); ce.setRootCause(e); throw ce; } } protected void transferAbort() { if (session.serverMode == Session.SERVER_PASSIVE) { unblockServer(); transferThreadManager.stopTaskThread(); } } /** All sockets opened when this server was active should send a special EBlock header before closing. */ private void closeOutgoingSockets() throws ClientException { SocketOperator op = new SocketOperator() { public void operate(SocketBox sb) throws Exception { if (((ManagedSocketBox) sb).isReusable()) { Socket s = sb.getSocket(); if (s != null) { // write the closing Eblock and close the socket EBlockImageDCWriter.close( new DataOutputStream(s.getOutputStream())); } } } }; try { socketPool.applyToAll(op); } catch (IOException e) { // ignore - sometimes server might close the socket } catch (Exception e) { ClientException ce = new ClientException(ClientException.SOCKET_OP_FAILED); ce.setRootCause(e); throw ce; } } public void setActive(HostPort hp) throws UnknownHostException, ClientException, IOException { if (logger.isDebugEnabled()) { logger.debug("hostport: " + hp.getHost() + " " + hp.getPort()); } if (session.serverMode == Session.SERVER_ACTIVE) { closeOutgoingSockets(); } socketPool.flush(); session.serverMode = Session.SERVER_ACTIVE; // may be needed later, if parallelism increases and // new connections need to be open this.remoteServerAddress = hp; transferThreadManager.activeConnect(hp, gSession.parallel); } public void setStripedActive(HostPortList hpl) throws UnknownHostException, IOException { if (hpl == null) { throw new IllegalArgumentException("null HostPortList"); } int stripes = hpl.size(); if (stripes < 1) { throw new IllegalArgumentException("empty HostPortList"); } socketPool.flush(); // = new SocketBox[pathes * stripes]; //create context manager that will be used by retrieve() this.stripeRetrContextManager = new StripeContextManager(stripes, socketPool, this); int pathes = gSession.parallel; gSession.serverMode = GridFTPSession.SERVER_EACT; for (int stripe = 0; stripe < stripes; stripe++) { transferThreadManager.activeConnect(hpl.get(stripe), pathes); } } public HostPort setPassive(int port, int queue) throws IOException { // remove existing sockets, if any socketPool.flush(); return super.setPassive(port, queue); } public HostPortList setStripedPassive() throws IOException { return setStripedPassive(ANY_PORT, DEFAULT_QUEUE); } public HostPortList setStripedPassive(int port, int queue) throws IOException { // remove existing sockets, if any socketPool.flush(); if (serverSocket == null) { ServerSocketFactory factory = ServerSocketFactory.getDefault(); serverSocket = factory.createServerSocket(port, queue); } gSession.serverMode = GridFTPSession.SERVER_EPAS; gSession.serverAddressList = new HostPortList(); String address = Util.getLocalHostAddress(); int localPort = serverSocket.getLocalPort(); HostPort hp = null; if (remoteControlChannel.isIPv6()) { String version = HostPort6.getIPAddressVersion(address); hp = new HostPort6(version, address, localPort); } else { hp = new HostPort(address, localPort); } gSession.serverAddressList.add(hp); logger.debug("started single striped passive server at port " + ((HostPort) gSession.serverAddressList.get(0)).getPort()); return gSession.serverAddressList; } /** Store the data from the data channel to the data sink. Does not block. If operation fails, exception might be thrown via local control channel. @param sink source of data **/ public void store(DataSink sink) { try { localControlChannel.resetReplyCount(); if (session.transferMode != GridFTPSession.MODE_EBLOCK) { // // no EBLOCK // EBlockParallelTransferContext context = (EBlockParallelTransferContext) createTransferContext(); context.setEodsTotal(0); if (session.serverMode == Session.SERVER_PASSIVE) { transferThreadManager.passiveConnect( sink, context, 1, serverSocket); } else { //1 non reusable connection transferThreadManager.startTransfer( sink, context, 1, ManagedSocketBox.NON_REUSABLE); } } else if ( session.serverMode != GridFTPSession.SERVER_EPAS && session.serverMode != GridFTPSession.SERVER_PASSIVE) { // // EBLOCK, local server not passive // exceptionToControlChannel( new DataChannelException( DataChannelException.BAD_SERVER_MODE), "refusing to store with active mode"); } else { // // EBLOCK, local server passive // // data channels will // share this transfer context EBlockParallelTransferContext context = (EBlockParallelTransferContext) createTransferContext(); // we are the passive side, so we don't really get to decide // how many connections will be used int willReuseConnections = socketPool.countFree(); int needNewConnections = 0; if (gSession.parallel > willReuseConnections) { needNewConnections = gSession.parallel - willReuseConnections; } logger.debug("will reuse " + willReuseConnections + " connections and start " + needNewConnections + " new ones."); transferThreadManager.startTransfer( sink, context, willReuseConnections, ManagedSocketBox.REUSABLE); if (needNewConnections > 0) { transferThreadManager.passiveConnect( sink, context, needNewConnections, serverSocket); } } } catch (Exception e) { exceptionToControlChannel(e, "ocurred during store()"); } } /** Retrieve the data from the data source and write to the data channel. This method does not block. If operation fails, exception might be thrown via local control channel. @param source source of data **/ public void retrieve(DataSource source) { try { localControlChannel.resetReplyCount(); if (session.transferMode != GridFTPSession.MODE_EBLOCK) { // // No EBLOCK // EBlockParallelTransferContext context = (EBlockParallelTransferContext) createTransferContext(); context.setEodsTotal(0); logger.debug("starting outgoing transfer without mode E"); if (session.serverMode == Session.SERVER_PASSIVE) { transferThreadManager.passiveConnect(source, context, serverSocket); } else { transferThreadManager.startTransfer( source, context, 1, ManagedSocketBox.NON_REUSABLE); } return; } else if (session.serverMode == Session.SERVER_ACTIVE) { // // EBLOCK, no striping // // data channels will share this transfer context EBlockParallelTransferContext context = (EBlockParallelTransferContext) createTransferContext(); int total = gSession.parallel; //we should send as many EODS as there are parallel streams context.setEodsTotal(total); int free = socketPool.countFree(); int willReuseConnections = (total > free) ? free : total; int willCloseConnections = (free > total) ? free - total : 0; int needNewConnections = (total > free) ? total - free: 0; logger.debug("will reuse " + willReuseConnections + " connections, start " + needNewConnections + " new ones, and close " + willCloseConnections); if (needNewConnections > 0 ) { transferThreadManager.activeConnect(this.remoteServerAddress, needNewConnections); } if (willCloseConnections > 0) { transferThreadManager.activeClose(context, willCloseConnections); } transferThreadManager.startTransfer( source, context, willReuseConnections + needNewConnections, ManagedSocketBox.REUSABLE); } else if (session.serverMode == GridFTPSession.SERVER_EACT) { // // EBLOCK, striping // if (stripeRetrContextManager == null) { throw new IllegalStateException(); } int stripes = stripeRetrContextManager.getStripes(); for (int stripe = 0; stripe < stripes; stripe++) { EBlockParallelTransferContext context = stripeRetrContextManager.getStripeContext(stripe); context.setEodsTotal(gSession.parallel); transferThreadManager.startTransfer( source, context, gSession.parallel, ManagedSocketBox.REUSABLE); } } else { // // EBLOCK and local server not active // throw new DataChannelException( DataChannelException.BAD_SERVER_MODE); } } catch (Exception e) { exceptionToControlChannel(e, "ocurred during retrieve()"); } }; //override public void abort() throws IOException { super.abort(); if (socketPool != null) { socketPool.flush(); } } //override public void close() throws IOException { super.close(); if (transferThreadManager != null) { transferThreadManager.close(); } } /** authenticate socket. if protection on, return authenticated socket wrapped over the original simpleSocket, else return original socket. **/ public static Socket authenticate( Socket simpleSocket, boolean isClientSocket, GSSCredential credential, int protection, DataChannelAuthentication dcau) throws Exception { GSSContext gssContext = null; GSSManager manager = ExtendedGSSManager.getInstance(); if (isClientSocket) { gssContext = manager.createContext( null, GSSConstants.MECH_OID, credential, GSSContext.DEFAULT_LIFETIME); } else { gssContext = manager.createContext(credential); } if (protection != GridFTPSession.PROTECTION_CLEAR) { ((ExtendedGSSContext) gssContext).setOption( GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); } gssContext.requestConf(protection == GridFTPSession.PROTECTION_PRIVATE); //Wrap the simple socket with GSI logger.debug("Creating secure socket"); GssSocketFactory factory = GssSocketFactory.getDefault(); GssSocket secureSocket = (GssSocket) factory.createSocket(simpleSocket, null, 0, gssContext); secureSocket.setUseClientMode(isClientSocket); if (dcau == null) { secureSocket.setAuthorization(null); } else if (dcau == DataChannelAuthentication.SELF) { secureSocket.setAuthorization(SelfAuthorization.getInstance()); } else if (dcau == DataChannelAuthentication.NONE) { // this should never be } else if (dcau instanceof DataChannelAuthentication) { // dcau.toFtpCmdArgument() kinda hackish but it works secureSocket.setAuthorization( new IdentityAuthorization(dcau.toFtpCmdArgument())); } /* that will force handshake */ secureSocket.getOutputStream().flush(); if (protection == GridFTPSession.PROTECTION_SAFE || protection == GridFTPSession.PROTECTION_PRIVATE) { logger.debug("Data channel protection: on"); return secureSocket; } else { // PROTECTION_CLEAR logger.debug("Data channel protection: off"); return simpleSocket; } } protected TransferContext createTransferContext() { EBlockParallelTransferContext context = new EBlockParallelTransferContext(); context.setSocketPool(socketPool); context.setTransferThreadManager(this.transferThreadManager); return context; } public TransferThreadManager createTransferThreadManager() { return new TransferThreadManager(socketPool, this, localControlChannel, gSession); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/000077500000000000000000000000001241116057200263735ustar00rootroot00000000000000BasicClientControlChannel.java000066400000000000000000000041211241116057200341670ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; import org.globus.ftp.exception.FTPReplyParseException; import java.io.IOException; import org.globus.ftp.exception.ServerException; /** Basic subset of client side control channel functionality, enough to implement the part of transfer after sending transfer command (RETR) up until receiving 200 reply. **/ public abstract class BasicClientControlChannel{ public static final int WAIT_FOREVER = -1; public abstract Reply read() throws ServerException, IOException, FTPReplyParseException; /** Return when reply is waiting **/ public void waitFor(Flag flag, int waitDelay) throws ServerException, IOException, InterruptedException { waitFor(flag, waitDelay, WAIT_FOREVER); } /** Block until reply is waiting in the control channel, or after timeout (maxWait), or when flag changes to true. If maxWait == WAIT_FOREVER, do not timeout. @param maxWait timeout in miliseconds **/ public abstract void waitFor(Flag flag, int waitDelay, int maxWait) throws ServerException, IOException, InterruptedException; /* public void write(Command cmd) throws IOException, IllegalArgumentException; */ public abstract void abortTransfer(); } //FTPServerFacade BasicServerControlChannel.java000066400000000000000000000024341241116057200342240ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; /** Basic subset of server side control channel functionality. Using this class, local server can send replies but not receive commands. **/ public interface BasicServerControlChannel{ /** write reply to the control channel **/ public void write(Reply reply); /** @return number of replies sent so far **/ public int getReplyCount(); /** set reply count to 0. If this function is used consequently at the beginning of each transfer, then reply count will always indicate number of messages of last transfer. **/ public void resetReplyCount(); } //BasicServerControlChannel JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/Command.java000066400000000000000000000054571241116057200306270ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; /** * Represents an FTP Control Channel Command */ public class Command { public static final Command FEAT = new Command("FEAT"); public static final Command ABOR = new Command("ABOR"); public static final Command CDUP = new Command("CDUP"); public static final Command PWD = new Command("PWD"); public static final Command QUIT = new Command("QUIT"); public static final Command PASV = new Command("PASV"); public static final Command SPAS = new Command("SPAS"); public static final Command EPSV = new Command("EPSV"); /////////////////////////////////////// // attributes private String name; private String parameters; /////////////////////////////////////// // operations /** * @param name the command name, eg. "PUT" * @param parameters the command parameters; in other words everything that * is contained between the space after the command name and the trailing * Telnet EOL, excluding both the mentioned space and EOL. For instance, * in command "STOR /tmp/file.txt\r\n", the parameters would be: * "/tmp/file.txt" * and trailing EOL. */ public Command(String name, String parameters) throws IllegalArgumentException{ initialize(name, parameters); } // end Command public Command(String name) throws IllegalArgumentException{ initialize(name, null); } private void initialize(String name, String parameters) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("null name"); } if (parameters != null && parameters.endsWith(FTPControlChannel.CRLF)) { throw new IllegalArgumentException("parameters end with EOL"); } this.name = name; this.parameters = parameters; } // end initialize /** * @return a String representation of this object, that is * *

    */ public static String toString(Command command) { return command.toString(); } public String toString() { if (parameters == null) { return name + FTPControlChannel.CRLF; } else { return name + " " + parameters + FTPControlChannel.CRLF; } } } // end Command JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/FTPControlChannel.java000066400000000000000000000344561241116057200325350ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; import java.net.Socket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import org.globus.common.CoGProperties; import org.globus.net.SocketFactory; import org.globus.ftp.exception.ServerException; import org.globus.ftp.exception.UnexpectedReplyCodeException; import org.globus.ftp.exception.FTPReplyParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

    * Represents FTP Protocol Interpreter. Encapsulates * control channel communication. * *

    */ public class FTPControlChannel extends BasicClientControlChannel { private static Log logger = LogFactory.getLog(FTPControlChannel.class.getName()); public static final String CRLF = "\r\n"; // used in blocking waitForReply() private static final int WAIT_FOREVER = -1; protected Socket socket; //input stream protected BufferedReader ftpIn; //raw stream underlying ftpIn protected InputStream rawFtpIn; //output stream protected OutputStream ftpOut; protected String host; protected int port; //true if connection has already been opened. protected boolean hasBeenOpened = false; private boolean ipv6 = false; private Reply lastReply; public FTPControlChannel(String host, int port) { this.host = host; this.port = port; this.ipv6 = (this.host.indexOf(':') != -1); } /** * Using this constructor, you can initialize an instance that does not * talk directly to the socket. If you use this constructor using streams * that belong to an active connection, there's no need to call open() * afterwards. **/ public FTPControlChannel(InputStream in, OutputStream out) { setInputStream(in); setOutputStream(out); } public String getHost() { return this.host; } public int getPort() { return this.port; } public boolean isIPv6() { return this.ipv6; } protected BufferedReader getBufferedReader() { return ftpIn; } protected OutputStream getOutputStream() { return ftpOut; } // not intended to be public. you can set streams in the constructor. protected void setInputStream(InputStream in) { rawFtpIn = in; ftpIn = new BufferedReader(new InputStreamReader(rawFtpIn)); } protected void setOutputStream(OutputStream out) { ftpOut = out; } /** * opens the connection and returns after it is ready for communication. * Before returning, it intercepts the initial server reply(-ies), * and not positive, throws UnexpectedReplyCodeException. * After returning, there should be no more queued replies on the line. * * Here's the sequence for connection establishment (rfc959): *
         *     120
         *         220
         *     220
         *     421
         *
    * @throws IOException on I/O error * @throws ServerException on negative or faulty server reply **/ public void open() throws IOException, ServerException { if (hasBeenOpened()) { throw new IOException("Attempt to open an already opened connection"); } InetAddress allIPs[]; //depending on constructor used, we may already have streams if (!haveStreams()) { boolean found = false; int i = 0; boolean firstPass = true; allIPs = InetAddress.getAllByName(host); while(!found) { try { logger.debug("opening control channel to " + allIPs[i] + " : " + port); InetSocketAddress isa = new InetSocketAddress(allIPs[i], port); socket = new Socket(); socket.setSoTimeout(CoGProperties.getDefault().getSocketTimeout()); socket.connect(isa, CoGProperties.getDefault().getSocketTimeout()); found = true; } catch(IOException ioEx) { logger.debug("failed connecting to " + allIPs[i] + " : " + port +":"+ioEx); i++; if(i == allIPs.length) { if(firstPass) { firstPass = false; i = 0; } else { throw ioEx; } } } } String pv = System.getProperty("org.globus.ftp.IPNAME"); if(pv != null) { host = socket.getInetAddress().getHostAddress(); } else { host = socket.getInetAddress().getCanonicalHostName(); } setInputStream(socket.getInputStream()); setOutputStream(socket.getOutputStream()); } readInitialReplies(); hasBeenOpened = true; } //intercepts the initial replies //(that the server sends after opening control ch.) protected void readInitialReplies() throws IOException, ServerException { Reply reply = null; try { reply = read(); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException( rpe, "Received faulty initial reply"); } if (Reply.isPositivePreliminary(reply)) { try { reply = read(); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException( rpe, "Received faulty second reply"); } } if (!Reply.isPositiveCompletion(reply)) { close(); throw ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(reply), "Server refused connection."); } } /** * Returns the last reply received from the server. */ public Reply getLastReply() { return lastReply; } /** * Closes the control channel */ public void close() throws IOException { logger.debug("ftp socket closed"); if (ftpIn != null) ftpIn.close(); if (ftpOut != null) ftpOut.close(); if (socket != null) socket.close(); hasBeenOpened = false; } private int checkSocketDone(Flag aborted, int ioDelay, int maxWait) throws ServerException, IOException, InterruptedException { int oldTOValue = this.socket.getSoTimeout(); int c = -10; int time = 0; boolean done = false; if (ioDelay <= 0) { ioDelay = 2000; } while(!done) { try { if (aborted.flag) { throw new InterruptedException(); } this.socket.setSoTimeout(ioDelay); ftpIn.mark(2); c = ftpIn.read(); done = true; } catch (SocketTimeoutException e) { // timeouts will happen logger.debug("temp timeout" + e); } catch (Exception e) { throw new InterruptedException(); } finally { ftpIn.reset(); this.socket.setSoTimeout(oldTOValue); } time += ioDelay; if(time > maxWait && maxWait != WAIT_FOREVER) { throw new ServerException(ServerException.REPLY_TIMEOUT); } } return c; } /** Block until one of the conditions are true:
    1. a reply is available in the control channel,
    2. timeout (maxWait) expired
    3. aborted flag changes to true.
    If maxWait == WAIT_FOREVER, never timeout and only check conditions (1) and (3). @param maxWait timeout in miliseconds @param ioDelay frequency of polling the control channel and checking the conditions @param aborted flag indicating wait aborted. **/ public void waitFor(Flag aborted, int ioDelay, int maxWait) throws ServerException, IOException, InterruptedException { int oldTimeout = this.socket.getSoTimeout(); try { int c = 0; if (maxWait != WAIT_FOREVER) { this.socket.setSoTimeout(maxWait); } else { this.socket.setSoTimeout(0); } c = this.checkSocketDone(aborted, ioDelay, maxWait); /* A bug in the server causes it to append \0 to each reply. As the result, we receive this \0 before the next reply. The code below handles this case. */ if (c != 0) { // if we're here, the server is healthy // and the reply is waiting in the buffer return; } // if we're here, we deal with the buggy server. // we discarded the \0 and now resume wait. logger.debug("Server sent \\0; resume wait"); try { // gotta read past the 0 we just remarked c = ftpIn.read(); c = this.checkSocketDone(aborted, ioDelay, maxWait); } catch (SocketTimeoutException e) { throw new ServerException(ServerException.REPLY_TIMEOUT); } catch (EOFException e) { throw new InterruptedException(); } } finally { this.socket.setSoTimeout(oldTimeout); } } /** * Block until a reply is available in the control channel. * @return the first unread reply from the control channel. * @throws IOException on I/O error * @throws FTPReplyParseException on malformatted server reply **/ public Reply read() throws ServerException, IOException, FTPReplyParseException, EOFException { Reply reply = new Reply(ftpIn); //System.out.println("FTP IN string "+reply.toString()); if (logger.isDebugEnabled()) { logger.debug("Control channel received: " + reply); } lastReply = reply; return reply; } public void abortTransfer() { } /** * Sends the command over the control channel. * Do not wait for reply. * @throws java.io.IOException on I/O error * @param cmd FTP command */ public void write(Command cmd) throws IOException, IllegalArgumentException { //we delete the initial reply when the first command is sent if (cmd == null) { throw new IllegalArgumentException("null argument: cmd"); } if (logger.isDebugEnabled()) { logger.debug("Control channel sending: " + cmd); } writeStr(cmd.toString()); } /** * Write the command to the control channel, * block until reply arrives and return the reply. * Before calling this method make sure that no old replies are * waiting on the control channel. Otherwise the reply returned * may not be the reply to this command. * @throws java.io.IOException on I/O error * @throws FTPReplyParseException on bad reply format * @param cmd FTP command * @return the first reply that waits in the control channel **/ public Reply exchange(Command cmd) throws ServerException, IOException, FTPReplyParseException { // send the command write(cmd); // get the reply return read(); } /** * Write the command to the control channel, * block until reply arrives and check if the command * completed successfully (reply code 200). * If so, return the reply, otherwise throw exception. * Before calling this method make sure that no old replies are * waiting on the control channel. Otherwise the reply returned * may not be the reply to this command. * @throws java.io.IOException on I/O error * @throws FTPReplyParseException on bad reply format * @throws UnexpectedReplyCodeException if reply is not a positive * completion reply (code 200) * @param cmd FTP command * @return the first reply that waits in the control channel **/ public Reply execute(Command cmd) throws ServerException, IOException, FTPReplyParseException, UnexpectedReplyCodeException { Reply reply = exchange(cmd); // check for positive reply if (!Reply.isPositiveCompletion(reply)) { throw new UnexpectedReplyCodeException(reply); } return reply; } protected void writeln(String msg) throws IOException { writeStr(msg + CRLF); } protected void writeStr(String msg) throws IOException { ftpOut.write(msg.getBytes()); ftpOut.flush(); } protected boolean hasBeenOpened() { return hasBeenOpened; } protected boolean haveStreams() { return (ftpIn != null && ftpOut != null); } } // end StandardPI JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/FTPServerFacade.java000066400000000000000000000434311241116057200321470ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; import org.globus.net.SocketFactory; import org.globus.util.Util; import org.globus.net.ServerSocketFactory; import org.globus.ftp.exception.FTPException; import org.globus.ftp.exception.ServerException; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.FTPReplyParseException; import org.globus.ftp.Session; import org.globus.ftp.HostPort; import org.globus.ftp.HostPort6; import org.globus.ftp.DataSource; import org.globus.ftp.Options; import org.globus.ftp.DataSink; import org.globus.ftp.dc.DataChannelFactory; import org.globus.ftp.dc.TaskThread; import org.globus.ftp.dc.Task; import org.globus.ftp.dc.ActiveConnectTask; import org.globus.ftp.dc.TransferContext; import org.globus.ftp.dc.PassiveConnectTask; import org.globus.ftp.dc.SimpleDataChannelFactory; import org.globus.ftp.dc.SimpleTransferContext; import org.globus.ftp.dc.LocalReply; import java.io.IOException; import java.net.ServerSocket; import java.net.UnknownHostException; import java.net.Socket; import java.util.LinkedList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** This class is not ment directly for the users. This class represents the part of the client responsible for data channel management. Especially when the remote server is in the passive mode, it behaves a lot like a local server. Thus its interface looks very much like a server interface.
    Current implementation is multithreaded. One thread is used for thread management and one for each transfer (this makes sense in GridFTP parallelism).
    The public methods can generally be divided into setter methods and active methods. Active methods are setActive(), setPassive(), retrieve(), and store(), and setter methods are the remaining. Setter methods do not generally throw exceptions related to ftp. Settings are not checked for correctness until the server is asked to performed some action, which is done by active methods. So you are safe to cal setXX() methods with any argument you like, until you call one of the "active" methods mentioned above.
    The managing thread is not started until one of the "active" methods is called: setActive(), retrieve(), or store(). These methods are asynchronous (return before completion) and the action is undertaken by the local manager thread. From this point on, all communication back to the caller is done through unidirectional local control channel. Information is communicated back to the user in form of FTP replies (instances of LocalReply). Generally, the sequence of replies should be the same as when communicating with remote server during the transfer (1xx intermediary reply; markers; final 226). Exceptions are serialized into 451 negative reply. **/ public class FTPServerFacade { private static Log logger = LogFactory.getLog(FTPServerFacade.class.getName()); /** local server socket parameter; used in setPassive() **/ public static final int ANY_PORT = 0; /** local server socket parameter; used in setPassive() **/ public static final int DEFAULT_QUEUE = 100; protected Session session; protected LocalControlChannel localControlChannel; protected DataChannelFactory dataChannelFactory; protected ServerSocket serverSocket; protected FTPControlChannel remoteControlChannel; protected HostPort remoteServerAddress; // used only by FTPServerFacade private TaskThread taskThread; /** Data channels are operated in multithreaded manner and they pass information (including exceptions) to the user using the local control channel. In the unlikely event that it fails, there is no way to communicate the exception to the user. In such circumstances this method should be called to print the exception directly to console. **/ public static void cannotPropagateError(Throwable e) { logger.error("Exception occured in the exception handling " + "code, so it cannot be properly propagated to " + "the user", e); } public FTPServerFacade(FTPControlChannel remoteControlChannel) { this.remoteControlChannel = remoteControlChannel; this.session = new Session(); this.localControlChannel = new LocalControlChannel(); this.dataChannelFactory = new SimpleDataChannelFactory(); } /** Use this method to get the client end of the local control channel. It is the only way to get the information of the current transfer state. **/ public BasicClientControlChannel getControlChannel() { return localControlChannel; } /** @return the session object associated with this server **/ public Session getSession() { return session; } // unconditional authorization /** No need for parameters; locally you are always authorized. **/ public void authorize() { session.authorized = true; } public void setTransferType(int type) { session.transferType = type; } public void setTransferMode(int mode) { session.transferMode = mode; } public void setProtectionBufferSize(int size) { session.protectionBufferSize = size; } /** Do nothing; this class does not support any options **/ public void setOptions(Options opts) { } /** Behave like setPassive(ANY_PORT, DEFAULT_QUEUE) **/ public HostPort setPassive() throws IOException{ return setPassive(ANY_PORT, DEFAULT_QUEUE); } /** Start the local server @param port required server port; can be set to ANY_PORT @param queue max size of queue of awaiting new connection requests @return the server address **/ public HostPort setPassive(int port, int queue) throws IOException{ if (serverSocket == null) { ServerSocketFactory factory = ServerSocketFactory.getDefault(); serverSocket = factory.createServerSocket(port, queue); } session.serverMode = Session.SERVER_PASSIVE; String address = Util.getLocalHostAddress(); int localPort = serverSocket.getLocalPort(); if (remoteControlChannel.isIPv6()) { String version = HostPort6.getIPAddressVersion(address); session.serverAddress = new HostPort6(version, address, localPort); } else { session.serverAddress = new HostPort(address, localPort); } logger.debug("started passive server at port " + session.serverAddress.getPort()); return session.serverAddress; } /** Asynchronous; return before completion. Connect to the remote server. Any exception that would occure will not be thrown but returned through the local control channel. **/ public void setActive(HostPort hp) throws UnknownHostException, ClientException, IOException { if (logger.isDebugEnabled()) { logger.debug("hostport: " + hp.getHost() + " " + hp.getPort()); } session.serverMode = Session.SERVER_ACTIVE; this.remoteServerAddress = hp; } /** Convert the exception to a negative 451 reply, and pipe it to the control channel. **/ protected void exceptionToControlChannel(Throwable e, String msg) { // this could be reimplemented. // Now the exception is serialized to the control channel. // but it could be simply appended to the LocalReply, // if LocalReply had such functionality. exceptionToControlChannel(e, msg, localControlChannel); } /** Convert the exception to a negative 451 reply, and pipe it to the provided control channel. **/ public static void exceptionToControlChannel( Throwable e, String msg, BasicServerControlChannel control) { // how to convert exception stack trace to string? // i am sure it can be done easier. java.io.StringWriter writer = new java.io.StringWriter(); e.printStackTrace(new java.io.PrintWriter(writer)); String stack = writer.toString(); // 451 Requested action aborted: local error in processing. LocalReply reply = new LocalReply(451, msg + "\n" + e.toString() + "\n" + stack); control.write(reply); } /** Asynchronous; return before completion. Start the incoming transfer and store the file to the supplied data sink. Any exception that would occure will not be thrown but returned through the local control channel. **/ public void store(DataSink sink) { try { localControlChannel.resetReplyCount(); TransferContext context= createTransferContext(); if (session.serverMode == Session.SERVER_PASSIVE) { runTask(createPassiveConnectTask(sink, context)); } else { runTask(createActiveConnectTask(sink, context)); } } catch (Exception e) { exceptionToControlChannel(e, "ocurred during store()"); } } /** Asynchronous; return before completion. Start the outgoing transfer reading the data from the supplied data source. Any exception that would occure will not be thrown but returned through the local control channel. **/ public void retrieve(DataSource source) { try { localControlChannel.resetReplyCount(); TransferContext context= createTransferContext(); if (session.serverMode == Session.SERVER_PASSIVE) { runTask(createPassiveConnectTask(source, context)); } else { runTask(createActiveConnectTask(source, context)); } } catch (Exception e) { exceptionToControlChannel(e, "ocurred during retrieve()"); } } /** close data channels, but not control, nor the server **/ public void abort() throws IOException{ } protected void transferAbort() { if (session.serverMode == Session.SERVER_PASSIVE) { unblockServer(); stopTaskThread(); } } protected void unblockServer() { if (serverSocket == null) { return; } String address = Util.getLocalHostAddress(); int port = serverSocket.getLocalPort(); // this is a hack to ensue the server socket is // unblocked from accpet() // but this is not guaranteed to work still SocketFactory factory = SocketFactory.getDefault(); Socket s = null; try { s = factory.createSocket(address, port); s.getInputStream(); } catch (Exception e) { } finally { if (s != null) { try { s.close(); } catch (Exception e) {} } } } public void close() throws IOException { logger.debug("close data channels"); abort(); logger.debug("close server socket"); if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { } unblockServer(); } stopTaskThread(); } /** Use this as an interface to the local manager thread. This submits the task to the thread queue. The thread will perform it when it's ready with other waiting tasks. **/ private synchronized void runTask(Task task) { if (taskThread == null) { taskThread = new TaskThread(); } taskThread.runTask(task); } protected synchronized void stopTaskThread() { logger.debug("stop master thread"); if (taskThread != null) { taskThread.stop(); taskThread.join(); taskThread = null; } } // task "factories": // use these methods to create tasks private PassiveConnectTask createPassiveConnectTask(DataSource source, TransferContext context) { return new PassiveConnectTask(serverSocket, source, localControlChannel, session, dataChannelFactory, context); } private PassiveConnectTask createPassiveConnectTask(DataSink sink, TransferContext context) { return new PassiveConnectTask(serverSocket, sink, localControlChannel, session, dataChannelFactory, context); } private ActiveConnectTask createActiveConnectTask(DataSource source, TransferContext context) { return new ActiveConnectTask(this.remoteServerAddress, source, localControlChannel, session, dataChannelFactory, context); } private ActiveConnectTask createActiveConnectTask(DataSink sink, TransferContext context) { return new ActiveConnectTask(this.remoteServerAddress, sink, localControlChannel, session, dataChannelFactory, context); } // inner classes /** This inner class represents a local control channel. One process can write replies using BasicServerControlChannel interface, and the other can read replies using BasicClientControlChannel interface. **/ protected class LocalControlChannel extends BasicClientControlChannel implements BasicServerControlChannel{ // FIFO queue of Replies private LinkedList replies = null; // how many replies have been pushed so far private int replyCount = 0; public LocalControlChannel() { replies = new LinkedList(); } protected synchronized void push(Reply newReply) { replies.add(newReply); replyCount++; notify(); } // blocking pop from queue protected synchronized Reply pop() throws InterruptedException { while (replies.isEmpty()) { wait(); } return (Reply)replies.removeFirst(); } //non blocking; check if queue is ready for pop public synchronized boolean ready() { return (!replies.isEmpty()); } public synchronized int getReplyCount() { return replyCount; } public synchronized void resetReplyCount() { replies.clear(); replyCount = 0; } public Reply read() throws IOException, FTPReplyParseException, ServerException{ try { return pop(); } catch (InterruptedException e) { ServerException se = new ServerException(FTPException.UNSPECIFIED, "interrupted while waiting."); se.setRootCause(e); throw se; } } public void write(Reply reply) { push(reply); } public void waitFor(Flag aborted, int ioDelay, int maxWait) throws ServerException, IOException, InterruptedException{ int i = 0; logger.debug("waiting for reply in local control channel"); while( !ready()) { if (aborted.flag) { throw new InterruptedException(); } if (maxWait != WAIT_FOREVER && i >= maxWait) { logger.debug("timeout"); throw new ServerException(ServerException.REPLY_TIMEOUT, "Max wait was " + maxWait + " and ioDelay " + ioDelay); } Thread.sleep(ioDelay); logger.debug("slept " + i); i += ioDelay; } logger.debug("local control channel ready"); } public void abortTransfer() { transferAbort(); } }// class localControlChannel protected TransferContext createTransferContext() { return SimpleTransferContext.getDefault(); } } // FTPServerFacade JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/Flag.java000066400000000000000000000013161241116057200301100ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; /** A semaphore **/ public class Flag { public boolean flag = false; } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/Reply.java000066400000000000000000000163401241116057200303350ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; import org.globus.ftp.exception.FTPReplyParseException; import java.io.Serializable; import java.io.EOFException; import java.io.IOException; import java.io.BufferedReader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // FTPReplyParseException - move line to exception // internationalize exceptions /** *

    * Represents the FTP reply. *

    */ public class Reply implements Serializable { private static Log logger = LogFactory.getLog(Reply.class.getName()); public static final int POSITIVE_PRELIMINARY = 1; public static final int POSITIVE_COMPLETION = 2; public static final int POSITIVE_INTERMEDIATE = 3; public static final int TRANSIENT_NEGATIVE_COMPLETION = 4; public static final int PERMANENT_NEGATIVE_COMPLETION = 5; //minimum length of 1st line: //message is defined as 3 chars + + + //so if text is empty, minimum 1st line length = 4 private static final int MIN_FIRST_LEN = 4; // instance members protected String message; protected int code; protected int category; protected boolean isMultiline; // for subclassing protected Reply() {}; /** * @throws EOFException on end of stream * @throws IOException on I/O problem * @throws FTPReplyParseException if cannot parse **/ public Reply(BufferedReader input) throws FTPReplyParseException, EOFException, IOException { logger.debug( "read 1st line"); String line = input.readLine(); if (logger.isDebugEnabled()) { logger.debug( "1st line: " + line); } //end of stream if (line == null) { throw new EOFException(); } //for compatibility with GT2.0 wuftp server which is incorrectly inserting \0 between lines line = ignoreLeading0(line); if(line.length() < MIN_FIRST_LEN) { throw new FTPReplyParseException( FTPReplyParseException.STRING_TOO_SHORT, "Minimum 1st line length = " + MIN_FIRST_LEN + ". Here's the incorrect 1st line ->" + line + "<-"); } // code String codeString = line.substring(0,3); try { code = Integer.parseInt(codeString); } catch (NumberFormatException e) { throw new FTPReplyParseException( FTPReplyParseException.FIRST_3_CHARS, "Here's the incorrect line ->" + line + "<-" + "and the first 3 chars ->" + codeString + "<-" ); } // category category = line.charAt(0) - '0'; // message char char4 = line.charAt(3); //do not include 4th char in message message = line.substring(4, line.length()); if (char4 == ' ') { //single line reply isMultiline = false; } else if (char4 == '-') { //multi - line reply isMultiline = true; String lastLineStarts = codeString + ' '; //platform dependent line separator String lineSeparator = System.getProperty("line.separator"); if (logger.isDebugEnabled()) { logger.debug( "multiline reply; last line should start with ->" + lastLineStarts + "<-"); logger.debug("lenght of line.separator on this OS: " + lineSeparator.length()); } StringBuffer buf = new StringBuffer(message); for (;;) { logger.debug( "read line"); line = input.readLine(); //end of stream if (line == null) { throw new EOFException(); } //for compatibility with GT2.0 wuftp server //which is incorrectly inserting \0 between lines line = ignoreLeading0(line); if (logger.isDebugEnabled()) { logger.debug( "line : ->" + line + "<-"); } buf.append(lineSeparator).append(line); if (line.startsWith(lastLineStarts)) { logger.debug("end reached"); break; } } message = buf.toString(); } else { throw new FTPReplyParseException( FTPReplyParseException.UNEXPECTED_4TH_CHAR, "Here's the incorrect line ->" + line + "<-" ); } } /** * * @return the first digit of the reply code. * */ public int getCategory() { return category; } /** * @return the reply code */ public int getCode() { return code; } public boolean isMultiline() { return isMultiline; } /** *

    * Returns the text that came with the reply, between the leading space and * terminating CRLF, excluding the mentioned space and CRLF. *

    *

    * If the reply is multi-line, this returns the text between the leading * dash "-" and the CRLF following the last line, excluding the mentioned * dash and CRLF. Note that lines are separated by the local line separator * [as returned by System.getProperty("line.separator")] rather than CRLF. * *

    *

    * *

    */ public String getMessage() { return message; } public static boolean isPositivePreliminary(Reply reply) { return (reply.getCategory() == POSITIVE_PRELIMINARY); } public static boolean isPositiveCompletion(Reply reply) { return (reply.getCategory() == POSITIVE_COMPLETION); } public static boolean isPositiveIntermediate(Reply reply) { return (reply.getCategory() == POSITIVE_INTERMEDIATE); } public static boolean isTransientNegativeCompletion(Reply reply) { return (reply.getCategory() == TRANSIENT_NEGATIVE_COMPLETION); } public static boolean isPermanentNegativeCompletion(Reply reply) { return (reply.getCategory() == PERMANENT_NEGATIVE_COMPLETION); } public String toString() { String mult = isMultiline ? "-" : " "; return code + mult + message; } /** GT2.0 wuftp server incorrectly inserts \0 between lines. We have to deal with that. **/ protected static String ignoreLeading0(String line) { if (line.length() > 0 && line.charAt(0) == 0) { logger.debug("WARNING: The first character of the reply is 0. Ignoring the character."); /* logger.debug( "\n\nWARNING:\n In the reply received from the server, the first character's code is 0! I will ignore it but this means the server is not following the protocol. Here's the details: \n first line of the reply ->" + line + "<-"); logger.debug( "First 3 chars of reply->" +line.substring(0,3)+"<-"); logger.debug( "char 0 ->" + line.charAt(0) + "<- code = " + (int)line.charAt(0)); logger.debug( "char 1 ->" + line.charAt(1) + "<- code = " + (int)line.charAt(1)); logger.debug( "char 2 ->" + line.charAt(2) + "<- code = " + (int)line.charAt(2)); logger.debug( "char 3 ->" + line.charAt(3) + "<- code = " + (int)line.charAt(3)); */ return line.substring(1, line.length()); } return line; } } // end Reply JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/TransferMonitor.java000066400000000000000000000201401241116057200323670ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; import org.globus.ftp.MarkerListener; import org.globus.ftp.PerfMarker; import org.globus.ftp.GridFTPRestartMarker; import org.globus.ftp.exception.ServerException; import org.globus.ftp.exception.UnexpectedReplyCodeException; import org.globus.ftp.exception.FTPReplyParseException; import java.io.InterruptedIOException; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class TransferMonitor implements Runnable { public final static int LOCAL = 1, REMOTE = 2; private int side; // source or dest private Log logger = null; private int maxWait; private int ioDelay; private BasicClientControlChannel controlChannel; private TransferState transferState; private MarkerListener mListener; private TransferMonitor other; private boolean abortable; private Flag aborted = new Flag(); private Thread thread; public TransferMonitor(BasicClientControlChannel controlChannel, TransferState transferState, MarkerListener mListener, int maxWait, int ioDelay, int side) { logger = LogFactory.getLog(TransferMonitor.class.getName() + ((side == LOCAL) ? ".Local" : ".Remote")); this.controlChannel = controlChannel; this.transferState = transferState; this.mListener = mListener; this.maxWait = maxWait; this.ioDelay = ioDelay; abortable = true; aborted.flag = false; this.side = side; } /** In this class, each instance gets a separate logger which is assigned the name in the constructor. This name is in the form "...GridFTPClient.thread host:port". @return the logger name. **/ public String getLoggerName() { return logger.toString(); } public void setOther(TransferMonitor other) { this.other = other; } /** * Abort the tpt transfer * but do not close resources */ public synchronized void abort() { logger.debug("abort"); if (!this.abortable) { return; } controlChannel.abortTransfer(); aborted.flag = true; } private synchronized void done() { this.abortable = false; } public void start(boolean blocking) { if (blocking) { this.thread = Thread.currentThread(); run(); } else { this.thread = new Thread(this); this.thread.setName("TransferMonitor" + this.thread.getName()); this.thread.start(); } } public void run() { try { // if the other thread had already terminated // with an error, behave as if it happened just now. if (transferState.hasError()) { logger.debug("the other thread terminated before this one started."); throw new InterruptedException(); } logger.debug("waiting for 1st reply; maxWait = " + maxWait + ", ioDelay = " + ioDelay); this.controlChannel.waitFor(aborted, ioDelay, maxWait); logger.debug("reading first reply"); Reply firstReply = controlChannel.read(); // 150 Opening BINARY mode data connection. // or // 125 Data connection already open; transfer starting if (Reply.isPositivePreliminary(firstReply)) { transferState.transferStarted(); logger.debug("first reply OK: " + firstReply.toString()); for(;;) { logger.debug("reading next reply"); this.controlChannel.waitFor(aborted, ioDelay, maxWait); logger.debug("got next reply"); Reply nextReply = controlChannel.read(); //perf marker if (nextReply.getCode() == 112) { logger.debug("marker arrived: " + nextReply.toString()); if (mListener != null) { mListener.markerArrived( new PerfMarker(nextReply.getMessage())); } continue; } //restart marker if (nextReply.getCode() == 111) { logger.debug("marker arrived: " + nextReply.toString()); if (mListener != null) { mListener.markerArrived( new GridFTPRestartMarker( nextReply.getMessage())); } continue; } //226 Transfer complete if (nextReply.getCode() == 226) { abortable = false; logger.debug("transfer complete: " + nextReply.toString()); break; } // any other reply logger.debug("unexpected reply: " + nextReply.toString()); logger.debug("exiting the transfer thread"); ServerException e = ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(nextReply), "Server reported transfer failure"); transferState.transferError(e); other.abort(); break; } } else { //first reply negative logger.debug("first reply bad: " + firstReply.toString()); logger.debug("category: " + firstReply.getCategory()); abortable = false; ServerException e = ServerException.embedUnexpectedReplyCodeException( new UnexpectedReplyCodeException(firstReply)); transferState.transferError(e); other.abort(); } logger.debug("thread dying naturally"); } catch (InterruptedException td) { //other transfer thread called abort() logger.debug("thread dying of InterruptedException."); transferState.transferError(td); } catch (InterruptedIOException td) { //other transfer thread called abort() which occurred //while this thread was performing IO logger.debug("thread dying of InterruptedIOException."); transferState.transferError(td); } catch (IOException e) { logger.debug("thread dying of IOException"); transferState.transferError(e); other.abort(); } catch (FTPReplyParseException rpe) { logger.debug("thread dying of FTPReplyParseException"); ServerException se = ServerException.embedFTPReplyParseException(rpe); transferState.transferError(se); other.abort(); } catch (ServerException e) { logger.debug("thread dying of timeout"); transferState.transferError(e); other.abort(); } finally { done(); transferState.transferDone(); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/main/java/org/globus/ftp/vanilla/TransferState.java000066400000000000000000000074301241116057200320270ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.vanilla; import java.io.InterruptedIOException; import java.io.IOException; import org.globus.ftp.MarkerListener; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.ServerException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class TransferState { private static Log logger = LogFactory.getLog(TransferState.class.getName()); private int transferDone; private int transferStarted; private Exception transferException = null; public TransferState() { this.transferDone = 0; this.transferStarted = 0; this.transferException = null; } // this is called when transfer successfully started (opening data conn) public synchronized void transferStarted() { this.transferStarted++; notifyAll(); } // this is called when TransferMonitor thread is finished public synchronized void transferDone() { this.transferDone++; notifyAll(); } // this is called when an error occurs during transfer public synchronized void transferError(Exception e) { logger.debug("intercepted exception", e); if (transferException == null) { transferException = e; } else if (transferException instanceof InterruptedException || transferException instanceof InterruptedIOException) { //if one of the threads throws an error, it interrupts //the other thread (by InterruptedException). //Here we make sure that transferException will store the //primary failure reason, not the resulting InterruptedException transferException = e; } notifyAll(); } public synchronized boolean isDone() { return this.transferDone >= 2; } public synchronized boolean isStarted() { return this.transferStarted >= 2; } /** * Blocks until the transfer is complete or * the transfer fails. */ public synchronized void waitForEnd() throws ServerException, ClientException, IOException { try { while(!isDone() && !hasError()) { wait(); } } catch(InterruptedException e) { // break } checkError(); } /** * Blocks until the transfer begins or * the transfer fails to start. */ public synchronized void waitForStart() throws ServerException, ClientException, IOException { try { while(!isStarted() && !hasError()) { wait(); } } catch(InterruptedException e) { // break } checkError(); } public synchronized boolean hasError() { return (transferException != null); } public Exception getError() { return transferException; } public void checkError() throws ServerException, ClientException, IOException { if (transferException == null) { return; } if (transferException instanceof ServerException) { throw (ServerException)transferException; } else if (transferException instanceof IOException) { throw (IOException)transferException; } else if (transferException instanceof InterruptedException) { throw new ClientException(ClientException.THREAD_KILLED); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/000077500000000000000000000000001241116057200212045ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/000077500000000000000000000000001241116057200221255ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/000077500000000000000000000000001241116057200227145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/000077500000000000000000000000001241116057200242075ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/000077500000000000000000000000001241116057200250005ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/000077500000000000000000000000001241116057200257575ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/AsciiTranslatorTest.java000066400000000000000000000055071241116057200325730ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.dc.AsciiTranslator; import org.globus.ftp.Buffer; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class AsciiTranslatorTest extends TestCase { static Log logger = LogFactory.getLog(AsciiTranslatorTest.class); public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(AsciiTranslatorTest.class); } public AsciiTranslatorTest(String name) { super(name); } public void test1() { crlnTest("\n"); } public void test2() { crlnTest("\r\n"); } public void crlnTest(String lineSep) { AsciiTranslator t = new AsciiTranslator(true, false, lineSep.getBytes()); check(t, "1abcdef", "1abcdef"); check(t, "2abc\r\ndef", "2abc" + lineSep + "def"); check(t, "3abc\r\r\ndef", "3abc\r" + lineSep + "def"); check(t, "4abc\n\n\n\n", "4abc\n\n\n\n"); check(t, "a\rb\r\nc\n\n\r\rd", "a\rb" + lineSep + "c\n\n\r\rd"); check(t, "abc\r", "abc"); check(t, "def", "\rdef"); check(t, "a\r\n\nbc\r", "a" + lineSep + "\nbc"); check(t, "\n\r\ndef", lineSep + lineSep + "def"); } public void test3() { lnTest("\n"); } public void test4() { lnTest("\r\n"); } public void lnTest(String lineSep) { AsciiTranslator t = new AsciiTranslator(false, true, lineSep.getBytes()); check(t, "1abcdef", "1abcdef"); check(t, "2abc\r\ndef", "2abc\r" + lineSep + "def"); check(t, "3abc\r\r\ndef", "3abc\r\r" + lineSep + "def"); check(t, "4abc\n\n\n", "4abc" + lineSep + lineSep + lineSep); check(t, "a\rb\r\nc\n\n\r\rd", "a\rb\r" + lineSep + "c" + lineSep + lineSep + "\r\rd"); check(t, "abc\r", "abc\r"); check(t, "a\r\n\nbc\r", "a\r" + lineSep + lineSep + "bc\r"); check(t, "\n\r\ndef", lineSep + "\r" + lineSep + "def"); } private void check(AsciiTranslator t, String inputStr, String expectedStr) { byte [] input = inputStr.getBytes(); byte [] output = t.translate(new Buffer(input, input.length)).getBuffer(); assertEquals(expectedStr, new String(output)); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/ByteRangeListTest.java000066400000000000000000000201601241116057200321750ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.ByteRange; import org.globus.ftp.ByteRangeList; import java.util.Vector; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test ByteRangeList **/ public class ByteRangeListTest extends TestCase { private static Log logger = LogFactory.getLog(ByteRangeListTest.class.getName()); public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(ByteRangeListTest.class); } public ByteRangeListTest(String name) { super(name); } /** Test merging ByteRange to ByteRangeList. Systematic test of most cases. Tests merge() and toFtpCmdArgument(). Assure that merge() does not modify parameter objects. **/ public void test1() { Vector v = new Vector(); v.add(new ByteRange(12, 17)); v.add(new ByteRange(24, 26)); v.add(new ByteRange(31, 31)); v.add(new ByteRange(40, 45)); v.add(new ByteRange(52, 52)); // t = vector // o = new range // t t t t t = // "12-17 24-26 31-31 40-45 52-52" // o t t t t t assertMerge1(v, 0,5, "0-5,12-17,24-26,31-31,40-45,52-52"); // ot t t t t assertMerge1(v, 7,11, "7-17,24-26,31-31,40-45,52-52"); // o-t t t t t assertMerge1(v, 3,15, "3-17,24-26,31-31,40-45,52-52"); // o-o t t t t assertMerge1(v, 10,18, "10-18,24-26,31-31,40-45,52-52"); // o-ot t t t assertMerge1(v, 10,23, "10-26,31-31,40-45,52-52"); // o-o-t t t t assertMerge1(v, 10,30, "10-31,40-45,52-52"); // o-o-o-o- t assertMerge1(v, 10,50, "10-50,52-52"); // o-o-o-o-o-o assertMerge1(v, 10,53, "10-53"); // t-t t t t t assertMerge1(v, 13,16, "12-17,24-26,31-31,40-45,52-52"); // - t t t t assertMerge1(v, 12,17, "12-17,24-26,31-31,40-45,52-52"); // t-o-o-t t t assertMerge1(v, 16,31, "12-31,40-45,52-52"); // -o-o-o-o-o assertMerge1(v, 12,100, "12-100"); // t o t t t t assertMerge1(v, 24,26, "12-17,24-26,31-31,40-45,52-52"); // t ot t t t assertMerge1(v, 20,23, "12-17,20-26,31-31,40-45,52-52"); // t o-o t t t assertMerge1(v, 20,29, "12-17,20-29,31-31,40-45,52-52"); // t o-ot t t assertMerge1(v, 20,30, "12-17,20-31,40-45,52-52"); // t o-o-o-o t assertMerge1(v, 20,49, "12-17,20-49,52-52"); // t to t t t assertMerge1(v, 27,27, "12-17,24-27,31-31,40-45,52-52"); // t tot t t assertMerge1(v, 27,30, "12-17,24-31,40-45,52-52"); // t to-ot t assertMerge1(v, 26,40, "12-17,24-45,52-52"); // t t t tot assertMerge1(v, 46,51, "12-17,24-26,31-31,40-52"); // t t t t o-t assertMerge1(v, 51,52, "12-17,24-26,31-31,40-45,51-52"); // t t t t -o assertMerge1(v, 52,53, "12-17,24-26,31-31,40-45,52-53"); // t t t t t o assertMerge1(v, 54,67, "12-17,24-26,31-31,40-45,52-52,54-67"); } /** real case (taken from transfer of 500 MB) **/ public void test2() { Vector v = new Vector(); v.add(new ByteRange(0, 134545408)); v.add(new ByteRange(134545408, 298778624)); assertMerge1(v, 298778624, 466747392, "0-466747392"); } /** Ad hoc tests of interesting merge cases. Test merging several ranges into 1 list. Test merge() and toFtpCmdArgument(). **/ public void test3() { //merge 2 -> 1 Vector v = new Vector();; v.add(new ByteRange(1,3)); v.add(new ByteRange(4,6)); assertMerge(v,"1-6"); //merge 3 -> 1, 2, or 3 v = new Vector(); v.add(new ByteRange(1,3)); v.add(new ByteRange(5,19)); v.add(new ByteRange(4,6)); assertMerge(v, "1-19"); v = new Vector(); v.add(new ByteRange(1,3)); v.add(new ByteRange(9,19)); v.add(new ByteRange(4,6)); assertMerge(v, "1-6,9-19"); v = new Vector(); v.add(new ByteRange(1,3)); v.add(new ByteRange(9,19)); v.add(new ByteRange(6,12)); assertMerge(v, "1-3,6-19"); v = new Vector(); v.add(new ByteRange(1,3)); v.add(new ByteRange(9,19)); v.add(new ByteRange(6,12)); assertMerge(v, "1-3,6-19"); v = new Vector(); v.add(new ByteRange(1,3)); v.add(new ByteRange(9,19)); v.add(new ByteRange(0,2)); assertMerge(v, "0-3,9-19"); v = new Vector(); v.add(new ByteRange(1,3)); v.add(new ByteRange(9,19)); v.add(new ByteRange(0,12)); assertMerge(v, "0-19"); //large number first v = new Vector(); v.add(new ByteRange(50,64)); v.add(new ByteRange(9,19)); v.add(new ByteRange(6,12)); assertMerge(v, "6-19,50-64"); v = new Vector(); v.add(new ByteRange(50,64)); v.add(new ByteRange(9,19)); v.add(new ByteRange(6,7)); assertMerge(v, "6-7,9-19,50-64"); //2 identical v = new Vector(); v.add(new ByteRange(6,7)); v.add(new ByteRange(9,19)); v.add(new ByteRange(6,7)); assertMerge(v, "6-7,9-19"); v = new Vector(); v.add(new ByteRange(30,40)); v.add(new ByteRange(6,7)); v.add(new ByteRange(30,40)); v.add(new ByteRange(6,7)); assertMerge(v, "6-7,30-40"); //1 superset v = new Vector(); v.add(new ByteRange(30,40)); v.add(new ByteRange(6,7)); v.add(new ByteRange(35,50)); v.add(new ByteRange(3,100)); assertMerge(v, "3-100"); v = new Vector(); v.add(new ByteRange(3,100)); v.add(new ByteRange(6,7)); v.add(new ByteRange(35,50)); v.add(new ByteRange(30,40)); assertMerge(v, "3-100"); //singletons v = new Vector(); v.add(new ByteRange(3,3)); v.add(new ByteRange(6,7)); v.add(new ByteRange(1,1)); v.add(new ByteRange(8,8)); assertMerge(v, "1-1,3-3,6-8"); v = new Vector(); v.add(new ByteRange(3,3)); v.add(new ByteRange(4,4)); v.add(new ByteRange(1,1)); v.add(new ByteRange(2,2)); assertMerge(v, "1-4"); } /** Create ByteRangeList from vector v, merge with new ByteRange(from, to), assure it renders toFtpCmdArgument() as expectedResult and that original vector and range did not change. Test merge(Vector), merge(ByteRange), toFtpCmdArgument() and **/ private void assertMerge1(Vector v, int from, int to, String expectedResult) { ByteRangeList list = new ByteRangeList(); list.merge(v); ByteRange newRange = new ByteRange(from, to); String vBefore = list.toFtpCmdArgument(); String rBefore = newRange.toString(); logger.info("merging range: " + vBefore + " + " + rBefore); // test merge list.merge(newRange); String actualResult = list.toFtpCmdArgument(); logger.debug(" -> " + actualResult); assertTrue(expectedResult.equals(actualResult)); logger.debug("ok, merged as expected."); // original vector and range did not change? ByteRangeList list2 = new ByteRangeList(); list2.merge(v); String vAfter = list2.toFtpCmdArgument(); String rAfter = newRange.toString(); assertTrue(vBefore.equals(vAfter)); assertTrue(rBefore.equals(rAfter)); logger.debug("ok, original objects intact"); }; /** Merge vector into a new ByteRangeList. Test merge(ByteRange), merge(Vector), toFtpCmdArgument(). **/ private void assertMerge(Vector v, String result) { logger.info("merging vector of ranges: " + result); ByteRangeList list1 = new ByteRangeList(); for (int i=0; i " + list1.toFtpCmdArgument()); assertTrue(list1.toFtpCmdArgument().equals(result)); logger.debug("merging one by one again.."); ByteRangeList list3 = new ByteRangeList(); for (int i=0; i " + list3.toFtpCmdArgument()); assertTrue(list3.toFtpCmdArgument().equals(result)); logger.debug("merging vector at once"); ByteRangeList list2 = new ByteRangeList(); list2.merge(v); logger.debug(" .. -> " + list2.toFtpCmdArgument()); assertTrue(list2.toFtpCmdArgument().equals(result)); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/ByteRangeTest.java000066400000000000000000000076541241116057200313560ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.ByteRange; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test ByteRange **/ public class ByteRangeTest extends TestCase { private static Log logger = LogFactory.getLog(FeatureListTest.class.getName()); public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(ByteRangeTest.class); } public ByteRangeTest(String name) { super(name); } public void test() { //trivial assertMerge(0,0, 0,0, 0,0, ByteRange.THIS_SUPERSET); assertMerge(52,52, 52,52, 52,52, ByteRange.THIS_SUPERSET); assertMerge(12,15, 12,15, 12,15, ByteRange.THIS_SUPERSET); // now testing all cases: adjacent / subset / superset / separate // mnemotechnic notation: // first range = t // second range = o // common subset = - // t o assertMerge(1,4, 7,8, 1,4, ByteRange.THIS_BELOW); // o t assertMerge(7,8, 1,4, 7,8, ByteRange.THIS_ABOVE); // ot assertMerge(5,7, 1,4, 1,7, ByteRange.ADJACENT); // to assertMerge(1,4, 5,7, 1,7, ByteRange.ADJACENT); // o-t assertMerge(3,15, -3,4, -3,15, ByteRange.ADJACENT); // t-o assertMerge(1,2, 2,4, 1,4, ByteRange.ADJACENT); // o- assertMerge(3,15, -3,15, -3,15, ByteRange.THIS_SUBSET); // t- assertMerge(-3,15, 3,15, -3,15, ByteRange.THIS_SUPERSET); // t-t assertMerge(-3,30, 3,15, -3,30, ByteRange.THIS_SUPERSET); // o-o assertMerge(3,15, -3,30, -3,30, ByteRange.THIS_SUBSET); // -t assertMerge(0,2, 0,0, 0,2, ByteRange.THIS_SUPERSET); // -o assertMerge(0,0, 0,2, 0,2, ByteRange.THIS_SUBSET); // - assertMerge(3,15, 3,15, 3,15, ByteRange.THIS_SUPERSET); //more about: separate or adjacent? assertMerge(1,1, 2,2, 1,2, ByteRange.ADJACENT); assertMerge(1,1, 4,4, 1,1, ByteRange.THIS_BELOW); assertMerge(-5,5, 6,9, -5,9, ByteRange.ADJACENT); assertMerge(-5,5, 7,9, -5,5, ByteRange.THIS_BELOW); assertConstructorError(4,3); assertConstructorError(16,2); assertConstructorError(20, -21); } /* test ByteRange(from1,to1).merge(new ByteRange(from2, to2)); the result should (from3, to3) and expectedReturn should be returned. */ private void assertMerge(int from1, int to1, int from2, int to2, int from1after, int to1after, int expectedReturn) { logger.debug("checking: (" + from1 + ".." + to1 +") + (" + from2 + ".." + to2 +") = (" + from1after + ".." + to1after + ")"); ByteRange br1 = new ByteRange(from1, to1); ByteRange br2 = new ByteRange(from2, to2); int ret = br1.merge(br2); logger.debug("... -> (" + br1.from + ".." + br1.to + ")"); assertTrue(ret == expectedReturn); assertTrue(br1.from == from1after); assertTrue(br1.to == to1after); } private void assertConstructorError(int from, int to) { logger.debug("checking constructor: (" + from + "," + to + ")"); boolean threwOk = false; try { new ByteRange(from, to); } catch (IllegalArgumentException e) { threwOk = true; } if (! threwOk ) { fail("constructor did not throw an exception when it should have"); } logger.debug("okay, throws exception as expected."); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/DataChannelReuseTest.java000066400000000000000000000361711241116057200326400ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.GridFTPClient; import org.globus.ftp.RetrieveOptions; import org.globus.ftp.GridFTPSession; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.FileRandomIO; import org.globus.ftp.DataSink; import org.globus.ftp.DataSource; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.RandomAccessFile; import org.ietf.jgss.GSSCredential; public class DataChannelReuseTest extends TestCase { private static Log logger = LogFactory.getLog(DataChannelReuseTest.class.getName()); // for incoming transfers protected String remoteSrcFile1 = TestEnv.serverADir + "/" + TestEnv.serverAFile; protected String remoteSrcFile2 = TestEnv.serverADir + "/" + TestEnv.serverAFile; protected String remoteSrcFile3 = TestEnv.serverADir + "/" + TestEnv.serverAFile; protected String localDestFile1 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; protected String localDestFile2 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; protected String localDestFile3 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; // for outgoing transfers protected String localSrcFile1 = TestEnv.localSrcDir + "/" + TestEnv.localSrcFile; protected String localSrcFile2 = TestEnv.localSrcDir + "/" + TestEnv.localSrcFile; protected String localSrcFile3 = TestEnv.localSrcDir + "/" + TestEnv.localSrcFile; protected String remoteDestFile1 = TestEnv.serverBDir + "/" + TestEnv.localSrcFile; protected String remoteDestFile2 = TestEnv.serverBDir + "/" + "somefile"; protected String remoteDestFile3 = TestEnv.serverBDir + "/" + TestEnv.localSrcFile; public DataChannelReuseTest(String name) { super(name); } public static void main(String[] args) throws Exception { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(DataChannelReuseTest.class); } /* reuse data channels */ public void testBasicGet() throws Exception { logger.info("basic data channel reuse"); GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); setParamsModeE(client, null); /* use default cred */ client.setOptions(new RetrieveOptions(TestEnv.parallelism)); DataSink sink1 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.setLocalPassive(); client.setActive(); client.get(remoteSrcFile1, sink1, null); sink1.close(); DataSink sink2 = new FileRandomIO(new RandomAccessFile(localDestFile2, "rw")); client.get(remoteSrcFile2, sink2, null); sink2.close(); DataSink sink3 = new FileRandomIO(new RandomAccessFile(localDestFile3, "rw")); client.get(remoteSrcFile3, sink3, null); sink3.close(); client.close(); } /* reuse data channels with put operations */ public void testBasicPut() throws Exception { logger.info("basic data channel reuse with put"); GridFTPClient client = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); setParamsModeE(client, null); /* use default cred */ client.setOptions(new RetrieveOptions(TestEnv.parallelism)); client.setDataChannelProtection(GridFTPSession.PROTECTION_CLEAR); client.setPassive(); client.setLocalActive(); // transfer DataSource source1 = new FileRandomIO(new RandomAccessFile(localSrcFile1, "r")); client.put(remoteDestFile1, source1, null); source1.close(); // check that everything got transferred long size = client.getSize(remoteDestFile1); File f = new File(localSrcFile1); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); DataSource source2 = new FileRandomIO(new RandomAccessFile(localSrcFile2, "r")); client.put(remoteDestFile2, source2, null); source2.close(); size = client.getSize(remoteDestFile2); f = new File(localSrcFile2); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); DataSource source3 = new FileRandomIO(new RandomAccessFile(localSrcFile3, "rw")); client.put(remoteDestFile3, source3, null); source3.close(); size = client.getSize(remoteDestFile3); f = new File(localSrcFile3); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.close(); } /* changing d.c. protection */ public void testGetProtection() throws Exception { logger.info("data channel reuse with changing d.c. protection"); GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); setParamsModeE(client, null); client.setOptions(new RetrieveOptions(TestEnv.parallelism)); client.setDataChannelProtection(GridFTPSession.PROTECTION_CLEAR); client.setPassiveMode(false); DataSink sink1 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.setLocalPassive(); client.setActive(); client.get(remoteSrcFile1, sink1, null); sink1.close(); client.setDataChannelProtection(GridFTPSession.PROTECTION_SAFE); client.setPassiveMode(false); DataSink sink2 = new FileRandomIO(new RandomAccessFile(localDestFile2, "rw")); client.get(remoteSrcFile2, sink2, null); sink2.close(); client.setDataChannelProtection(GridFTPSession.PROTECTION_PRIVATE); client.setPassiveMode(false); DataSink sink3 = new FileRandomIO(new RandomAccessFile(localDestFile3, "rw")); client.get(remoteSrcFile3, sink3, null); sink3.close(); client.setDataChannelProtection(GridFTPSession.PROTECTION_CLEAR); client.setPassiveMode(false); // use file1 again DataSink sink4 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.setLocalPassive(); client.setActive(); client.get(remoteSrcFile1, sink4, null); sink4.close(); client.close(); } /* changing d.c. protection. */ public void testPutProtection() throws Exception { logger.info("data channel reuse with put and protection"); GridFTPClient client = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); setParamsModeE(client, null); client.setOptions(new RetrieveOptions(TestEnv.parallelism)); client.setDataChannelProtection(GridFTPSession.PROTECTION_CLEAR); client.setPassiveMode(true); // transfer DataSource source1 = new FileRandomIO(new RandomAccessFile(localSrcFile1, "r")); client.put(remoteDestFile1, source1, null); source1.close(); // check that everything got transferred long size = client.getSize(remoteDestFile1); File f = new File(localSrcFile1); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.setDataChannelProtection(GridFTPSession.PROTECTION_PRIVATE); client.setPassiveMode(true); DataSource source2 = new FileRandomIO(new RandomAccessFile(localSrcFile2, "r")); client.put(remoteDestFile2, source2, null); source2.close(); size = client.getSize(remoteDestFile2); f = new File(localSrcFile2); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.setDataChannelProtection(GridFTPSession.PROTECTION_CLEAR); client.setPassiveMode(true); DataSource source3 = new FileRandomIO(new RandomAccessFile(localSrcFile3, "rw")); client.put(remoteDestFile3, source3, null); source3.close(); size = client.getSize(remoteDestFile3); f = new File(localSrcFile3); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.close(); } /* reuse data channels with changing TCP buffer size */ public void testGetTCPBuffer() throws Exception { logger.info("data channel reuse with changing TCP buffer size"); GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); setParamsModeE(client, null); /* use default cred */ client.setOptions(new RetrieveOptions(TestEnv.parallelism)); client.setLocalPassive(); client.setActive(); client.setLocalTCPBufferSize(16000); DataSink sink1 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.get(remoteSrcFile1, sink1, null); sink1.close(); client.setLocalTCPBufferSize(1234567); DataSink sink2 = new FileRandomIO(new RandomAccessFile(localDestFile2, "rw")); client.get(remoteSrcFile1, sink2, null); sink2.close(); client.setLocalTCPBufferSize(80003); DataSink sink3 = new FileRandomIO(new RandomAccessFile(localDestFile3, "rw")); client.get(remoteSrcFile1, sink3, null); sink3.close(); client.setLocalTCPBufferSize(55500); // using file1 again DataSink sink4 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.get(remoteSrcFile1, sink4, null); sink4.close(); client.close(); } /* reuse data channels with put operations and changing TCP buffer */ public void testPutTCPBuffer() throws Exception { logger.info("data channel reuse with put and changing tcp buffer"); GridFTPClient client = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); setParamsModeE(client, null); /* use default cred */ client.setOptions(new RetrieveOptions(TestEnv.parallelism)); client.setDataChannelProtection(GridFTPSession.PROTECTION_CLEAR); client.setPassive(); client.setLocalActive(); client.setLocalTCPBufferSize(16000); // transfer DataSource source1 = new FileRandomIO(new RandomAccessFile(localSrcFile1, "r")); client.put(remoteDestFile1, source1, null); source1.close(); // check that everything got transferred long size = client.getSize(remoteDestFile1); File f = new File(localSrcFile1); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.setLocalTCPBufferSize(1234567); DataSource source2 = new FileRandomIO(new RandomAccessFile(localSrcFile2, "r")); client.put(remoteDestFile2, source2, null); source2.close(); size = client.getSize(remoteDestFile2); f = new File(localSrcFile2); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.setLocalTCPBufferSize(55500); DataSource source3 = new FileRandomIO(new RandomAccessFile(localSrcFile3, "rw")); client.put(remoteDestFile3, source3, null); source3.close(); size = client.getSize(remoteDestFile3); f = new File(localSrcFile3); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.close(); } /* reuse data channels, interspersed by setActive and setPassive calls (which tear all reused connections) */ public void testGetTearing() throws Exception { logger.info("data channel reuse interspersed by setActive/passive"); GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); setParamsModeE(client, null); /* use default cred */ client.setOptions(new RetrieveOptions(TestEnv.parallelism)); client.setLocalPassive(); client.setActive(); DataSink sink1 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.get(remoteSrcFile1, sink1, null); sink1.close(); DataSink sink2 = new FileRandomIO(new RandomAccessFile(localDestFile2, "rw")); client.get(remoteSrcFile2, sink2, null); sink2.close(); // tear data connections client.setLocalPassive(); client.setActive(); DataSink sink3 = new FileRandomIO(new RandomAccessFile(localDestFile3, "rw")); client.get(remoteSrcFile3, sink3, null); sink3.close(); // reusing file1 again DataSink sink4 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.get(remoteSrcFile1, sink4, null); sink4.close(); client.close(); } /* reuse data channels with put operations, interspersed by setActive and setPassive calls (which tear all connections) */ public void testPutTearing() throws Exception { logger.info("data channel reuse with put and interspersed setActive/passive"); GridFTPClient client = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); setParamsModeE(client, null); /* use default cred */ client.setOptions(new RetrieveOptions(TestEnv.parallelism)); client.setDataChannelProtection(GridFTPSession.PROTECTION_CLEAR); client.setPassive(); client.setLocalActive(); // transfer DataSource source1 = new FileRandomIO(new RandomAccessFile(localSrcFile1, "r")); client.put(remoteDestFile1, source1, null); source1.close(); // check that everything got transferred long size = client.getSize(remoteDestFile1); File f = new File(localSrcFile1); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); DataSource source2 = new FileRandomIO(new RandomAccessFile(localSrcFile2, "r")); client.put(remoteDestFile2, source2, null); source2.close(); size = client.getSize(remoteDestFile2); f = new File(localSrcFile2); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); // tear data connections client.setPassive(); client.setLocalActive(); DataSource source3 = new FileRandomIO(new RandomAccessFile(localSrcFile3, "rw")); client.put(remoteDestFile3, source3, null); source3.close(); size = client.getSize(remoteDestFile3); f = new File(localSrcFile3); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); // transfer file1 again DataSource source4 = new FileRandomIO(new RandomAccessFile(localSrcFile1, "r")); client.put(remoteDestFile1, source4, null); source4.close(); // check that everything got transferred size = client.getSize(remoteDestFile1); f = new File(localSrcFile1); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.close(); } private void setParamsModeE(GridFTPClient client, GSSCredential cred) throws Exception { client.authenticate(cred); client.setProtectionBufferSize(16384); client.setType(GridFTPSession.TYPE_IMAGE); client.setMode(GridFTPSession.MODE_EBLOCK); client.setDataChannelAuthentication(DataChannelAuthentication.SELF); client.setDataChannelProtection(GridFTPSession.PROTECTION_SAFE); } } DataChannelReuseVaryingParTest.java000066400000000000000000000147471241116057200345710ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.GridFTPClient; import org.globus.ftp.RetrieveOptions; import org.globus.ftp.GridFTPSession; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.FileRandomIO; import org.globus.ftp.DataSink; import org.globus.ftp.DataSource; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.RandomAccessFile; import org.ietf.jgss.GSSCredential; /** Test data channel reuse with varying parallelism*/ public class DataChannelReuseVaryingParTest extends TestCase { private static Log logger = LogFactory.getLog(DataChannelReuseVaryingParTest.class.getName()); // for incoming transfers protected String remoteSrcFile1 = TestEnv.serverADir + "/" + TestEnv.serverAFile; protected String remoteSrcFile2 = TestEnv.serverADir + "/" + TestEnv.serverAFile; protected String remoteSrcFile3 = TestEnv.serverADir + "/" + TestEnv.serverAFile; protected String localDestFile1 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; protected String localDestFile2 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; protected String localDestFile3 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; // for outgoing transfers protected String localSrcFile1 = TestEnv.localSrcDir + "/" + TestEnv.localSrcFile; protected String localSrcFile2 = TestEnv.localSrcDir + "/" + TestEnv.localSrcFile; protected String localSrcFile3 = TestEnv.localSrcDir + "/" + TestEnv.localSrcFile; protected String remoteDestFile1 = TestEnv.serverBDir + "/" + TestEnv.localSrcFile; protected String remoteDestFile2 = TestEnv.serverBDir + "/" + "somefile"; protected String remoteDestFile3 = TestEnv.serverBDir + "/" + TestEnv.localSrcFile; public DataChannelReuseVaryingParTest(String name) { super(name); } public static void main(String[] args) throws Exception { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(DataChannelReuseVaryingParTest.class); } /* * Incoming connection, with changing parallelism */ public void testGetVarPar() throws Exception { logger.info("data channel reuse with get and changing parallelism"); GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); setParamsModeE(client, null); client.setOptions(new RetrieveOptions(4)); client.setPassiveMode(false); DataSink sink1 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.get(remoteSrcFile1, sink1, null); sink1.close(); client.setOptions(new RetrieveOptions(2)); client.setPassiveMode(false); DataSink sink2 = new FileRandomIO(new RandomAccessFile(localDestFile2, "rw")); client.get(remoteSrcFile1, sink2, null); sink2.close(); client.setOptions(new RetrieveOptions(7)); client.setPassiveMode(false); DataSink sink3 = new FileRandomIO(new RandomAccessFile(localDestFile3, "rw")); client.get(remoteSrcFile1, sink3, null); sink3.close(); client.setOptions(new RetrieveOptions(1)); client.setPassiveMode(false); // using file1 again DataSink sink4 = new FileRandomIO(new RandomAccessFile(localDestFile1, "rw")); client.get(remoteSrcFile1, sink4, null); sink4.close(); client.close(); } /* * Outgoing connection and changing parallelism */ public void testPutVarPar() throws Exception { logger.info("data channel reuse with put and changing parallelism"); GridFTPClient client = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); setParamsModeE(client, null); client.setOptions(new RetrieveOptions(4)); client.setPassiveMode(true); // transfer DataSource source1 = new FileRandomIO(new RandomAccessFile(localSrcFile1, "r")); client.put(remoteDestFile1, source1, null); source1.close(); // check that everything got transferred long size = client.getSize(remoteDestFile1); File f = new File(localSrcFile1); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.setOptions(new RetrieveOptions(2)); client.setPassiveMode(true); DataSource source2 = new FileRandomIO(new RandomAccessFile(localSrcFile2, "r")); client.put(remoteDestFile2, source2, null); source2.close(); size = client.getSize(remoteDestFile2); f = new File(localSrcFile2); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.setOptions(new RetrieveOptions(7)); client.setPassiveMode(true); DataSource source3 = new FileRandomIO(new RandomAccessFile(localSrcFile3, "rw")); client.put(remoteDestFile3, source3, null); source3.close(); size = client.getSize(remoteDestFile3); f = new File(localSrcFile3); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.setOptions(new RetrieveOptions(1)); client.setPassiveMode(true); // transfer file1 again DataSource source4 = new FileRandomIO(new RandomAccessFile(localSrcFile1, "r")); client.put(remoteDestFile1, source4, null); source4.close(); // check that everything got transferred size = client.getSize(remoteDestFile1); f = new File(localSrcFile1); logger.debug("comparing size: " + size + " <-> " + f.length() ); assertEquals(f.length(), size); client.close(); } private void setParamsModeE(GridFTPClient client, GSSCredential cred) throws Exception { client.authenticate(cred); client.setProtectionBufferSize(16384); client.setType(GridFTPSession.TYPE_IMAGE); client.setMode(GridFTPSession.MODE_EBLOCK); client.setDataChannelAuthentication(DataChannelAuthentication.SELF); client.setDataChannelProtection(GridFTPSession.PROTECTION_SAFE); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/FTPClient2PartyTest.java000066400000000000000000000265061241116057200323650ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.Session; import org.globus.ftp.FTPClient; import org.globus.ftp.DataSource; import org.globus.ftp.DataSink; import org.globus.ftp.DataSinkStream; import org.globus.ftp.DataSourceStream; import org.globus.ftp.exception.ServerException; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.io.FileOutputStream; import java.io.FileInputStream; /** Test FTPClient.get() and put() **/ public class FTPClient2PartyTest extends TestCase { private static Log logger = LogFactory.getLog(FTPClient2PartyTest.class.getName()); protected FTPClient src = null; // note that this can be always null, because // user is not obliged to provide FTP destination server protected FTPClient dest = null; public FTPClient2PartyTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(FTPClient2PartyTest.class); } private boolean skipTest(String property, String msg) { if (property == null) { if (TestEnv.failUnset) { fail(msg); } logger.info("Test skipped: " + msg); return true; } else { return false; } } public void testGet() throws Exception { logger.info("get"); testGet(TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir, TestEnv.serverFFile, TestEnv.localDestDir); } public void testPut() throws Exception { logger.info("put"); if (skipTest(TestEnv.serverGHost, "serverGHost undefined")) { return; } testPut(TestEnv.serverGHost, TestEnv.serverGPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGDir, TestEnv.localSrcDir, TestEnv.localSrcFile); } /** Try transferring file to and from bad port on existing server. IOException should be thrown. **/ public void testGetNoSuchPort() throws Exception{ if (TestEnv.serverANoSuchPort == TestEnv.UNDEFINED) { logger.info("Omitting the test: test3Party_noSuchPort"); logger.info("because some necessary properties are not defined."); return; } logger.info("get from non existent port"); boolean caughtOK = false; try { testGet(TestEnv.serverFHost, TestEnv.serverFNoSuchPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir, TestEnv.serverFFile, TestEnv.localDestDir); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } logger.info("put to non existent port"); caughtOK = false; try { testPut(TestEnv.serverAHost, TestEnv.serverANoSuchPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGDir, TestEnv.localSrcDir, TestEnv.localSrcFile); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } } /** Try transferring file to and from non existent server. IOException should be thrown. **/ public void testGetNoSuchServer() throws Exception{ logger.info("get from non existent server"); boolean caughtOK = false; try { testGet(TestEnv.noSuchServer, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir, TestEnv.serverFFile, TestEnv.localDestDir); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } logger.info("put to non existent server"); caughtOK = false; try { testPut(TestEnv.noSuchServer, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir, TestEnv.serverFFile, TestEnv.localDestDir); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } } /** try transferring non existent file; ServerException should be thrown **/ public void testGetNoSuchSrcFile() throws Exception{ logger.info("get with bad src file"); try { testGet(TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir, TestEnv.serverFNoSuchFile, TestEnv.localDestDir); } catch (ServerException e) { logger.debug("Test passed: ServerException properly thrown.", e); } } /** try transferring file to non existent directory; ServerException should be thrown. **/ public void testPutNoSuchDestDir() throws Exception{ logger.info("put with bad dest dir"); if (skipTest(TestEnv.serverGHost, "serverGHost undefined")) { return; } try { testPut(TestEnv.serverGHost, TestEnv.serverGPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGNoSuchDir, TestEnv.localSrcDir, TestEnv.localSrcFile); } catch (ServerException e) { logger.debug("Test passed: ServerException properly thrown.", e); } } private void testGet(String host, int port, String user, String password, String remoteDir, String remoteFile, String localDir) throws Exception{ logger.info("active, image, stream"); testGet(host, port, user, password, remoteDir + "/" + remoteFile, localDir, Session.SERVER_ACTIVE, Session.TYPE_IMAGE, Session.MODE_STREAM); logger.info("active, ascii, stream"); testGet(host, port, user, password, remoteDir + "/" + remoteFile, localDir, Session.SERVER_ACTIVE, Session.TYPE_ASCII, Session.MODE_STREAM); logger.info("pasive, image, stream"); testGet(host, port, user, password, remoteDir + "/" + remoteFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_IMAGE, Session.MODE_STREAM); logger.info("pasive, ascii, stream"); testGet(host, port, user, password, remoteDir + "/" + remoteFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_ASCII, Session.MODE_STREAM); } private void testGet(String host, int port, String user, String password, String fullRemoteFile, String localDestDir, int localServerMode, int transferType, int transferMode) throws Exception { String smode = (localServerMode == Session.SERVER_PASSIVE)? "pasv" : "actv"; String tmode = (transferMode == Session.MODE_STREAM) ? "stream" : "eblok"; String ttype = (transferType == Session.TYPE_ASCII) ? "ascii" : "image"; String fullLocalFile = localDestDir + "/test.get." + smode + "." + tmode +"." + ttype +"." + System.currentTimeMillis(); logger.debug("will write to: " + fullLocalFile); FTPClient client = new FTPClient(host, port); testGet_setParams(client, user, password, localServerMode, transferType, transferMode); DataSink sink = new DataSinkStream(new FileOutputStream(fullLocalFile)); client.get(fullRemoteFile, sink, null); client.close(); } protected void testGet_setParams(FTPClient client, String user, String password, int localServerMode, int transferType, int transferMode) throws Exception{ //System.out.println("USER = "+ user + "PAssword="+ password); client.authorize(user, password); // secure server: client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); if (localServerMode == Session.SERVER_ACTIVE) { client.setPassive(); client.setLocalActive(); } else { client.setLocalPassive(); client.setActive(); } } private void testPut(String host, int port, String user, String password, String remoteDir, String localDir, String localFile) throws Exception{ logger.info("active, image, stream"); testPut(host, port, user, password, remoteDir, localFile, localDir, Session.SERVER_ACTIVE, Session.TYPE_IMAGE, Session.MODE_STREAM); logger.info("active, ascii, stream"); testPut(host, port, user, password, remoteDir, localFile, localDir, Session.SERVER_ACTIVE, Session.TYPE_ASCII, Session.MODE_STREAM); logger.info("pasive, image, stream"); testPut(host, port, user, password, remoteDir, localFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_IMAGE, Session.MODE_STREAM); logger.info("pasive, ascii, stream"); testPut(host, port, user, password, remoteDir, localFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_ASCII, Session.MODE_STREAM); } private void testPut(String host, int port, String user, String password, String remoteDestDir, String localFile, String localDir, int localServerMode, int transferType, int transferMode) throws Exception { FTPClient client = new FTPClient(host, port); testPut_setParams(client, user, password, localServerMode, transferType, transferMode); String fullLocalFile = localDir + "/" + localFile; String fullRemoteFile = remoteDestDir + "/" + localFile; DataSource source = new DataSourceStream(new FileInputStream(fullLocalFile)); client.put(fullRemoteFile, source, null); client.close(); } protected void testPut_setParams(FTPClient client, String user, String password, int localServerMode, int transferType, int transferMode) throws Exception{ client.authorize(user, password); // secure server: client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); if (localServerMode == Session.SERVER_ACTIVE) { client.setPassive(); client.setLocalActive(); } else { client.setLocalPassive(); client.setActive(); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/FTPClientListTest.java000066400000000000000000000072141241116057200321120ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.Session; import org.globus.ftp.FTPClient; import org.globus.ftp.DataSink; import org.globus.ftp.HostPort; import org.globus.ftp.Buffer; import org.globus.ftp.FileInfo; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.util.Vector; import java.io.ByteArrayOutputStream; public class FTPClientListTest extends TestCase { private static Log logger = LogFactory.getLog(FTPClientListTest.class.getName()); public FTPClientListTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(FTPClientListTest.class); } public void testListPassive() throws Exception { testList(true); } public void testListActive() throws Exception { testList(false); } private void testList(boolean passive) throws Exception { FTPClient src = new FTPClient(TestEnv.serverFHost, TestEnv.serverFPort); src.authorize(TestEnv.serverFUser, TestEnv.serverFPassword); src.setType(Session.TYPE_ASCII); src.changeDir(TestEnv.serverFDir); src.setPassiveMode(passive); boolean foundit = false; Vector v = src.list(); logger.debug("list received"); while (! v.isEmpty()) { FileInfo f = (FileInfo)v.remove(0); logger.info(f.toString()); if (f.getName().equals(TestEnv.serverFFile)) { foundit = true; } } src.close(); assertTrue("expected file not in the list", foundit); } public void test2() throws Exception { logger.info("test two consective list, using both list functions"); FTPClient src = new FTPClient(TestEnv.serverFHost, TestEnv.serverFPort); src.authorize(TestEnv.serverFUser, TestEnv.serverFPassword); String output1 = null; String output2 = null; // using list() src.changeDir(TestEnv.serverFDir); Vector v = src.list(); logger.debug("list received"); StringBuffer output1Buffer = new StringBuffer(); while (! v.isEmpty()) { FileInfo f = (FileInfo)v.remove(0); output1Buffer.append(f.toString()).append("\n"); } output1 = output1Buffer.toString(); // using list(String,String, DataSink) HostPort hp2 = src.setPassive(); src.setLocalActive(); final ByteArrayOutputStream received2= new ByteArrayOutputStream(1000); // unnamed DataSink subclass will write data channel content // to "received" stream. src.list("*", "-d", new DataSink(){ public void write(Buffer buffer) throws IOException{ logger.debug("received " + buffer.getLength() + " bytes of directory listing"); received2.write(buffer.getBuffer(), 0, buffer.getLength()); } public void close() throws IOException{}; }); // transfer done. Data is in received2 stream. output2 = received2.toString(); logger.debug(output2); src.close(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/FTPClientTest.java000066400000000000000000000270661241116057200312650ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.Session; import org.globus.ftp.FTPClient; import org.globus.ftp.StreamModeRestartMarker; import org.globus.ftp.HostPort; import org.globus.ftp.exception.ServerException; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Date; import java.io.IOException; public class FTPClientTest extends TestCase { private static Log logger = LogFactory.getLog(FTPClientTest.class.getName()); public FTPClientTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(FTPClientTest.class); } private boolean skipTest(String property, String msg) { if (property == null) { if (TestEnv.failUnset) { fail(msg); } logger.info("Test skipped: " + msg); return true; } else { return false; } } public void testSize() throws Exception { logger.info("getSize()"); FTPClient src = new FTPClient(TestEnv.serverFHost, TestEnv.serverFPort); src.authorize(TestEnv.serverFUser, TestEnv.serverFPassword); src.changeDir(TestEnv.serverFDir); assertEquals(true, src.exists(TestEnv.serverFFile)); src.setType(Session.TYPE_IMAGE); long size = -1; size = src.getSize(TestEnv.serverFFile); assertEquals(TestEnv.serverFFileSize, size); size = src.size(TestEnv.serverFFile); assertEquals(TestEnv.serverFFileSize, size); Date d1 = src.getLastModified(TestEnv.serverFFile); Date d2 = src.lastModified(TestEnv.serverFFile); assertEquals(d1.getTime(), d2.getTime()); // TODO: need to verify the date agaist something.. src.close(); } public void testDir() throws Exception { logger.info("makeDir()"); if (skipTest(TestEnv.serverGHost, "serverGHost undefined")) { return; } FTPClient dest = new FTPClient(TestEnv.serverGHost, TestEnv.serverGPort); dest.authorize(TestEnv.serverGUser, TestEnv.serverGPassword); String tmpDir = "abcdef"; String baseDir = dest.getCurrentDir(); dest.makeDir(tmpDir); dest.changeDir(tmpDir); assertEquals(baseDir + "/" + tmpDir, dest.getCurrentDir()); dest.goUpDir(); assertEquals(baseDir, dest.getCurrentDir()); dest.deleteDir(tmpDir); try { dest.changeDir(tmpDir); fail("directory should have been removed"); } catch (Exception e) { } dest.close(); } /* do not run: the server might not support FEAT public void testFeature() throws Exception { logger.info("getFeatureList()"); FeatureList fl = src.getFeatureList(); assertEquals(true, fl.contains("DcaU")); assertEquals(false, fl.contains("MIS")); } */ public void testModes() throws Exception { logger.info("setActive()/setPassive()"); FTPClient src = new FTPClient(TestEnv.serverFHost, TestEnv.serverFPort); src.authorize(TestEnv.serverFUser, TestEnv.serverFPassword); HostPort hp = null; hp = new HostPort("140.221.11.99", 8888); src.setActive(hp); hp = src.setPassive(); logger.debug(hp.getHost() + " " + hp.getPort()); src.close(); } /* do not run: the server might not support OPTS public void testOptions() throws Exception { logger.info("retrieveOptions()"); Options opts = new RetrieveOptions(1, 2, 3); src.setOptions(opts); } */ public void testRestartMarker() throws Exception { logger.info("setRestartMarker()"); FTPClient src = new FTPClient(TestEnv.serverFHost, TestEnv.serverFPort); src.authorize(TestEnv.serverFUser, TestEnv.serverFPassword); StreamModeRestartMarker rm = new StreamModeRestartMarker(12345); src.setRestartMarker(rm); src.close(); } /** try third party transfer. no exception should be thrown. **/ public void test3Party() throws Exception { logger.info("3 party"); if (skipTest(TestEnv.serverGHost, "serverGHost undefined")) { return; } test3Party( TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir + "/" + TestEnv.serverFFile, TestEnv.serverGHost, TestEnv.serverGPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGDir + "/" + TestEnv.serverGFile ); } /** Try transferring file to and from bad port on existing server. IOException should be thrown. **/ public void test3Party_noSuchPort() throws Exception{ logger.info("3 party with bad port"); if (TestEnv.serverANoSuchPort == TestEnv.UNDEFINED) { logger.info("Omitting the test: test3Party_noSuchPort"); logger.info("because some necessary properties are not defined."); return; } logger.debug("transfer FROM non existent port"); boolean caughtOK = false; try { test3Party( TestEnv.serverAHost, TestEnv.serverANoSuchPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir + "/" + TestEnv.serverFFile, TestEnv.serverGHost, TestEnv.serverGPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGDir + "/" + TestEnv.serverGFile ); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } logger.debug("transfer TO non existent port"); caughtOK = false; try { test3Party( TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir + "/" + TestEnv.serverFFile, TestEnv.serverAHost, TestEnv.serverANoSuchPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGDir + "/" + TestEnv.serverGFile ); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } } /** Try transferring file to and from non existent server. IOException should be thrown. **/ public void test3Party_noSuchServer1() throws Exception { logger.info("3 party with bad server"); logger.debug("transfer FROM non existent server"); try { test3Party( TestEnv.noSuchServer, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir + "/" + TestEnv.serverFFile, TestEnv.serverGHost, TestEnv.serverGPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGDir + "/" + TestEnv.serverGFile ); } catch (IOException e) { logger.debug("Test passed: IOException properly thrown.", e); } } /** Try transferring file to and from non existent server. IOException should be thrown. **/ public void test3Party_noSuchServer2() throws Exception { logger.info("3 party with bad server"); logger.debug("transfer TO non existent server"); try { test3Party( TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir + "/" + TestEnv.serverFFile, TestEnv.noSuchServer, 21, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGDir + "/" + TestEnv.serverGFile ); } catch (IOException e) { logger.debug("Test passed: IOException properly thrown.", e); } } /** try transferring non existent file; ServerException should be thrown **/ public void test3Party_noSuchSrcFile() throws Exception { logger.info("3 party with bad src file"); if (skipTest(TestEnv.serverGHost, "serverGHost undefined")) { return; } try { test3Party( TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir + "/" + TestEnv.serverFNoSuchFile, TestEnv.serverGHost, TestEnv.serverGPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGDir + "/" + TestEnv.serverGFile ); } catch (ServerException e) { logger.debug("Test passed: ServerException properly thrown.", e); } } /** try transferring file to non existent directory; ServerException should be thrown. **/ public void test3Party_noSuchDestDir() throws Exception { logger.info("3 party with bad dest dir"); if (skipTest(TestEnv.serverGHost, "serverGHost undefined")) { return; } try { test3Party( TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword, TestEnv.serverFDir + "/" + TestEnv.serverFFile, TestEnv.serverGHost, TestEnv.serverGPort, TestEnv.serverGUser, TestEnv.serverGPassword, TestEnv.serverGNoSuchDir + "/" + TestEnv.serverGFile ); } catch (ServerException e) { logger.debug("Test passed: ServerException properly thrown.", e); } } /** This method implements the actual transfer. **/ private void test3Party(String host1, int port1, String user1, String password1, String sourceFile, String host2, int port2, String user2, String password2, String destFile) throws Exception { FTPClient client1 = new FTPClient(host1, port1); FTPClient client2 = new FTPClient(host2, port2); test3Party_setParams(client1, user1, password1); test3Party_setParams(client2, user2, password2); client1.transfer(sourceFile, client2, destFile, false, null); client1.close(); client2.close(); } private void test3Party_setParams(FTPClient client, String user, String password) throws Exception{ client.authorize(user, password); // secure server: client.setProtectionBufferSize(16384); client.setType(Session.TYPE_IMAGE); client.setMode(Session.MODE_STREAM); } public void testPortCreationRace() throws Exception { String host = "localhost"; int port = 5555; for(int i = 0; i < 1000; i++) { FTPClient client = null; client = new FTPClient(TestEnv.serverFHost, TestEnv.serverFPort); client.authorize(TestEnv.serverFUser, TestEnv.serverFPassword); client.setType(Session.TYPE_IMAGE); client.setPassive(); client.setLocalActive(); client.close(); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/FTPControlChannelTest.java000066400000000000000000000121361241116057200327500ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.vanilla.Command; import org.globus.ftp.vanilla.Reply; import org.globus.ftp.vanilla.FTPControlChannel; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test FTPControlChannel **/ public class FTPControlChannelTest extends TestCase{ private static Log logger = LogFactory.getLog(FTPControlChannelTest.class.getName()); public FTPControlChannelTest(String name) { super(name); logger.debug(TestEnv.show()); } public static void main (String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(FTPControlChannelTest.class); } public void testAuth() throws Exception{ logger.info("USER/PASS"); try { testAuth(TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFUser, TestEnv.serverFPassword); //"ftp.globus.org", 21, "anonymous", "globus@globus.org" } catch (Exception e) { logger.error("", e); fail(e.toString()); } } /** Because data channel is not present, the server should answer here "425 Can't build data connection: Connection refused." **/ public void testRetr() throws Exception{ logger.info("RETR"); try { testRetr(TestEnv.serverFHost, TestEnv.serverFPort, TestEnv.serverFDir, "/", TestEnv.serverFFile, TestEnv.serverFUser, TestEnv.serverFPassword); //testRetr("ftp.globus.org", 21, "anonymous", "globus@globus.org"); } catch (Exception e) { logger.error("", e); fail(e.toString()); } } private void testAuth(String host, int port, String user, String password) throws Exception { FTPControlChannel pi = new FTPControlChannel(host, port); try { pi.open(); } catch (Exception e) { fail("Could not connect to server at " + host + ":" + port); } pi.write(new Command("USER", user)); Reply reply = pi.read(); if (Reply.isPositiveIntermediate(reply)) { pi.write(new Command("PASS", password)); reply = pi.read(); } pi.close(); if (! Reply.isPositiveCompletion(reply)) { fail("in attempt to log in, received unexpected reply from server: " + reply); } } //testAuth private void testRetr(String host, int port, String dir, String separator, String file, String user, String password) throws Exception { FTPControlChannel pi = new FTPControlChannel(host, port); try { pi.open(); } catch (Exception e) { fail("Could not connect to server at " + host + ":" + port); } pi.write(new Command("USER", user)); Reply reply = pi.read(); if (Reply.isPositiveIntermediate(reply)) { pi.write(new Command("PASS", password)); reply = pi.read(); } if (! Reply.isPositiveCompletion(reply)) { fail("in attempt to log in, received unexpected reply from server: " + reply); } pi.write(new Command("RETR", dir + separator +file)); logger.debug("received: " + pi.read().toString()); // this can still fail is connection gets closed. /* logger.debug("tester: start reading reply..."); int b; java.io.InputStream is = pi.getInputStream(); while ( (b = is.read()) != '\n' ) { System.out.println("next byte ->" + (char)b +"<- code [" + b + "]"); }; */ pi.close(); } //testRetr // not possible to test it: // list needs data channel private void testList(String host, int port, String user, String password) throws Exception { FTPControlChannel pi = new FTPControlChannel(host, port); try { pi.open(); } catch (Exception e) { fail("Could not connect to server at " + host + ":" + port); } pi.write(new Command("USER", user)); Reply reply = pi.read(); if (Reply.isPositiveIntermediate(reply)) { pi.write(new Command("PASS", password)); reply = pi.read(); } if (! Reply.isPositiveCompletion(reply)) { fail("in attempt to log in, received unexpected reply from server: " + reply); } pi.write(new Command("LIST")); logger.debug("tester received: " + pi.read()); pi.write(new Command("PWD")); logger.debug("tester received: " + pi.read()); pi.write(new Command("SYST")); logger.debug("tester received: " + pi.read()); pi.close(); } //testList } //FTPControlChannelTest JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/FTPExceptionTest.java000066400000000000000000000043431241116057200317760ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.exception.FTPException; import org.globus.ftp.exception.FTPReplyParseException; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test FTPException **/ public class FTPExceptionTest extends TestCase{ private static Log logger = LogFactory.getLog(FTPExceptionTest.class.getName()); public FTPExceptionTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite ( ) { return new TestSuite(FTPExceptionTest.class); } /** This is only testing if no errors are thrown during standard operations on exceptions. **/ public void testFTPException() { java.io.IOException ioe = new java.io.IOException("Some weird i/o thing."); FTPException e1 = new FTPException(4); e1.setCode(0); e1.getRootCause(); e1.setRootCause(ioe); e1.toString(); e1.getMessage(); FTPException e2 = new FTPException(0, "This is additional message."); e2.setCode(0); e2.getRootCause(); e2.setRootCause(ioe); e2.toString(); e2.getMessage(); FTPException e3 = new FTPReplyParseException(1, "This is additional message."); //e3.setCode(0); e3.getRootCause(); e3.setRootCause(ioe); e3.toString(); e3.getMessage(); /*System.out.println("---to string---"); System.out.println(e.toString()); System.out.println("--- message ---"); System.out.println(e.getMessage()); System.out.println("--- stack trace ---"); e.printStackTrace(); */ } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/FeatureListTest.java000066400000000000000000000060031241116057200317100ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.FeatureList; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test FeatureList **/ public class FeatureListTest extends TestCase{ private static Log logger = LogFactory.getLog(FeatureListTest.class.getName()); public FeatureListTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite ( ) { return new TestSuite(FeatureListTest.class); } private static String nl = System.getProperty("line.separator"); private static String featMsg= "Extensions supported:" + nl + " REST STREAM" + nl + " ESTO" + nl + " ERET" + nl + " MDTM" + nl + " SIZE" + nl + " PARALLEL" + nl + " DCAU" + nl + "211 END"; //should contain private static final int Y = 1; //should not contain private static final int N = 2; //should throw error private static final int E = 3; public void testContains() { logger.info("testing parsed feature set:"); FeatureList fl = new FeatureList(featMsg); testContains(fl, "REST STREAM", Y); testContains(fl, FeatureList.ESTO, Y); testContains(fl, FeatureList.DCAU, Y); testContains(fl, FeatureList.PARALLEL, Y); testContains(fl, FeatureList.PARALLEL, Y); testContains(fl, FeatureList.SIZE, Y); testContains(fl, FeatureList.MDTM, Y); testContains(fl, FeatureList.ERET, Y); //reply's 1st and last line testContains(fl, "Extensions supported:", N); testContains(fl, "211 END", N); //bad testContains(fl, null, E); testContains(fl, "", N); testContains(fl, "TVFS", N); } private void testContains( FeatureList fl, String feature, int expectedResult) { switch (expectedResult) { case Y: assertTrue(fl.contains(feature)); logger.info("okay, contains " + feature); break; case N: assertTrue( ! fl.contains(feature)); logger.info("okay, does not contain " + feature); break; case E: boolean threwOk = false; try { fl.contains(feature); } catch (IllegalArgumentException e) { threwOk = true; } if (! threwOk ) { fail("FeatureList.contains() did not throw an exception when it should have"); } logger.info("okay, throws exception as expected."); break; } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/FileInfoTest.java000066400000000000000000000172131241116057200311610ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.FileInfo; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class FileInfoTest extends TestCase { private static Log logger = LogFactory.getLog(ReplyTest.class.getName()); public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(FileInfoTest.class); } public FileInfoTest(String name) { super(name); } public void testRegular() throws Exception { FileInfo f1 = new FileInfo("drwxr-xr-x 2 guest other 1536 Jan 31 15:15 run.bat"); assertEquals(" run.bat", f1.getName()); assertEquals(true, f1.isDirectory()); assertEquals(1536, f1.getSize()); assertEquals("Jan 31", f1.getDate()); assertEquals("15:15", f1.getTime()); } public void testNoGroup() throws Exception { FileInfo f2 = new FileInfo("-rw-rw-r-- 1 globus 117579 Nov 29 13:24 AdGriP.pdf"); assertEquals("AdGriP.pdf", f2.getName()); assertEquals(false, f2.isDirectory()); assertEquals(117579, f2.getSize()); assertEquals("Nov 29", f2.getDate()); assertEquals("13:24", f2.getTime()); } public void testSpace() throws Exception { FileInfo f3 = new FileInfo("drwxrwxr-x 2 gawor globus 512 Dec 26 2001 gatekeeper file 2"); assertEquals("gatekeeper file 2", f3.getName()); assertEquals(true, f3.isDirectory()); assertEquals(512, f3.getSize()); assertEquals("Dec 26", f3.getDate()); assertEquals("2001", f3.getTime()); } public void testFileWithDate() throws Exception { FileInfo f4 = new FileInfo("drwxrwxr-x 2 gawor globus 512 Dec 26 2001 gatekeeper-2001"); assertEquals("gatekeeper-2001", f4.getName()); assertEquals(true, f4.isDirectory()); assertEquals(512, f4.getSize()); assertEquals("Dec 26", f4.getDate()); assertEquals("2001", f4.getTime()); } public void testFileWithDateWithSpace() throws Exception { FileInfo f4 = new FileInfo("drwxrwxr-x 2 gawor globus 512 Dec 26 2001 gatekeeper-2001 a b c "); assertEquals("gatekeeper-2001 a b c ", f4.getName()); assertEquals(true, f4.isDirectory()); assertEquals(512, f4.getSize()); assertEquals("Dec 26", f4.getDate()); assertEquals("2001", f4.getTime()); } public void testRegular2() throws Exception { FileInfo f4 = new FileInfo("drwxrwxr-x 2 7 7 4096 May 1 1994 bin"); assertEquals("bin", f4.getName()); assertEquals(true, f4.isDirectory()); assertEquals(4096, f4.getSize()); assertEquals("May 1", f4.getDate()); assertEquals("1994", f4.getTime()); } public void testSoftLink() throws Exception { FileInfo f4 = new FileInfo("lrwxrwxrwx 1 root root 10 Nov 2 2001 mouse -> /dev/psaux"); assertEquals(true, f4.isSoftLink()); assertEquals("mouse -> /dev/psaux", f4.getName()); assertEquals(10, f4.getSize()); assertEquals("Nov 2", f4.getDate()); assertEquals("2001", f4.getTime()); } /** character device. an entry of /dev directory has slightly different format */ public void testCharDev() throws Exception { FileInfo f5 = new FileInfo("crw-rw-rw- 1 root tty 3, 24 Apr 14 2001 ttyq8"); assertEquals(true, f5.isDevice()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getName()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getDate()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getTime()); assertEquals(FileInfo.UNKNOWN_NUMBER,f5.getSize()); } /** block device. an entry of /dev directory has slightly different format */ public void testBlockDev() throws Exception { FileInfo f5 = new FileInfo("brw-rw---- 1 root cdrom 15, 0 Apr 14 2001 sonycd"); assertEquals(true, f5.isDevice()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getName()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getDate()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getTime()); assertEquals(FileInfo.UNKNOWN_NUMBER,f5.getSize()); } /** suppose that group is missing in /dev directory entry */ public void testCharDev2() throws Exception { FileInfo f5 = new FileInfo("crw-rw-rw- 1 root 3, 24 Apr 14 2001 ttyq8"); assertEquals(true, f5.isDevice()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getName()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getDate()); assertEquals(FileInfo.UNKNOWN_STRING,f5.getTime()); assertEquals(FileInfo.UNKNOWN_NUMBER,f5.getSize()); } public void testPermission() throws Exception { FileInfo f1 = new FileInfo("-rwxrw-r-- 2 guest other 1536 Jan 31 15:15 run.bat"); int mode = (1 << 8) + (1 << 7) + (1 << 6) + (1 << 5) + (1 << 4) + (1 << 2); assertEquals(mode,f1.getMode()); assertEquals("764",f1.getModeAsString()); assertEquals(true,f1.userCanRead()); assertEquals(true,f1.userCanWrite()); assertEquals(true,f1.userCanExecute()); assertEquals(true,f1.groupCanRead()); assertEquals(true,f1.groupCanWrite()); assertEquals(false,f1.groupCanExecute()); assertEquals(true,f1.allCanRead()); assertEquals(false,f1.allCanWrite()); assertEquals(false,f1.allCanExecute()); f1 = new FileInfo("------x-wx 2 guest other 1536 Jan 31 15:15 run.bat"); mode = (1 << 3) + (1 << 1) + (1 << 0); assertEquals(mode,f1.getMode()); assertEquals("013",f1.getModeAsString()); assertEquals(false,f1.userCanRead()); assertEquals(false,f1.userCanWrite()); assertEquals(false,f1.userCanExecute()); assertEquals(false,f1.groupCanRead()); assertEquals(false,f1.groupCanWrite()); assertEquals(true,f1.groupCanExecute()); assertEquals(false,f1.allCanRead()); assertEquals(true,f1.allCanWrite()); assertEquals(true,f1.allCanExecute()); } /* public void test() throws Exception { String b = "drwxrwxr-x 2 7 7 4096 May 1 1994 bin\n" + "drwxrwx-wx 16 468 861 4096 Oct 2 15:19 chammp\n" + "drwxrws-wx 2 1487 1123 4096 Oct 28 1999 chemio\n" + "drwxrwxr-x 2 7 7 4096 Mar 1 1994 dev\n" + "dr-xrwxr-x 2 7 7 4096 Oct 25 16:00 etc\n" + "drwxrws-wx 7 7 300 4096 Nov 14 07:03 incoming\n" + "drwxr-xr-x 2 0 0 4096 Sep 27 19:23 lib\n" + "drwxr-xr-x 2 0 0 4096 Oct 9 1999 lost+found\n" + "drwxr-xr-x 2 793 76 4096 Apr 17 2002 openpbs\n" + "lrwxrwxrwx 1 0 0 21 Sep 20 04:39 pieper -> pub/People/pieper/old\n" + "drwxrwxr-x 72 7 7 4096 Oct 25 15:58 pub\n" + "drwxrwxr-x 3 7 7 4096 Mar 1 1994 usr\n" + "drwxr-sr-x 2 793 76 4096 May 10 1999 wiki\n"; java.io.BufferedReader r = new java.io.BufferedReader(new java.io.StringReader(b)); String line; while( (line = r.readLine()) != null) { System.out.println(line); new FileInfo(line); } } */ } GridFTPClient2PartyAsynchTransferTest.java000066400000000000000000000114601241116057200357600ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.Session; import org.globus.ftp.GridFTPClient; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.vanilla.FTPServerFacade; import org.globus.ftp.InputStreamDataSink; import org.globus.ftp.OutputStreamDataSource; import org.globus.ftp.vanilla.TransferState; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; /** Test GridFTPClient.get() and put() **/ public class GridFTPClient2PartyAsynchTransferTest extends GridFTPClient2PartyTransferTest { protected static Log logger = LogFactory.getLog(GridFTPClient2PartyAsynchTransferTest.class.getName()); public GridFTPClient2PartyAsynchTransferTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(GridFTPClient2PartyAsynchTransferTest.class); } public void testGetPassive() throws Exception { testGet(Session.SERVER_ACTIVE); } public void testGetActive() throws Exception { //testGet(Session.SERVER_PASSIVE); } public void testPutPassive() throws Exception { testPut(Session.SERVER_ACTIVE); } public void testPutActive() throws Exception { //testPut(Session.SERVER_PASSIVE); } protected void get(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(getCredential()); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); if (localServerMode == Session.SERVER_ACTIVE) { client.setPassive(); client.setLocalActive(); } else { if (TestEnv.localServerPort == TestEnv.UNDEFINED) { client.setLocalPassive(); } else { client.setLocalPassive(TestEnv.localServerPort, FTPServerFacade.DEFAULT_QUEUE); } client.setActive(); } InputStreamDataSink sink = new InputStreamDataSink(); TransferState s = client.asynchGet(fullRemoteFile, sink, null); FileOutputStream out = new FileOutputStream(fullLocalFile); InputStream in = sink.getInputStream(); byte [] buff = new byte[2048]; int bytes = 0; while ( (bytes = in.read(buff)) != -1 ) { out.write(buff, 0, bytes); logger.debug("wrote: " + bytes); } out.close(); in.close(); s.waitForEnd(); } /** This method performs the actual transfer **/ protected void put(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(getCredential()); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); if (localServerMode == Session.SERVER_ACTIVE) { client.setPassive(); client.setLocalActive(); } else { if (TestEnv.localServerPort == TestEnv.UNDEFINED) { client.setLocalPassive(); } else { client.setLocalPassive(TestEnv.localServerPort, FTPServerFacade.DEFAULT_QUEUE); } client.setActive(); } logger.debug("sending file " + fullLocalFile); OutputStreamDataSource source = new OutputStreamDataSource(2048); TransferState s = client.asynchPut(fullRemoteFile, source, null); FileInputStream in = new FileInputStream(fullLocalFile); OutputStream out = source.getOutputStream(); byte [] buff = new byte[2048]; int bytes = 0; while ( (bytes = in.read(buff)) != -1 ) { out.write(buff, 0, bytes); logger.debug("wrote: " + bytes); } out.close(); in.close(); s.waitForEnd(); } } GridFTPClient2PartyParallelTest.java000066400000000000000000000125641241116057200345700ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.GridFTPClient; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.Session; import org.globus.ftp.GridFTPSession; import org.globus.ftp.RetrieveOptions; import org.globus.ftp.FileRandomIO; import org.globus.ftp.DataSource; import org.globus.ftp.DataSink; import java.io.RandomAccessFile; import junit.framework.Test; import junit.framework.TestSuite; /** Test parallel GridFTPClient.get() and put() **/ public class GridFTPClient2PartyParallelTest extends GridFTPClient2PartyTest { int parallelism = 1; //use inherited logger //private static Log logger = //LogFactory.getLog(GridFTPClient2PartyParallelTest.class.getName()); public GridFTPClient2PartyParallelTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(GridFTPClient2PartyParallelTest.class); } // overriden methods /** Test get() and put() with parallelism ranging from 1 to the test property org.globus.ftp.test.gridftp.parallelism **/ public void testGet() { //int i = 5; title(); for (int i = 1; i <= TestEnv.parallelism; i++) { this.parallelism = i; super.testGet(); } } public void testPut() { //int i = 5; title(); for (int i = 1; i <= TestEnv.parallelism; i++) { this.parallelism = i; super.testPut(); } } protected void title() { logger.info("Testing:"); logger.info("parallel 2 party transfer\n\n"); } protected void testGet(String host, int port, String subject, String remoteDir, String remoteFile, String localDir) throws Exception{ logger.info("with configuration: parallel, passive, image, eblock"); testGet(host, port, subject, remoteDir + "/" + remoteFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_IMAGE, GridFTPSession.MODE_EBLOCK); // stream mode not supported with parallelism } protected void testPut(String host, int port, String subject, String remoteDir, String localDir, String localFile) throws Exception{ logger.info("with configuration: parallel, active, image, eblock"); testPut(host, port, subject, remoteDir, localFile, localDir, Session.SERVER_ACTIVE, Session.TYPE_IMAGE, GridFTPSession.MODE_EBLOCK); // stream mode not supported with parallelism } protected void get(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(null); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); // adding parallelism logger.info("parallelism: " + parallelism); client.setOptions(new RetrieveOptions(parallelism)); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); // in extended block mode, receiving side must be passive assertTrue(localServerMode == Session.SERVER_PASSIVE); client.setLocalPassive(); /* This seems like a bad test, selecting the same port always results in errors if (TestEnv.localServerPort == TestEnv.UNDEFINED) { client.setLocalPassive(); } else { client.setLocalPassive(TestEnv.localServerPort, org.globus.ftp.vanilla.FTPServerFacade.DEFAULT_QUEUE); } */ client.setActive(); assertTrue(transferMode == GridFTPSession.MODE_EBLOCK); DataSink sink = null; sink = new FileRandomIO(new RandomAccessFile(fullLocalFile, "rw")); client.get(fullRemoteFile, sink, null); } protected void put(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(null); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); // adding parallelism logger.info("parallelism: " + parallelism); client.setOptions(new RetrieveOptions(parallelism)); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); assertTrue(localServerMode == Session.SERVER_ACTIVE); client.setPassive(); client.setLocalActive(); assertTrue(transferMode == GridFTPSession.MODE_EBLOCK); logger.debug("sending file " + fullLocalFile); DataSource source = null; source = new FileRandomIO(new RandomAccessFile(fullLocalFile, "r")); client.put(fullRemoteFile, source, null); } } GridFTPClient2PartyStripingTest.java000066400000000000000000000107231241116057200346260ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.GridFTPClient; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.Session; import org.globus.ftp.GridFTPSession; import org.globus.ftp.RetrieveOptions; import org.globus.ftp.FileRandomIO; import org.globus.ftp.DataSource; import org.globus.ftp.DataSinkStream; import org.globus.ftp.DataSourceStream; import org.globus.ftp.HostPortList; import org.globus.ftp.DataSink; import org.globus.ftp.vanilla.FTPServerFacade; import junit.framework.Test; import junit.framework.TestSuite; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.RandomAccessFile; /** Test GridFTPClient.stripedGet() and stripedPut() **/ public class GridFTPClient2PartyStripingTest extends GridFTPClient2PartyParallelTest { public GridFTPClient2PartyStripingTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(GridFTPClient2PartyStripingTest.class); } // // overriden methods // protected void title() { logger.info("Testing:"); logger.info("striped 2 party transfer\n\n"); } /** This demonstrates striped file storage. **/ protected void get(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(null); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); // adding parallelism logger.info("parallelism: " + parallelism); client.setOptions(new RetrieveOptions(parallelism)); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); // in extended block mode, receiving side must be passive assertTrue(localServerMode == Session.SERVER_PASSIVE); HostPortList hpl = null; /* seems like the same problem. there will be port collissions this way. usign an unset port number only if (TestEnv.localServerPort == TestEnv.UNDEFINED) { hpl = client.setLocalStripedPassive(); } else { hpl = client.setLocalStripedPassive(TestEnv.localServerPort, FTPServerFacade.DEFAULT_QUEUE); } */ hpl = client.setLocalStripedPassive(); client.setStripedActive(hpl); DataSink sink = null; if (transferMode == GridFTPSession.MODE_EBLOCK) { sink = new FileRandomIO(new RandomAccessFile(fullLocalFile, "rw")); } else { sink = new DataSinkStream(new FileOutputStream(fullLocalFile)); } client.get(fullRemoteFile, sink, null); } /** This demonstrates striped file retrieval. **/ protected void put(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(null); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); // adding parallelism logger.info("parallelism: " + parallelism); client.setOptions(new RetrieveOptions(parallelism)); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); assertTrue(localServerMode == Session.SERVER_ACTIVE); client.setStripedPassive(); client.setLocalStripedActive(); logger.debug("sending file " + fullLocalFile); DataSource source = null; if (transferMode == GridFTPSession.MODE_EBLOCK) { source = new FileRandomIO(new RandomAccessFile(fullLocalFile, "r")); } else { source = new DataSourceStream(new FileInputStream(fullLocalFile)); } client.put(fullRemoteFile, source, null); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/GridFTPClient2PartyTest.java000066400000000000000000000401201241116057200331570ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.Session; import org.globus.ftp.GridFTPSession; import org.globus.ftp.DataSource; import org.globus.ftp.FileRandomIO; import org.globus.ftp.GridFTPClient; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.DataSinkStream; import org.globus.ftp.DataSourceStream; import org.globus.ftp.DataSink; import org.globus.ftp.exception.ServerException; import org.globus.ftp.vanilla.FTPServerFacade; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.File; import java.io.RandomAccessFile; import org.ietf.jgss.GSSCredential; import org.gridforum.jgss.ExtendedGSSManager; /** Test GridFTPClient.get() and put() **/ public class GridFTPClient2PartyTest extends TestCase { protected static Log logger = LogFactory.getLog(GridFTPClient2PartyTest.class.getName()); protected GridFTPClient src = null; // note that this can be always null, because // user is not obliged to provide FTP destination server protected GridFTPClient dest = null; public GridFTPClient2PartyTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(GridFTPClient2PartyTest.class); } public void testGet() { try{ // edit here to run multiple tests of same config for(int i = 0; i<1; i++) { logger.info("testing get"); testGet(TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir, TestEnv.serverASmallFile, TestEnv.localDestDir); } } catch (Exception e) { logger.error("", e); fail(e.toString()); } } public void testPut() { if (TestEnv.serverBHost == null) { fail("Test disabled - serverBHost undefined"); } try{ // edit here to run multiple tests of same config for(int i = 0; i<1; i++) { logger.info("testing put"); testPut(TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir, TestEnv.localSrcDir, TestEnv.localSrcFile); } } catch (Exception e) { logger.error("", e); fail(e.toString()); } } /** Try transferring file to and from bad port on existing server. IOException should be thrown. **/ public void testNoSuchPort() throws Exception{ if (TestEnv.serverANoSuchPort == TestEnv.UNDEFINED) { logger.info("Omitting the test: test3Party_noSuchPort"); logger.info("because some necessary properties are not defined."); return; } logger.info("get from non existent port"); boolean caughtOK = false; try { testGet(TestEnv.serverAHost, TestEnv.serverANoSuchPort, TestEnv.serverASubject, TestEnv.serverADir, TestEnv.serverASmallFile, TestEnv.localDestDir); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, " + "but the expected exception has not been thrown."); } } caughtOK = false; try { testPut(TestEnv.serverAHost, TestEnv.serverANoSuchPort, TestEnv.serverASubject, TestEnv.serverBDir, TestEnv.localSrcDir, TestEnv.localSrcFile); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, " + "but the expected exception has not been thrown."); } } } /** Try transferring file to and from non existent server. IOException should be thrown. **/ public void testNoSuchServer() throws Exception{ logger.info("get from non existent server"); boolean caughtOK = false; try { testGet(TestEnv.noSuchServer, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir, TestEnv.serverASmallFile, TestEnv.localDestDir); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, " + "but the expected exception has not been thrown."); } } logger.info("put to non existent server"); caughtOK = false; try { testPut(TestEnv.noSuchServer, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir, TestEnv.serverASmallFile, TestEnv.localDestDir); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } } /** try transferring non existent file; ServerException should be thrown **/ public void testGetNoSuchSrcFile() throws Exception{ logger.info("get with bad src file"); boolean serverFNoSuchFile_OK = false; try { testGet(TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir, TestEnv.serverANoSuchFile, TestEnv.localDestDir); } catch (Exception e) { if (e instanceof ServerException) { logger.debug(e.toString()); serverFNoSuchFile_OK = true; logger.debug("Test passed: ServerException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!serverFNoSuchFile_OK) { fail("Attempted to transfer non existent file, but " + "no exception has been thrown."); } } } /** try transferring file to non existent directory; ServerException should be thrown. **/ public void testPutNoSuchDestDir() throws Exception{ logger.info("put with bad dest dir"); boolean serverGNoSuchDir_OK = false; try { testPut(TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBNoSuchDir, TestEnv.localSrcDir, TestEnv.localSrcFile); } catch (Exception e) { if (e instanceof ServerException) { logger.debug(e.toString()); serverGNoSuchDir_OK = true; logger.debug("Test passed: ServerException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!serverGNoSuchDir_OK) { fail("Attempted to transfer to non existent dir, but " + "no exception has been thrown."); } } } protected void testGet(String host, int port, String subject, String remoteDir, String remoteFile, String localDir) throws Exception{ logger.info("with configuration: passive, image, eblock"); testGet(host, port, subject, remoteDir + "/" + remoteFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_IMAGE, GridFTPSession.MODE_EBLOCK); logger.info("with configuration: passive, image, stream"); testGet(host, port, subject, remoteDir + "/" + remoteFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_IMAGE, Session.MODE_STREAM); logger.info("with configuration: passive, ascii, stream"); testGet(host, port, subject, remoteDir + "/" + remoteFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_ASCII, Session.MODE_STREAM); } protected void testGet(String host, int port, String subject, String fullRemoteFile, String localDestDir, int localServerMode, int transferType, int transferMode) throws Exception { String smode = (localServerMode == Session.SERVER_PASSIVE)? "pasv" : "actv"; String tmode = (transferMode == Session.MODE_STREAM) ? "stream" : "eblock"; String ttype = (transferType == Session.TYPE_ASCII) ? "ascii" : "image"; DataChannelAuthentication dcau = null; int prot = -1; for (int i = 0; i < 3; i ++) { switch (i) { case 0: dcau = DataChannelAuthentication.NONE; prot = GridFTPSession.PROTECTION_CLEAR; break; case 1: dcau = DataChannelAuthentication.SELF; prot = GridFTPSession.PROTECTION_CLEAR; break; case 2: dcau = DataChannelAuthentication.SELF; prot = GridFTPSession.PROTECTION_SAFE; break; default: throw new Exception(); } String dcauStr = (dcau == DataChannelAuthentication.NONE) ? "nodcau" : "dcau" ; String protStr = (prot == GridFTPSession.PROTECTION_CLEAR) ? "clear" : "safe"; logger.info("with configuration: " + dcauStr + ", " + protStr); String fullLocalFile = localDestDir + "/c2p2.get." + smode + "." + tmode +"." + ttype + "." + dcauStr + "." + protStr + "." + System.currentTimeMillis(); GridFTPClient client = new GridFTPClient(host, port); client.setAuthorization(TestEnv.getAuthorization(subject)); get(client, localServerMode, transferType, transferMode, dcau, prot, fullLocalFile, fullRemoteFile); long size = client.getSize(fullRemoteFile); client.close(); // if type = ASCII, file size before and after transfer may // differ, otherwise they shouldn't if (transferType != Session.TYPE_ASCII) { File f = new File(fullLocalFile); assertEquals(fullRemoteFile + " -> " + fullLocalFile, size, f.length()); } } } /** This method performs the actual transfer **/ protected void get(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(getCredential()); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); if (localServerMode == Session.SERVER_ACTIVE) { client.setPassive(); client.setLocalActive(); } else { client.setLocalPassive(); client.setActive(); } DataSink sink = null; if (transferMode == GridFTPSession.MODE_EBLOCK) { sink = new FileRandomIO(new RandomAccessFile(fullLocalFile, "rw")); } else { sink = new DataSinkStream(new FileOutputStream(fullLocalFile)); } client.get(fullRemoteFile, sink, null); } protected void testPut(String host, int port, String subject, String remoteDir, String localDir, String localFile) throws Exception{ logger.info("with configuration: active, image, eblock"); testPut(host, port, subject, remoteDir, localFile, localDir, Session.SERVER_ACTIVE, Session.TYPE_IMAGE, GridFTPSession.MODE_EBLOCK); logger.info("with configuration: active, image, stream"); testPut(host, port, subject, remoteDir, localFile, localDir, Session.SERVER_ACTIVE, Session.TYPE_IMAGE, Session.MODE_STREAM); logger.info("with configuration: active, ascii, stream"); testPut(host, port, subject, remoteDir, localFile, localDir, Session.SERVER_ACTIVE, Session.TYPE_ASCII, Session.MODE_STREAM); /* cannot put with passive logger.info("pasive, image, eblock"); testPut(host, port, remoteDir, localFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_IMAGE, Session.MODE_EBLOCK); logger.info("pasive, image, stream"); testPut(host, port, remoteDir, localFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_IMAGE, Session.MODE_STREAM); logger.info("pasive, ascii, stream"); testPut(host, port, remoteDir, localFile, localDir, Session.SERVER_PASSIVE, Session.TYPE_ASCII, Session.MODE_STREAM); */ } protected void testPut(String host, int port, String subject, String remoteDestDir, String localFile, String localDir, int localServerMode, int transferType, int transferMode) throws Exception { String smode = (localServerMode == Session.SERVER_PASSIVE)? "pasv" : "actv"; String tmode = (transferMode == Session.MODE_STREAM) ? "stream" : "eblock"; String ttype = (transferType == Session.TYPE_ASCII) ? "ascii" : "image"; DataChannelAuthentication dcau = null; int prot = -1; for (int i = 0; i < 3; i ++) { switch (i) { case 0: dcau = DataChannelAuthentication.NONE; prot = GridFTPSession.PROTECTION_CLEAR; break; case 1: dcau = DataChannelAuthentication.SELF; prot = GridFTPSession.PROTECTION_CLEAR; break; case 2: dcau = DataChannelAuthentication.SELF; prot = GridFTPSession.PROTECTION_SAFE; break; default: throw new Exception(); } String dcauStr = (dcau == DataChannelAuthentication.NONE) ? "nodcau" : "dcau" ; String protStr = (prot == GridFTPSession.PROTECTION_CLEAR) ? "clear" : "safe"; logger.info("with configuration: " + dcauStr + ", " + protStr); String fullLocalFile = localDir + "/" + localFile; String fullRemoteFile = remoteDestDir + "/c2p2.put." + smode + "." + tmode +"." + ttype + "." + dcauStr + "." + protStr + "." + System.currentTimeMillis(); GridFTPClient client = new GridFTPClient(host, port); client.setAuthorization(TestEnv.getAuthorization(subject)); put(client, localServerMode, transferType, transferMode, dcau, prot, fullLocalFile, fullRemoteFile); long size = client.getSize(fullRemoteFile); client.close(); // if type = ASCII, file sizes before and after transfer may // differ, otherwise they shouldn't if (transferType != Session.TYPE_ASCII) { File f = new File(fullLocalFile); assertEquals(fullLocalFile + " -> " + fullRemoteFile, f.length(), size); } } } /** This method performs the actual transfer **/ protected void put(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(getCredential()); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); if (localServerMode == Session.SERVER_ACTIVE) { client.setPassive(); client.setLocalActive(); } else { if (TestEnv.localServerPort == TestEnv.UNDEFINED) { client.setLocalPassive(); } else { client.setLocalPassive(TestEnv.localServerPort, FTPServerFacade.DEFAULT_QUEUE); } client.setActive(); } logger.debug("sending file " + fullLocalFile); DataSource source = null; if (transferMode == GridFTPSession.MODE_EBLOCK) { source = new FileRandomIO(new RandomAccessFile(fullLocalFile, "r")); } else { source = new DataSourceStream(new FileInputStream(fullLocalFile)); } client.put(fullRemoteFile, source, null); } private GSSCredential getCredential() throws Exception { return ExtendedGSSManager.getInstance().createCredential(GSSCredential.INITIATE_AND_ACCEPT); } } GridFTPClient2PartyTransferTest.java000066400000000000000000000225631241116057200346200ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.Session; import org.globus.ftp.GridFTPSession; import org.globus.ftp.DataSource; import org.globus.ftp.FileRandomIO; import org.globus.ftp.GridFTPClient; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.DataSinkStream; import org.globus.ftp.DataSourceStream; import org.globus.ftp.DataSink; import org.globus.ftp.vanilla.FTPServerFacade; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.File; import java.io.RandomAccessFile; import org.ietf.jgss.GSSCredential; import org.gridforum.jgss.ExtendedGSSManager; /** Test GridFTPClient.get() and put() **/ public class GridFTPClient2PartyTransferTest extends TestCase { protected static Log logger = LogFactory.getLog(GridFTPClient2PartyTransferTest.class.getName()); public GridFTPClient2PartyTransferTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(GridFTPClient2PartyTransferTest.class); } public void testGetPassive() throws Exception { testGet(Session.SERVER_ACTIVE); } public void testGetActive() throws Exception { testGet(Session.SERVER_PASSIVE); // test EBLOCK testGet(Session.SERVER_PASSIVE, Session.TYPE_IMAGE, GridFTPSession.MODE_EBLOCK); } public void testPutPassive() throws Exception { testPut(Session.SERVER_ACTIVE); // test EBLOCK testPut(Session.SERVER_ACTIVE, Session.TYPE_IMAGE, GridFTPSession.MODE_EBLOCK); } public void testPutActive() throws Exception { testPut(Session.SERVER_PASSIVE); } // --------- internal functions ----------------- // test two stream binary and stream ascii protected void testGet(int localServerMode) throws Exception { testGet(localServerMode, Session.TYPE_IMAGE, Session.MODE_STREAM); testGet(localServerMode, Session.TYPE_ASCII, Session.MODE_STREAM); } // test no dcau, dcau with clear, and dcau with safe protected void testGet(int localServerMode, int transferType, int transferMode) throws Exception { testGet(localServerMode, transferType, transferMode, DataChannelAuthentication.NONE, GridFTPSession.PROTECTION_CLEAR); testGet(localServerMode, transferType, transferMode, DataChannelAuthentication.SELF, GridFTPSession.PROTECTION_CLEAR); testGet(localServerMode, transferType, transferMode, DataChannelAuthentication.SELF, GridFTPSession.PROTECTION_SAFE); } protected void testGet(int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot) throws Exception { String smode = (localServerMode == Session.SERVER_PASSIVE)? "pasv" : "actv"; String tmode = (transferMode == Session.MODE_STREAM) ? "stream" : "eblock"; String ttype = (transferType == Session.TYPE_ASCII) ? "ascii" : "image"; String dcauStr = (dcau == DataChannelAuthentication.NONE) ? "nodcau" : "dcau"; String protStr = (prot == GridFTPSession.PROTECTION_CLEAR) ? "clear" : "safe"; logger.info("with configuration: " + dcauStr + ", " + protStr); String fullRemoteFile = TestEnv.serverADir + "/" + TestEnv.serverASmallFile; String fullLocalFile = TestEnv.localDestDir + "/c2ptt.get." + smode + "." + tmode +"." + ttype + "." + dcauStr + "." + protStr + "." + System.currentTimeMillis(); GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); get(client, localServerMode, transferType, transferMode, dcau, prot, fullLocalFile, fullRemoteFile); long size = client.getSize(fullRemoteFile); client.close(); // if type = ASCII, file size before and after transfer may // differ, otherwise they shouldn't if (transferType != Session.TYPE_ASCII) { File f = new File(fullLocalFile); assertEquals(fullRemoteFile + " -> " + fullLocalFile, size, f.length()); } } // test two stream binary and stream ascii protected void testPut(int localServerMode) throws Exception { testPut(localServerMode, Session.TYPE_IMAGE, Session.MODE_STREAM); testPut(localServerMode, Session.TYPE_ASCII, Session.MODE_STREAM); } // test no dcau, dcau with clear, and dcau with safe protected void testPut(int localServerMode, int transferType, int transferMode) throws Exception { testPut(localServerMode, transferType, transferMode, DataChannelAuthentication.NONE, GridFTPSession.PROTECTION_CLEAR); testPut(localServerMode, transferType, transferMode, DataChannelAuthentication.SELF, GridFTPSession.PROTECTION_CLEAR); testPut(localServerMode, transferType, transferMode, DataChannelAuthentication.SELF, GridFTPSession.PROTECTION_SAFE); } protected void testPut(int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot) throws Exception { String smode = (localServerMode == Session.SERVER_PASSIVE)? "pasv" : "actv"; String tmode = (transferMode == Session.MODE_STREAM) ? "stream" : "eblock"; String ttype = (transferType == Session.TYPE_ASCII) ? "ascii" : "image"; String dcauStr = (dcau == DataChannelAuthentication.NONE) ? "nodcau" : "dcau"; String protStr = (prot == GridFTPSession.PROTECTION_CLEAR) ? "clear" : "safe"; logger.info("with configuration: " + dcauStr + ", " + protStr); String fullLocalFile = TestEnv.localSrcDir + "/" + TestEnv.localSrcFile; String fullRemoteFile = TestEnv.serverBDir + "/c2ptt.put." + smode + "." + tmode +"." + ttype + "." + dcauStr + "." + protStr + "." + System.currentTimeMillis(); GridFTPClient client = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); put(client, localServerMode, transferType, transferMode, dcau, prot, fullLocalFile, fullRemoteFile); long size = client.getSize(fullRemoteFile); client.close(); // if type = ASCII, file sizes before and after transfer may // differ, otherwise they shouldn't if (transferType != Session.TYPE_ASCII) { File f = new File(fullLocalFile); assertEquals(fullLocalFile + " -> " + fullRemoteFile, f.length(), size); } } /** This method performs the actual transfer **/ protected void get(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(getCredential()); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); if (localServerMode == Session.SERVER_ACTIVE) { client.setPassive(); client.setLocalActive(); } else { client.setLocalPassive(); client.setActive(); } DataSink sink = null; if (transferMode == GridFTPSession.MODE_EBLOCK) { sink = new FileRandomIO(new RandomAccessFile(fullLocalFile, "rw")); } else { sink = new DataSinkStream(new FileOutputStream(fullLocalFile)); } client.get(fullRemoteFile, sink, null); } /** This method performs the actual transfer **/ protected void put(GridFTPClient client, int localServerMode, int transferType, int transferMode, DataChannelAuthentication dcau, int prot, String fullLocalFile, String fullRemoteFile) throws Exception{ client.authenticate(getCredential()); /* use default cred */ client.setProtectionBufferSize(16384); client.setType(transferType); client.setMode(transferMode); client.setDataChannelAuthentication(dcau); client.setDataChannelProtection(prot); if (localServerMode == Session.SERVER_ACTIVE) { client.setPassive(); client.setLocalActive(); } else { client.setLocalPassive(); client.setActive(); } logger.debug("sending file " + fullLocalFile); DataSource source = null; if (transferMode == GridFTPSession.MODE_EBLOCK) { source = new FileRandomIO(new RandomAccessFile(fullLocalFile, "r")); } else { source = new DataSourceStream(new FileInputStream(fullLocalFile)); } client.put(fullRemoteFile, source, null); } protected GSSCredential getCredential() throws Exception { return ExtendedGSSManager.getInstance().createCredential(GSSCredential.INITIATE_AND_ACCEPT); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/GridFTPClientTest.java000066400000000000000000000676171241116057200321010ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.GridFTPClient; import org.globus.ftp.RetrieveOptions; import org.globus.ftp.HostPortList; import org.globus.ftp.GridFTPSession; import org.globus.ftp.StreamModeRestartMarker; import org.globus.ftp.FeatureList; import org.globus.ftp.FileInfo; import org.globus.ftp.Session; import org.globus.ftp.HostPort; import org.globus.ftp.Options; import org.globus.ftp.DataSink; import org.globus.ftp.DataSource; import org.globus.ftp.Buffer; import org.globus.ftp.vanilla.Reply; import org.globus.ftp.ChecksumAlgorithm; import org.globus.ftp.exception.ServerException; import org.globus.ftp.MlsxEntry; import org.globus.ftp.FileRandomIO; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Date; import java.util.Vector; import java.io.File; import java.io.RandomAccessFile; import java.io.IOException; import java.io.ByteArrayOutputStream; import org.ietf.jgss.GSSCredential; public class GridFTPClientTest extends TestCase { private static Log logger = LogFactory.getLog(GridFTPClientTest.class.getName()); public GridFTPClientTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(GridFTPClientTest.class); } private GridFTPClient connect() throws Exception { GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); client.authenticate(null); return client; } public void testControlChannelProtectionEnc() throws Exception { GridFTPClient client = null; client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); client.setControlChannelProtection(GridFTPSession.PROTECTION_PRIVATE); client.authenticate(null); client.getCurrentDir(); client.close(); } public void testControlChannelProtectionSig() throws Exception { GridFTPClient client = null; client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); client.setControlChannelProtection(GridFTPSession.PROTECTION_SAFE); client.authenticate(null); client.getCurrentDir(); client.close(); } public void testExists() throws Exception { GridFTPClient client = connect(); assertTrue("file", client.exists(TestEnv.serverADir + "/" + TestEnv.serverAFile)); assertTrue("dir", client.exists(TestEnv.serverADir)); assertFalse("file2", client.exists("foobar")); client.close(); } public void testSize() throws Exception { logger.info("getSize()"); GridFTPClient client = connect(); client.changeDir(TestEnv.serverADir); assertEquals(true, client.exists(TestEnv.serverAFile)); client.setType(Session.TYPE_IMAGE); long size = client.getSize(TestEnv.serverAFile); assertEquals(TestEnv.serverAFileSize, size); Date d = client.getLastModified(TestEnv.serverAFile); client.close(); } public void testDir() throws Exception { logger.info("makeDir()"); GridFTPClient client = connect(); String tmpDir = "abcdef"; String baseDir = client.getCurrentDir(); client.makeDir(tmpDir); client.changeDir(tmpDir); assertEquals(baseDir + "/" + tmpDir, client.getCurrentDir()); client.goUpDir(); assertEquals(baseDir, client.getCurrentDir()); client.deleteDir(tmpDir); try { client.changeDir(tmpDir); fail("directory should have been removed"); } catch (Exception e) { } client.close(); } public void testFeature() throws Exception { logger.info("getFeatureList()"); GridFTPClient client = connect(); FeatureList fl = client.getFeatureList(); assertEquals(true, fl.contains("DcaU")); assertEquals(false, fl.contains("MIS")); assertTrue(client.isFeatureSupported("DcaU")); assertFalse(client.isFeatureSupported("MIS")); client.close(); } public void testQuote() throws Exception { GridFTPClient client = connect(); client.setType(Session.TYPE_IMAGE); client.changeDir(TestEnv.serverADir); Reply r = client.quote("size " + TestEnv.serverAFile); assertTrue(Reply.isPositiveCompletion(r)); assertEquals(TestEnv.serverAFileSize, Long.parseLong(r.getMessage())); client.close(); } public void testSite() throws Exception { GridFTPClient client = connect(); Reply r = client.site("help"); assertTrue(Reply.isPositiveCompletion(r)); assertTrue(r.getMessage().indexOf("PASV") != -1); client.close(); } public void testDirRename() throws Exception { GridFTPClient client = connect(); String tmpDir = "abcdef"; client.makeDir(tmpDir); String newName = "foo-" + System.currentTimeMillis(); client.rename(tmpDir, newName); client.rename(newName, tmpDir); client.deleteDir(tmpDir); client.close(); } public void testOptions() throws Exception { logger.info("retrieveOptions()"); GridFTPClient client = connect(); Options opts = new RetrieveOptions(3); client.setOptions(opts); client.close(); } public void testRestartMarker() throws Exception { logger.info("setRestartMarker()"); GridFTPClient client = connect(); StreamModeRestartMarker rm = new StreamModeRestartMarker(12345); client.setRestartMarker(rm); client.close(); } public void testAllocate() throws Exception { GridFTPClient client = connect(); client.allocate(5); client.close(); } public void testChecksum() throws Exception { GridFTPClient client = connect(); String checksum = client.checksum(ChecksumAlgorithm.MD5, 0, TestEnv.serverAFileSize, TestEnv.serverADir + "/" + TestEnv.serverAFile); assertEquals(TestEnv.serverAFileChecksum, checksum.trim()); client.close(); } public void testListAscii() throws Exception { testList(Session.MODE_STREAM, Session.TYPE_ASCII); } public void testSetChecksum() throws Exception { GridFTPClient client = connect(); FeatureList fl = client.getFeatureList(); if( fl.contains("SCKS")) { client.setChecksum(ChecksumAlgorithm.MD5, TestEnv.serverAFileChecksum); } else { try { client.setChecksum(ChecksumAlgorithm.MD5, TestEnv.serverAFileChecksum); //assertEquals("SCKS should not be supported by the server","SCKS is supported by the server"); } catch ( Exception ex ){ logger.info("SCKS is not supported by the server"); } } client.close(); } public void testListEblock() throws Exception { testList(GridFTPSession.MODE_EBLOCK, Session.TYPE_IMAGE); } private void testList(int mode, int type) throws Exception { logger.info("show list output using GridFTPClient"); GridFTPClient client = connect(); client.setType(type); client.setMode(mode); client.changeDir(TestEnv.serverADir); Vector v = client.list(null, null); logger.debug("list received"); while (! v.isEmpty()) { FileInfo f = (FileInfo)v.remove(0); logger.info(f.toString()); } client.close(); } public void testNListAscii() throws Exception { testNList(Session.MODE_STREAM, Session.TYPE_ASCII); } public void testNListEblock() throws Exception { testNList(GridFTPSession.MODE_EBLOCK, Session.TYPE_IMAGE); } private void testNList(int mode, int type) throws Exception { logger.info("show list output using GridFTPClient"); GridFTPClient client = connect(); client.setType(type); client.setMode(mode); client.changeDir(TestEnv.serverADir); Vector v = client.nlist(); logger.debug("list received"); while (! v.isEmpty()) { FileInfo f = (FileInfo)v.remove(0); logger.info(f.toString()); } client.close(); } public void testMListAscii() throws Exception { testMList(Session.MODE_STREAM, Session.TYPE_ASCII); } public void testMListEblock() throws Exception { testMList(GridFTPSession.MODE_EBLOCK, Session.TYPE_IMAGE); } private void testMList(int mode, int type) throws Exception { logger.info("show list output using GridFTPClient"); GridFTPClient client = connect(); client.setType(type); client.setMode(mode); client.changeDir(TestEnv.serverADir); Vector v = client.mlsd(null); logger.debug("list received"); while (! v.isEmpty()) { MlsxEntry f = (MlsxEntry)v.remove(0); logger.info(f.toString()); } client.close(); } public void testList2() throws Exception { logger.info("test two consective list, using both list functions, using GridFTPClient"); GridFTPClient client = connect(); String output1 = null; String output2 = null; // using list() client.changeDir(TestEnv.serverADir); Vector v = client.list(null, null); logger.debug("list received"); StringBuffer output1Buffer = new StringBuffer(); while (! v.isEmpty()) { FileInfo f = (FileInfo)v.remove(0); output1Buffer.append(f.toString()).append("\n"); } output1 = output1Buffer.toString(); // using list(String,String, DataSink) HostPort hp2 = client.setPassive(); client.setLocalActive(); final ByteArrayOutputStream received2= new ByteArrayOutputStream(1000); // unnamed DataSink subclass will write data channel content // to "received" stream. client.list(null, null, new DataSink(){ public void write(Buffer buffer) throws IOException{ logger.debug("received " + buffer.getLength() + " bytes of directory listing"); received2.write(buffer.getBuffer(), 0, buffer.getLength()); } public void close() throws IOException{}; }); // transfer done. Data is in received2 stream. output2 = received2.toString(); logger.debug(output2); client.close(); } public void testConnectionReset1() throws Exception { DataSink sink = (new DataSink() { public void write(Buffer buffer) throws IOException{ logger.debug("received " + buffer.getLength() + " bytes of directory listing"); } public void close() throws IOException{}; }); GridFTPClient client = connect(); String pwd = client.getCurrentDir(); client.setPassiveMode(false); try { client.get(TestEnv.serverANoSuchFile, sink, null); fail("did not throw expected exception"); } catch (Exception e) { // should fail //e.printStackTrace(); } client.setPassiveMode(true); client.put(new File(TestEnv.localSrcDir + "/" + TestEnv.localSrcFile), TestEnv.serverBDir + "/" + TestEnv.serverBFile, false); assertEquals(pwd, client.getCurrentDir()); client.close(); } public void testConnectionReset2() throws Exception { DataSink sink = (new DataSink() { public void write(Buffer buffer) throws IOException{ logger.debug("received " + buffer.getLength() + " bytes of directory listing"); } public void close() throws IOException{}; }); GridFTPClient client = connect(); String pwd = client.getCurrentDir(); client.setPassiveMode(true); try { client.get(TestEnv.serverANoSuchFile, sink, null); fail("did not throw expected exception"); } catch (Exception e) { // should fail //e.printStackTrace(); } // client.setPassiveMode(true); // client.nlist(); // assertEquals(pwd, client.getCurrentDir()); client.close(); } public void testConnectionReset3() throws Exception { DataSink sink = (new DataSink() { public void write(Buffer buffer) throws IOException{ logger.debug("received " + buffer.getLength() + " bytes of directory listing"); } public void close() throws IOException{}; }); GridFTPClient client = connect(); client.setMode(GridFTPSession.MODE_EBLOCK); client.setType(Session.TYPE_IMAGE); String pwd = client.getCurrentDir(); client.setOptions(new RetrieveOptions(4)); client.setPassiveMode(false); try { client.get(TestEnv.serverANoSuchFile, sink, null); fail("did not throw expected exception"); } catch (Exception e) { // should fail //e.printStackTrace(); } DataSource source = new FileRandomIO(new RandomAccessFile( TestEnv.localSrcDir + "/" + TestEnv.localSrcFile, "r")); client.setPassiveMode(true); client.put(TestEnv.serverBDir + "/" + TestEnv.serverBFile, source, null); assertEquals(pwd, client.getCurrentDir()); client.close(); } // try third party transfer. no exception should be thrown. public void test3PartyModeE() throws Exception { logger.info("3 party mode E"); try { test3PartyModeE( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null // use default cred ); } catch (Exception e) { logger.error("", e); fail(e.toString()); } } // try third party transfer. no exception should be thrown. public void test3Party() throws Exception{ logger.info("3 party"); try { test3Party( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null // use default cred ); } catch (Exception e) { logger.error("", e); fail(e.toString()); } } // Try transferring file to and from bad port on existing server. // IOException should be thrown. public void test3PartyNoSuchPort() throws Exception{ logger.info("3 party with bad port"); if (TestEnv.serverANoSuchPort == TestEnv.UNDEFINED) { logger.info("Omitting the test: test3Party_noSuchPort"); logger.info("because some necessary properties are not defined."); return; } logger.debug("transfer FROM non existent port"); boolean caughtOK = false; try { test3Party( TestEnv.serverAHost, TestEnv.serverANoSuchPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null // use default cred ); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } logger.debug("transfer TO non existent port"); caughtOK = false; try { test3Party( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverAHost, TestEnv.serverANoSuchPort, TestEnv.serverASubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null // use default cred ); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } } // Try transferring file to and from non existent server. // IOException should be thrown. public void test3PartyNoSuchServer() throws Exception{ logger.info("3 party with bad server"); logger.debug("transfer FROM non existent server"); boolean caughtOK = false; try { test3Party( TestEnv.noSuchServer, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null // use default cred ); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } logger.debug("transfer TO non existent server"); caughtOK = false; try { test3Party( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.noSuchServer, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null // use default cred ); } catch (Exception e) { if (e instanceof IOException) { logger.debug(e.toString()); caughtOK = true; logger.debug("Test passed: IOException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!caughtOK) { fail("Attempted to contact non existent server, but the expected exception has not been thrown."); } } } // try transferring non existent file; ServerException should be thrown public void test3PartyNoSuchSrcFile() throws Exception{ logger.info("3 party with bad src file"); boolean serverANoSuchFile_OK = false; try { test3Party( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverANoSuchFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null // use default cred ); } catch (Exception e) { if (e instanceof ServerException) { logger.debug(e.toString()); serverANoSuchFile_OK = true; logger.debug("Test passed: ServerException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!serverANoSuchFile_OK) { fail("Attempted to transfer non existent file, but no exception has been thrown."); } } } // try transferring file to non existent directory; // ServerException should be thrown. public void test3PartyNoSuchDestDir() throws Exception{ logger.info("3 party with bad dest dir"); boolean serverBNoSuchDir_OK = false; try { test3Party( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBNoSuchDir + "/" + TestEnv.serverBFile, null // use default cred ); } catch (Exception e) { if (e instanceof ServerException) { logger.debug(e.toString()); serverBNoSuchDir_OK = true; logger.debug("Test passed: ServerException properly thrown."); } else { logger.error("", e); fail(e.toString()); } } finally { if (!serverBNoSuchDir_OK) { fail("Attempted to transfer to non existent dir, but no exception has been thrown."); } } } private void test3Party(String host1, int port1, String subject1, String sourceFile, String host2, int port2, String subject2, String destFile, GSSCredential cred) throws Exception { GridFTPClient client1 = null; GridFTPClient client2 = null; try { client1 = new GridFTPClient(host1, port1); client1.setAuthorization(TestEnv.getAuthorization(subject1)); client2 = new GridFTPClient(host2, port2); client2.setAuthorization(TestEnv.getAuthorization(subject2)); test3Party_setParams(client1, cred); test3Party_setParams(client2, cred); client1.transfer(sourceFile, client2, destFile, false, null); } finally { if (client1 != null) { try { client1.close(true); } catch (Exception e) { logger.error("", e); } } if (client2 != null) { try { client2.close(true); } catch (Exception e) { logger.error("", e); } } } } private void test3Party_setParams(GridFTPClient client, GSSCredential cred) throws Exception{ client.authenticate(cred); client.setProtectionBufferSize(16384); client.setType(GridFTPSession.TYPE_IMAGE); client.setMode(GridFTPSession.MODE_STREAM); } private void test3PartyModeE(String host1, int port1, String subject1, String sourceFile, String host2, int port2, String subject2, String destFile, GSSCredential cred) throws Exception { GridFTPClient source = null; GridFTPClient dest = null; try { source = new GridFTPClient(host1, port1); source.setAuthorization(TestEnv.getAuthorization(subject1)); dest = new GridFTPClient(host2, port2); dest.setAuthorization(TestEnv.getAuthorization(subject2)); test3PartyModeE_setParams(source, cred); test3PartyModeE_setParams(dest, cred); source.setOptions(new RetrieveOptions(TestEnv.parallelism)); //long size = source.getSize(sourceFile); HostPortList hpl = dest.setStripedPassive(); source.setStripedActive(hpl); source.extendedTransfer(sourceFile, dest, destFile, null); } finally { if (source != null) { try { source.close(true); } catch (Exception e) { logger.error("", e); } } if (dest != null) { try { dest.close(true); } catch (Exception e) { logger.error("", e); } } } } private void test3PartyModeE_setParams(GridFTPClient client, GSSCredential cred) throws Exception{ client.authenticate(cred); client.setProtectionBufferSize(16384); client.setType(GridFTPSession.TYPE_IMAGE); client.setMode(GridFTPSession.MODE_EBLOCK); } } GridFTPControlChannelTest.java000066400000000000000000000355371241116057200335110ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.HostPortList; import org.globus.ftp.vanilla.Reply; import org.globus.ftp.vanilla.Command; import org.globus.ftp.vanilla.FTPControlChannel; import org.globus.ftp.extended.GridFTPControlChannel; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ietf.jgss.GSSCredential; /** Test GridFTPControlChannel **/ public class GridFTPControlChannelTest extends TestCase{ private static Log logger = LogFactory.getLog(GridFTPControlChannelTest.class.getName()); public GridFTPControlChannelTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run (suite()); } public static Test suite ( ) { return new TestSuite(GridFTPControlChannelTest.class); } public void test3PartyParallel() throws Exception{ logger.info("3rd party parallel (using OPTS RETR Parallelism)"); try { test3PartyParallel( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null, /* use default cred */ 5 ); } catch (Exception e) { logger.error("", e); fail(e.toString()); } } /** Test authenticate() **/ public void testAuth() throws Exception{ logger.info("authenticate()"); try { testAuth(TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, null); /* use default cred */ } catch (Exception e) { logger.error("", e); fail(e.toString()); } } /** Test third party transfer **/ public void test3Party() throws Exception{ logger.info("3rd party"); try { test3Party( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null /* use default cred */ ); } catch (Exception e) { logger.error("", e); fail(e.toString()); } } /** Test striped third party transfer **/ public void test3PartyStriping() throws Exception{ logger.info("3rd party striping (using SPAS/SPOR)"); try { test3PartyStriping( TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir + "/" + TestEnv.serverAFile, TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir + "/" + TestEnv.serverBFile, null, /* use default cred */ 5 ); } catch (Exception e) { logger.error("", e); fail(e.toString()); } } private void testAuth(String host, int port, String subject, GSSCredential cred) throws Exception { GridFTPControlChannel pi = new GridFTPControlChannel(host, port); pi.open(); pi.setAuthorization(TestEnv.getAuthorization(subject)); pi.authenticate(cred); } //testAuth private void checkPositive(Reply r) { logger.debug("tester: received: " + r.toString()); if (400<= r.getCode()) { fail("received non positive reply: " + r.toString()); } } private void test3Party(String host1, int port1, String subject1, String sourceFile, String host2, int port2, String subject2, String destFile, GSSCredential cred) throws Exception { // // pi2 = control channel to destination server // GridFTPControlChannel pi2 = new GridFTPControlChannel(host2, port2); pi2.open(); pi2.setAuthorization(TestEnv.getAuthorization(subject2)); logger.debug("Connected to server 2."); pi2.authenticate(cred); pi2.write(new Command("TYPE", "I")); checkPositive(pi2.read()); pi2.write(new Command("PBSZ", "16384")); checkPositive(pi2.read()); pi2.write(new Command("PASV")); Reply pasvReply = pi2.read(); checkPositive(pasvReply); //parse PASV reply of the form: //227 Entering Passive Mode (140,221,65,198,172,18) if (pasvReply.getCode() != 227) fail("received unexpected server reply to Pasv: " + pasvReply.getCode()); String pasvReplyMsg=pasvReply.getMessage(); logger.debug("tester: The message is: " + pasvReplyMsg); int openBracket = pasvReplyMsg.indexOf("("); int closeBracket = pasvReplyMsg.indexOf(")", openBracket); String portCommandParam = pasvReplyMsg.substring(openBracket+1, closeBracket); pi2.write(new Command("STOR", destFile)); //do not wait for reply // // pi1 = control channel to source server // GridFTPControlChannel pi1 = new GridFTPControlChannel(host1, port1); pi1.open(); pi1.setAuthorization(TestEnv.getAuthorization(subject1)); logger.debug("Connected to server 1."); pi1.authenticate(cred); pi1.write(new Command("TYPE", "I")); checkPositive(pi1.read()); pi1.write(new Command("SIZE", sourceFile)); checkPositive(pi1.read()); pi1.write(new Command("PBSZ", "16384")); checkPositive(pi1.read()); //PORT Command port = new Command("PORT", portCommandParam); pi1.write(port); checkPositive(pi1.read()); pi1.write(new Command("RETR", sourceFile)); // 150 Opening BINARY mode data connection. checkPositive(pi1.read()); checkPositive(pi2.read()); //226 Transfer complete checkPositive(pi1.read()); checkPositive(pi2.read()); pi1.write(new Command("QUIT")); pi2.write(new Command("QUIT")); //221 Service closing control connection. checkPositive(pi1.read()); checkPositive(pi2.read()); pi1.close(); pi2.close(); } private void test3PartyParallel(String host1, int port1, String subject1, String sourceFile, String host2, int port2, String subject2, String destFile, GSSCredential cred, int parallelism) throws Exception { // // pi2 = control channel to destination server // GridFTPControlChannel pi2 = new GridFTPControlChannel(host2, port2); pi2.open(); pi2.setAuthorization(TestEnv.getAuthorization(subject2)); logger.debug("Connected to server 2."); pi2.authenticate(cred); //FEAT doesServerSupportParallel(pi2); pi2.write(new Command("TYPE", "I")); checkPositive(pi2.read()); pi2.write(new Command("MODE", "E")); checkPositive(pi2.read()); pi2.write(new Command("PBSZ", "16384")); checkPositive(pi2.read()); pi2.write(new Command("PASV")); Reply pasvReply = pi2.read(); checkPositive(pasvReply); //parse PASV reply of the form: //227 Entering Passive Mode (140,221,65,198,172,18) if (pasvReply.getCode() != 227) fail("received unexpected server reply to Pasv: " + pasvReply.getCode()); String pasvReplyMsg=pasvReply.getMessage(); logger.debug("tester: The message is: " + pasvReplyMsg); int openBracket = pasvReplyMsg.indexOf("("); int closeBracket = pasvReplyMsg.indexOf(")", openBracket); String portCommandParam = pasvReplyMsg.substring(openBracket+1, closeBracket); pi2.write(new Command("STOR", destFile)); //do not wait for reply // // pi1 = control channel to source server // GridFTPControlChannel pi1 = new GridFTPControlChannel(host1, port1); pi1.open(); pi1.setAuthorization(TestEnv.getAuthorization(subject1)); logger.debug("Connected to server 1."); pi1.authenticate(cred); //FEAT doesServerSupportParallel(pi1); pi1.write(new Command("TYPE", "I")); checkPositive(pi1.read()); pi1.write(new Command("MODE", "E")); checkPositive(pi1.read()); pi1.write(new Command("SIZE", sourceFile)); checkPositive(pi1.read()); pi1.write(new Command("OPTS", "RETR Parallelism=" + parallelism + "," + parallelism + "," + parallelism +";")); pi1.write(new Command("PBSZ", "16384")); checkPositive(pi1.read()); //PORT Command port = new Command("PORT", portCommandParam); pi1.write(port); checkPositive(pi1.read()); pi1.write(new Command("RETR", sourceFile)); for(;;) { Reply reply1 = pi1.read(); //200 PORT command successful. if (reply1.getCode() == 200) { continue; } // 150 Opening BINARY mode data connection. if (reply1.getCode() == 150) { continue; } //perf marker if (reply1.getCode() == 112) { continue; } //restart marker if (reply1.getCode() == 111) { continue; } //226 Transfer complete if (reply1.getCode() == 226) { break; } fail("received unexpected reply from server 1: " + reply1.toString()); } for(;;) { Reply reply1 = pi2.read(); //200 PORT command successful. if (reply1.getCode() == 200) { continue; } // 150 Opening BINARY mode data connection. if (reply1.getCode() == 150) { continue; } //perf marker if (reply1.getCode() == 112) { continue; } //restart marker if (reply1.getCode() == 111) { continue; } //226 Transfer complete if (reply1.getCode() == 226) { break; } fail("received unexpected reply from server 2: " + reply1.toString()); } pi1.write(new Command("QUIT")); pi2.write(new Command("QUIT")); //221 Service closing control connection. checkPositive(pi1.read()); checkPositive(pi2.read()); pi1.close(); pi2.close(); }//test3PartyParallel //using ESTO and ERET private void test3PartyStriping(String host1, int port1, String subject1, String sourceFile, String host2, int port2, String subject2, String destFile, GSSCredential cred, int parallelism) throws Exception { // // pi2 = control channel to destination server // GridFTPControlChannel pi2 = new GridFTPControlChannel(host2, port2); pi2.open(); pi2.setAuthorization(TestEnv.getAuthorization(subject2)); logger.debug("Connected to server 2."); pi2.authenticate(cred); //FEAT doesServerSupportParallel(pi2); pi2.write(new Command("TYPE", "I")); checkPositive(pi2.read()); pi2.write(new Command("MODE", "E")); checkPositive(pi2.read()); pi2.write(new Command("PBSZ", "16384")); checkPositive(pi2.read()); pi2.write(new Command("SPAS")); Reply spasReply = pi2.read(); checkPositive(spasReply); logger.debug("tester: Received reply to SPAS."); if (spasReply.getCode() != 229) fail("received unexpected server reply to Spas: " + spasReply.getCode()); String spasReplyMsg=spasReply.getMessage(); logger.debug("tester: The message is: " + spasReplyMsg); String sporCommandParam = new HostPortList(spasReply.getMessage()).toFtpCmdArgument(); pi2.write(new Command("ESTO", "A 0 " + destFile)); //do not wait for reply // // pi1 = control channel to source server // GridFTPControlChannel pi1 = new GridFTPControlChannel(host1, port1); pi1.open(); pi1.setAuthorization(TestEnv.getAuthorization(subject1)); logger.debug("Connected to server 1."); pi1.authenticate(cred); //FEAT doesServerSupportParallel(pi1); pi1.write(new Command("TYPE", "I")); checkPositive(pi1.read()); pi1.write(new Command("MODE", "E")); checkPositive(pi1.read()); pi1.write(new Command("SIZE", sourceFile)); Reply sizeReply = pi1.read(); checkPositive(sizeReply); long sourceFileSize = Long.parseLong(sizeReply.getMessage()); pi1.write(new Command("OPTS", "RETR Parallelism=" + parallelism + "," + parallelism + "," + parallelism +";")); pi1.write(new Command("PBSZ", "16384")); checkPositive(pi1.read()); //PORT Command port = new Command("SPOR", sporCommandParam); pi1.write(port); checkPositive(pi1.read()); pi1.write(new Command("ERET", "P 0 " + sourceFileSize + " " + sourceFile)); for(;;) { Reply reply1 = pi1.read(); //200 PORT command successful. if (reply1.getCode() == 200) { continue; } // 150 Opening BINARY mode data connection. if (reply1.getCode() == 150) { continue; } //perf marker if (reply1.getCode() == 112) { continue; } //restart marker if (reply1.getCode() == 111) { continue; } //226 Transfer complete if (reply1.getCode() == 226) { break; } fail("received unexpected reply from server 1: " + reply1.toString()); } for(;;) { Reply reply2 = pi2.read(); //200 PORT command successful. if (reply2.getCode() == 200) { continue; } // 150 Opening BINARY mode data connection. if (reply2.getCode() == 150) { continue; } //perf marker if (reply2.getCode() == 112) { continue; } //restart marker if (reply2.getCode() == 111) { continue; } //226 Transfer complete if (reply2.getCode() == 226) { break; } fail("received unexpected reply from server 2: " + reply2.toString()); } pi1.write(new Command("QUIT")); pi2.write(new Command("QUIT")); //221 Service closing control connection. checkPositive(pi1.read()); checkPositive(pi2.read()); pi1.close(); pi2.close(); }//test3rdPartyStriping //ensure that the server supports PARALLEL, or fail private void doesServerSupportParallel(FTPControlChannel pi2) throws Exception{ pi2.write(new Command("FEAT")); Reply featReply = pi2.read(); checkPositive(featReply); //logger.debug("tester: feat response received"); String featMsg = featReply.getMessage(); //logger.debug("tester: " + featMsg); int line = 0; int thisLineStarts = 0; int thisLineEnds = 0; for(;;line++) { thisLineEnds =featMsg.indexOf('\n', thisLineStarts); if (thisLineEnds == -1) //PARALLEL extension not found fail("Server does not support PARALLEL"); String thisLine=featMsg.substring(thisLineStarts, thisLineEnds); //logger.debug("feat line -> " + thisLine + "<-"); if (thisLine.indexOf("PARALLEL") != -1) { //PARALLEL found logger.debug("Server does support parallel (feat reply line " + line + " )"); break; } thisLineStarts = thisLineEnds+1; } } } GridFTPRestartMarkerTest.java000066400000000000000000000063241241116057200333560ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.GridFTPRestartMarker; import org.globus.ftp.ByteRangeList; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test GridFTPRestartMarker **/ public class GridFTPRestartMarkerTest extends TestCase { private static Log logger = LogFactory.getLog(GridFTPRestartMarkerTest.class.getName()); private static String nl = System.getProperty("line.separator"); private static String space = " "; public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(GridFTPRestartMarkerTest.class); } public GridFTPRestartMarkerTest(String name) { super(name); } public void testConstructorError() { //make sure only IllegalArgumentE gets thrown // whole reply rather than just a message assertConstructorError("111 Range Marker 0-29"); assertConstructorError("129-Perf Marker\n"); // to < from assertConstructorError("Range Marker 30-45,30-20,50-51"); // bad format assertConstructorError("Range Marker 30-45,46-2e"); assertConstructorError("Range Marker -3,70-82"); assertConstructorError("Range Marker 30-4570-82"); } public void testConstruction() { //simple testConstruction("30-66"); testConstruction("30-45,60-71,100-134"); //adjacent ranges testConstruction("0-17,18-50,51-114", "0-114"); //backwards testConstruction("51-114,18-49,0-16", "0-16,18-49,51-114"); //overlaping ranges testConstruction("44-99,1-5,30-37,0-36", "0-37,44-99"); //real cases (taken from transfer of 500 MB) testConstruction("0-134545408","0-134545408"); testConstruction("134545408-298778624", "134545408-298778624"); testConstruction("298778624-466747392", "298778624-466747392"); } private void testConstruction(String in) { testConstruction(in,in); } private void testConstruction(String in, String out) { logger.info(" constructing: " + in + " -> " + out); GridFTPRestartMarker m = new GridFTPRestartMarker("Range Marker " + in); ByteRangeList l = new ByteRangeList(); l.merge(m.toVector()); assertTrue(l.toFtpCmdArgument().equals(out)); } private void assertConstructorError(String arg) { logger.info("constructing bad: " + arg); boolean threwOk = false; try { new GridFTPRestartMarker(arg); } catch (IllegalArgumentException e) { threwOk = true; } if (! threwOk ) { fail("constructor did not throw an exception when it should have"); } logger.debug("okay, throws exception as expected."); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/HostPortListTest.java000066400000000000000000000140031241116057200320760ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.HostPort; import org.globus.ftp.HostPort6; import org.globus.ftp.HostPortList; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test HostPortList **/ public class HostPortListTest extends TestCase { private static Log logger = LogFactory.getLog(HostPortListTest.class.getName()); private static String nl = System.getProperty("line.separator"); private static String space = " "; static final String param1 = "140,221,65,198,173,202"; static final String msg1 ="Entering Striped Passive Mode" + nl + space + param1 + nl + "229 End"; static final String hp1str = "140,221,65,198,173,202"; static final String hp2str = "140,221,65,198,1,50"; static final String param2 = hp1str + space + hp2str; static final String msg2 ="Entering Striped Passive Mode" + nl + space + hp1str + nl + space + hp2str + nl + "229 End"; static final String msg2_text = hp1str + space + hp2str; static final String hp1str_6 = "|1|140.221.65.198|6789|"; static final String hp2str_6 = "|2|1080::8:800:200C:417A|50|"; static final String param2_6 = hp1str + space + hp2str; static final String msg2_6 ="Entering Striped Passive Mode" + nl + space + hp1str_6 + nl + space + hp2str_6 + nl + "229 End"; static final String msg2_text_6 = hp1str_6 + space + hp2str_6; static final String BAD_REPLY_1 = "MODE E ok."; static final String BAD_REPLY_2 = "Extensions supported:" + nl + space + "REST STREAM" + nl + space + "ESTO" + nl + space + "ERET" + nl + space + "MDTM" + nl + space + "SIZE" + nl + space + "PARALLEL" + nl + space + "DCAU" + nl + "211 END"; static final String hp5str = "127,0,0,1,100,0"; static final String param5 = hp1str + space + hp2str + space + hp5str; static final String msg5 ="Entering Striped Passive Mode" + nl + space + hp1str + nl + space + hp2str + nl + space + hp5str + nl + "229 End"; public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(HostPortListTest.class); } public HostPortListTest(String name) { super(name); } public void testString() { logger.info("testing construction from String"); testString(msg1, param1); testString(msg2, param2); testConstructorError(BAD_REPLY_1); testConstructorError(BAD_REPLY_2); } public void testHP() { logger.info("testing construction from HostPort object"); HostPort hp1 = new HostPort(param1); HostPortList hpl1 = new HostPortList(); hpl1.add(hp1); //double checking - make sure this does not change internal state testObject(hpl1, param1); testObject(hpl1, param1); HostPortList hpl2 = new HostPortList(); hpl2.add(new HostPort(hp1str)); hpl2.add(new HostPort(hp2str)); testObject(hpl2, param2); testObject(hpl2, param2); } public void testMixed() { logger.info("testing construction from String, and later modification by add(HostPort)"); HostPortList hpl2 = new HostPortList(msg1); hpl2.add(new HostPort(hp2str)); testObject(hpl2, param2); testObject(hpl2, param2); hpl2.add(new HostPort(hp5str)); testObject(hpl2, param5); testObject(hpl2, param5); } /** make sure that message "msg" is properly converted to the SPOR command argument "arg" **/ private void testString(String msg, String ftpCmdArg) { String result = new HostPortList(msg).toFtpCmdArgument(); assertEquals(ftpCmdArg, result); } private void testObject(HostPortList hpl, String ftpCmdArg) { String msg = hpl.toFtpCmdArgument(); assertEquals(ftpCmdArg, msg); } /** assume this is a bad argument to HostPortList constructor. make sure the constructor throws an exception. **/ private void testConstructorError(String msg) { logger.info("checking bad message: " + msg); boolean threwOk = false; try { new HostPortList(msg); } catch (IllegalArgumentException e) { threwOk = true; } if (! threwOk ) { fail("HostPortList constructor did not throw an exception when it should have"); } logger.debug("okay, throws exception as expected."); } public void testParseIPv4() { HostPortList list = HostPortList.parseIPv4Format(msg2); assertEquals(2, list.size()); HostPort p1 = new HostPort(hp1str); HostPort p2 = new HostPort(hp2str); assertEquals(p1.getHost(), list.get(0).getHost()); assertEquals(p1.getPort(), list.get(0).getPort()); assertEquals(p2.getHost(), list.get(1).getHost()); assertEquals(p2.getPort(), list.get(1).getPort()); assertEquals(msg2_text, list.toFtpCmdArgument()); } public void testParseIPv6() { HostPortList list = HostPortList.parseIPv6Format(msg2_6); assertEquals(2, list.size()); HostPort6 p1 = new HostPort6(hp1str_6); HostPort6 p2 = new HostPort6(hp2str_6); assertEquals(p1.getHost(), list.get(0).getHost()); assertEquals(p1.getPort(), list.get(0).getPort()); assertEquals(p1.getVersion(), ((HostPort6)list.get(0)).getVersion()); assertEquals(p2.getHost(), list.get(1).getHost()); assertEquals(p2.getPort(), list.get(1).getPort()); assertEquals(p2.getVersion(), ((HostPort6)list.get(1)).getVersion()); assertEquals(msg2_text_6, list.toFtpCmdArgument()); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/HostPortTest.java000066400000000000000000000052651241116057200312540ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.HostPort6; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test HostPort **/ public class HostPortTest extends TestCase { private static Log logger = LogFactory.getLog(HostPortTest.class.getName()); public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(HostPortTest.class); } public HostPortTest(String name) { super(name); } public void testCreateIPv6() { HostPort6 hp = null; hp = new HostPort6(HostPort6.IPv6, "1080::8:800:200C:417A", 123); assertEquals(HostPort6.IPv6, hp.getVersion()); assertEquals("1080::8:800:200C:417A", hp.getHost()); assertEquals(123, hp.getPort()); assertEquals("|2|1080::8:800:200C:417A|123|", hp.toFtpCmdArgument()); hp = new HostPort6(HostPort6.IPv4, "192.168.1.1", 456); assertEquals(HostPort6.IPv4, hp.getVersion()); assertEquals("192.168.1.1", hp.getHost()); assertEquals(456, hp.getPort()); assertEquals("|1|192.168.1.1|456|", hp.toFtpCmdArgument()); } public void testParseIPv6() { parseIPv6("|||6446|", null, null, 6446); parseIPv6("|1|132.235.1.2|6275|", "1", "132.235.1.2", 6275); parseIPv6("|2|1080::8:800:200C:417A|5282|", "2", "1080::8:800:200C:417A", 5282); } private void parseIPv6(String reply, String version, String host, int port) { HostPort6 p = new HostPort6(reply); assertEquals(version, p.getVersion()); assertEquals(host, p.getHost()); assertEquals(port, p.getPort()); String text = p.toFtpCmdArgument(); assertEquals(reply, text); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/InputStreamDataSinkTest.java000066400000000000000000000130411241116057200333530ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import java.io.InputStream; import java.io.EOFException; import org.globus.ftp.Buffer; import org.globus.ftp.InputStreamDataSink; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class InputStreamDataSinkTest extends TestCase { private static Log logger = LogFactory.getLog(InputStreamDataSinkTest.class.getName()); public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(InputStreamDataSinkTest.class); } public InputStreamDataSinkTest(String name) { super(name); } // data sink is closed public void testCloseDataSink() throws Exception { InputStreamDataSink sr = new InputStreamDataSink(); sr.write(new Buffer(new byte[] {'a'}, 1)); sr.write(new Buffer(new byte[] {'b'}, 1)); sr.write(new Buffer(new byte[] {'c'}, 1)); sr.close(); try { sr.write(new Buffer(null, 4)); fail("did not throw exception"); } catch (EOFException e) { } InputStream in = sr.getInputStream(); assertEquals('a', in.read()); assertEquals('b', in.read()); assertEquals('c', in.read()); assertEquals(-1, in.read()); } public void testCloseDataSinkAndStream() throws Exception { InputStreamDataSink sr = new InputStreamDataSink(); Thread1 t = new Thread1(sr); t.start(); // give the thread a chance to run Thread.sleep(2000); sr.close(); assertTrue(t.getException() == null); int n = 5; assertEquals(n, t.getCounter()); InputStream in = sr.getInputStream(); for (int i=0;i restart marker arrived:"); list.merge(marker.toVector()); logger.info("Current transfer state: " + list.toFtpCmdArgument()); } private void perfMarkerArrived(PerfMarker marker) { logger.info("--> perf marker arrived"); // time stamp logger.info("Timestamp = " + marker.getTimeStamp()); // stripe index if (marker.hasStripeIndex()) { try { logger.info("Stripe index =" + marker.getStripeIndex()); } catch (PerfMarkerException e) { enclosing.fail(e.toString()); } }else { logger.info("Stripe index: not present"); } // stripe bytes transferred if (marker.hasStripeBytesTransferred()) { try { logger.info("Stripe bytes transferred = " + marker.getStripeBytesTransferred()); } catch (PerfMarkerException e) { enclosing.fail(e.toString()); } }else { logger.info("Stripe Bytes Transferred: not present"); } // total stripe count if (marker.hasTotalStripeCount()) { try { logger.info("Total stripe count = " + marker.getTotalStripeCount()); } catch (PerfMarkerException e) { enclosing.fail(e.toString()); } }else { logger.info("Total stripe count: not present"); } }//PerfMarkerArrived }//class MarkerListenerImpl private static Log logger = LogFactory.getLog(MarkerTest.class.getName()); public MarkerTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(MarkerTest.class); } public void testModeEMarkers() throws Exception { MarkerListenerImpl listener = new MarkerListenerImpl(); GridFTPClient source = null; GridFTPClient dest = null; try { source = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); source.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); String sourceFile = TestEnv.serverADir + "/" + TestEnv.serverALargeFile; dest = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); dest.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); String destFile = TestEnv.serverBDir + "/" + TestEnv.serverBFile; setParams(source, null); setParams(dest, null); source.setOptions(new RetrieveOptions(TestEnv.parallelism)); HostPortList hpl = dest.setStripedPassive(); source.setStripedActive(hpl); source.extendedTransfer(sourceFile, dest, destFile, listener); logger.info("--> most recent byte range list: " + listener.list.toFtpCmdArgument()); } catch (Exception e) { logger.error("", e); fail(e.toString()); } finally { if (source != null) { try { source.close(); } catch (Exception e) { logger.error("", e); } } if (dest != null) { try { dest.close(); } catch (Exception e) { logger.error("", e); } } } } private void setParams(GridFTPClient client, GSSCredential cred) throws Exception{ client.authenticate(cred); client.setProtectionBufferSize(16384); client.setType(GridFTPSession.TYPE_IMAGE); client.setMode(GridFTPSession.MODE_EBLOCK); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/MlsxTest.java000066400000000000000000000155341241116057200304150ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import java.util.Vector; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.ftp.GridFTPClient; import org.globus.ftp.GridFTPSession; import org.globus.ftp.HostPort; import org.globus.ftp.MlsxEntry; import org.globus.ftp.Session; /** * Test of MlsxEntry class, MLST and MLSD commands */ public class MlsxTest extends TestCase { private static Log logger = LogFactory.getLog(MlsxTest.class.getName()); public static void main(String[] argv) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(MlsxTest.class); } public MlsxTest(String name) { super(name); } /* size -- Size in octets modify -- Last modification time create -- Creation time type -- Entry type unique -- Unique id of file/directory perm -- File permissions, whether read, write, execute is allowed for the login id. lang -- Language of the file name per IANA[12] registry. media-type -- MIME media-type of file contents per IANA registry. charset -- Character set per IANA registry (if not UTF-8) */ public void testMlsxEntry() throws Exception { logger.info("test creation of MlsxEntry"); MlsxEntry entry = new MlsxEntry("Type=file;Size=1024990;Perm=r; /tmp/cap60.pl198.tar.gz"); assertEquals(entry.getFileName(), "/tmp/cap60.pl198.tar.gz"); assertEquals(entry.get(MlsxEntry.TYPE), MlsxEntry.TYPE_FILE); assertEquals(entry.get(MlsxEntry.PERM), "r"); assertEquals(entry.get(MlsxEntry.SIZE), "1024990"); assertEquals(entry.get(MlsxEntry.CREATE), null); entry = new MlsxEntry("Type=dir;Modify=19981107085215;Perm=el; /tmp"); assertEquals(entry.getFileName(), "/tmp"); assertEquals(entry.get(MlsxEntry.TYPE), MlsxEntry.TYPE_DIR); assertEquals(entry.get(MlsxEntry.MODIFY), "19981107085215"); entry = new MlsxEntry("Type=pdir;Modify=19990112030508;Perm=el; .."); assertEquals(entry.getFileName(), ".."); assertEquals(entry.get(MlsxEntry.TYPE), MlsxEntry.TYPE_PDIR); entry = new MlsxEntry("Type=pdir;Perm=e;Unique=keVO1+d?3; two words"); assertEquals(entry.getFileName(), "two words"); entry = new MlsxEntry("Type=file;Perm=r;Unique=keVO1+IH4; leading space"); assertEquals(entry.getFileName(), " leading space"); /* other possible tests from the specs: Type=OS.unix=slink:/foobar;Perm=;Unique=keVO1+4G4; foobar Type=OS.unix=chr-13/29;Perm=;Unique=keVO1+5G4; device Type=OS.unix=blk-11/108;Perm=;Unique=keVO1+6G4; block Type=file;Perm=awr;Unique=keVO1+8G4; writable Type=dir;Perm=cpmel;Unique=keVO1+7G4; promiscuous Type=dir;Perm=;Unique=keVO1+1t2; no-exec Type=file;Perm=r;Unique=keVO1+EG4; two words Type=file;Perm=r;Unique=keVO1+IH4; leading space Type=dir;Perm=cpmdelf;Unique=keVO1+!s2; empty Type=cdir;Perm=cpmel;Unique=keVO1+7G4; test/incoming type=cdir;unique=AQkAAAAAAAABCAAA; / type=dir;unique=AQkAAAAAAAABEAAA; bin Type=cdir;Modify=19990219073522; /iana/assignments/media-types */ } public void testMlst() throws Exception { logger.info("test MLST"); GridFTPClient src = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); src.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); src.authenticate(null); // use default creds src.setType(Session.TYPE_ASCII); src.changeDir(TestEnv.serverADir); MlsxEntry entry = src.mlst(TestEnv.serverAFile); logger.debug(entry.toString()); assertEquals(MlsxEntry.TYPE_FILE, entry.get(MlsxEntry.TYPE)); assertEquals(String.valueOf(TestEnv.serverAFileSize), entry.get(MlsxEntry.SIZE)); assertEquals(TestEnv.serverAFile, entry.getFileName()); src.close(); } public void test3() throws Exception { logger.info("show mlsd output using GridFTPClient"); GridFTPClient src = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); src.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); src.authenticate(null); // use default creds src.setType(Session.TYPE_ASCII); src.changeDir(TestEnv.serverADir); Vector v = src.mlsd(); logger.debug("mlsd received"); while (!v.isEmpty()) { MlsxEntry f = (MlsxEntry) v.remove(0); logger.info(f.toString()); } src.close(); } public void test4() throws Exception { logger.info("get mlsd output using GridFTPClient, EBlock, Image"); GridFTPClient src = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); src.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); src.authenticate(null); // use default creds src.setType(Session.TYPE_IMAGE); src.setMode(GridFTPSession.MODE_EBLOCK); // server sends the listing over data channel. // so in EBlock, it must be active HostPort hp = src.setLocalPassive(); src.setActive(hp); src.changeDir(TestEnv.serverADir); Vector v = src.mlsd(); logger.debug("mlsd received"); while (!v.isEmpty()) { MlsxEntry f = (MlsxEntry) v.remove(0); logger.debug(f.toString()); } src.close(); } public void test5() throws Exception { logger.info( "test two consective mlsd, using both mlsd functions, using GridFTPClient"); GridFTPClient src = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); src.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); src.authenticate(null); // use default creds String output1 = null; String output2 = null; // using mlsd() Vector v = src.mlsd(TestEnv.serverADir); logger.debug("mlsd received"); StringBuffer output1Buffer = new StringBuffer(); while (!v.isEmpty()) { MlsxEntry f = (MlsxEntry) v.remove(0); output1Buffer.append(f.toString()).append("\n"); } output1 = output1Buffer.toString(); logger.debug(output1); // using mlsd 2nd time HostPort hp2 = src.setPassive(); src.setLocalActive(); src.changeDir(TestEnv.serverADir); v = src.mlsd(); logger.debug("mlsd received"); StringBuffer output2Buffer = new StringBuffer(); while (!v.isEmpty()) { MlsxEntry f = (MlsxEntry) v.remove(0); output2Buffer.append(f.toString()).append("\n"); } output2 = output2Buffer.toString(); logger.debug(output2); src.close(); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/MultipleTransfersTest.java000066400000000000000000000214151241116057200331500ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.GridFTPClient; import org.globus.ftp.RetrieveOptions; import org.globus.ftp.GridFTPSession; import org.globus.ftp.FileRandomIO; import org.globus.ftp.DataSink; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.RandomAccessFile; import org.ietf.jgss.GSSCredential; public class MultipleTransfersTest extends TestCase { private static Log logger = LogFactory.getLog(MultipleTransfersTest.class.getName()); public MultipleTransfersTest(String name) { super(name); } public static void main (String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite ( ) { return new TestSuite(MultipleTransfersTest.class); } public void test2PartyMultipleTransfers() throws Exception { logger.info("GridFTP client - client-server - multiple files - stream mode"); GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); String srcFile1 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String srcFile2 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String srcFile3 = TestEnv.serverADir + "/" + TestEnv.serverAFile; File destFile1 = new File(TestEnv.localDestDir + "/" + TestEnv.serverAFile); File destFile2 = new File(TestEnv.localDestDir + "/" + TestEnv.serverAFile); File destFile3 = new File(TestEnv.localDestDir + "/" + TestEnv.serverAFile); setParamsModeS(client, null); /* use default cred */ client.setPassive(); client.setLocalActive(); client.get(srcFile1, destFile1); client.setPassive(); client.setLocalActive(); client.get(srcFile2, destFile2); client.setPassive(); client.setLocalActive(); client.get(srcFile3, destFile3); client.close(); } /* do not reuse data channels */ public void test2PartyMultipleTransfersModeE() throws Exception { logger.info("GridFTP client - client-server - multiple files - stream mode - no d.c. reuse"); GridFTPClient client = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); client.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); String srcFile1 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String srcFile2 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String srcFile3 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String destFile1 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; String destFile2 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; String destFile3 = TestEnv.localDestDir + "/" + TestEnv.serverAFile; setParamsModeE(client, null); /* use default cred */ client.setOptions(new RetrieveOptions(TestEnv.parallelism)); DataSink sink1 = new FileRandomIO(new RandomAccessFile(destFile1, "rw")); client.setLocalPassive(); client.setActive(); client.get(srcFile1, sink1, null); DataSink sink2 = new FileRandomIO(new RandomAccessFile(destFile2, "rw")); client.setLocalPassive(); client.setActive(); client.get(srcFile2, sink2, null); DataSink sink3 = new FileRandomIO(new RandomAccessFile(destFile3, "rw")); client.setLocalPassive(); client.setActive(); client.get(srcFile3, sink3, null); client.close(); } /* Only tests that nothing unusual happens when transferring several files, and that server does not return error. Does not check if files get transferred correctly. Check the server logs to see that no unnecessary commands are sent. */ public void test3PartyMultipleTransfers() throws Exception { logger.info("GridFTP client - 3 party - multiple files - stream mode"); GridFTPClient source = null; GridFTPClient dest = null; try { source = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); source.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); String SrcFile1 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String SrcFile2 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String SrcFile3 = TestEnv.serverADir + "/" + TestEnv.serverAFile; dest = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); dest.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); String DestFile1 = TestEnv.serverBDir + "/" + TestEnv.serverBFile; String DestFile2 = TestEnv.serverBDir + "/" + TestEnv.serverBFile; String DestFile3 = TestEnv.serverBDir + "/" + TestEnv.serverBFile; setParamsModeS(source, null); /* use default cred */ setParamsModeS(dest, null); /* use default cred */ source.transfer(SrcFile1, dest, DestFile1, false, null); source.setActive(dest.setPassive()); source.transfer(SrcFile2, dest, DestFile2, false, null); source.setActive(dest.setPassive()); source.transfer(SrcFile1, dest, DestFile1, false, null); source.setActive(dest.setPassive()); source.transfer(SrcFile3, dest, DestFile3, false, null); source.setActive(dest.setPassive()); source.transfer(SrcFile1, dest, DestFile1, false, null); } catch (Exception e) { logger.error("", e); fail(e.toString()); } finally { if (source != null) { try { source.close(); } catch (Exception e) { logger.error("", e); } } if (dest != null) { try { dest.close(); } catch (Exception e) { logger.error("", e); } } } } private void setParamsModeS(GridFTPClient client, GSSCredential cred) throws Exception{ client.authenticate(cred); client.setProtectionBufferSize(16384); client.setType(GridFTPSession.TYPE_IMAGE); client.setMode(GridFTPSession.MODE_STREAM); } /** try third party transfer. no exception should be thrown. **/ public void test3PartyMultipleTransfersModeE() throws Exception { logger.info("GridFTPClient - 3 party - multiple files - mode E"); GridFTPClient source = null; GridFTPClient dest = null; try { source = new GridFTPClient(TestEnv.serverAHost, TestEnv.serverAPort); source.setAuthorization(TestEnv.getAuthorization(TestEnv.serverASubject)); String SrcFile1 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String SrcFile2 = TestEnv.serverADir + "/" + TestEnv.serverAFile; String SrcFile3 = TestEnv.serverADir + "/" + TestEnv.serverAFile; dest = new GridFTPClient(TestEnv.serverBHost, TestEnv.serverBPort); dest.setAuthorization(TestEnv.getAuthorization(TestEnv.serverBSubject)); String DestFile1 = TestEnv.serverBDir + "/" + TestEnv.serverBFile; String DestFile2 = TestEnv.serverBDir + "/" + TestEnv.serverBFile; String DestFile3 = TestEnv.serverBDir + "/" + TestEnv.serverBFile; setParamsModeE(source, null); /* use default cred */ setParamsModeE(dest, null); /* use default cred */ source.setOptions(new RetrieveOptions(TestEnv.parallelism)); source.setActive(dest.setPassive()); source.transfer(SrcFile1, dest, DestFile1, false, null); source.transfer(SrcFile2, dest, DestFile2, false, null); source.transfer(SrcFile3, dest, DestFile3, false, null); } catch (Exception e) { logger.error("", e); fail(e.toString()); } finally { if (source != null) { try { source.close(); } catch (Exception e) { logger.error("", e); } } if (dest != null) { try { dest.close(); } catch (Exception e) { logger.error("", e); } } } } private void setParamsModeE(GridFTPClient client, GSSCredential cred) throws Exception{ client.authenticate(cred); client.setProtectionBufferSize(16384); client.setType(GridFTPSession.TYPE_IMAGE); client.setMode(GridFTPSession.MODE_EBLOCK); } } OutputStreamDataSourceTest.java000066400000000000000000000122661241116057200340410ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import java.io.OutputStream; import java.io.EOFException; import org.globus.ftp.Buffer; import org.globus.ftp.OutputStreamDataSource; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class OutputStreamDataSourceTest extends TestCase { private static Log logger = LogFactory.getLog(OutputStreamDataSourceTest.class.getName()); public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(OutputStreamDataSourceTest.class); } public OutputStreamDataSourceTest(String name) { super(name); } // data source is closed public void testCloseDataSourceSingle() throws Exception { OutputStreamDataSource sr = new OutputStreamDataSource(512); OutputStream out = sr.getOutputStream(); out.write(1); out.flush(); out.write(2); out.flush(); out.write(3); out.flush(); Buffer buf; buf = sr.read(); assertTrue(buf != null); buf = sr.read(); assertTrue(buf != null); sr.close(); buf = sr.read(); assertTrue(buf == null); } // data source is blocked in read while data source close is called public void testCloseDataSourceMulti() throws Exception { OutputStreamDataSource sr = new OutputStreamDataSource(512); Thread1 t = new Thread1(sr); t.start(); // give the thread a chance to run Thread.sleep(2000); sr.close(); assertEquals(null, t.getBuffer()); assertEquals(null, t.getException()); assertEquals(null, sr.read()); } class Thread1 extends Thread { private Buffer buf; private Exception exception; private OutputStreamDataSource sr; public Thread1(OutputStreamDataSource sr) { this.sr = sr; } public Buffer getBuffer() { return buf; } public Exception getException() { return exception; } public void run() { try { buf = sr.read(); } catch (Exception e) { exception = e; } } } // output stream is blocked in flush while data source close is called public void testCloseDataSourceStream() throws Exception { OutputStreamDataSource sr = new OutputStreamDataSource(512); OutputStream out = sr.getOutputStream(); Thread2 t = new Thread2(out); t.start(); // give the thread a chance to run Thread.sleep(20000); sr.close(); assertTrue(t.getException1() == null); assertTrue(t.getException2() != null); assertTrue(t.getException2() instanceof EOFException); assertTrue(sr.read() == null); } class Thread2 extends Thread { private Exception exception1, exception2; private OutputStream sr; public Thread2(OutputStream sr) { this.sr = sr; } public Exception getException1() { return exception1; } public Exception getException2() { return exception2; } public void run() { try { sr.write(1); sr.flush(); sr.write(2); sr.flush(); sr.write(3); sr.flush(); sr.write(4); sr.flush(); sr.write(5); sr.flush(); sr.write(6); } catch (Exception e) { exception1 = e; return; } try { sr.flush(); } catch (Exception e) { exception2 = e; } } } // output stream is closed while Data Source is calling read() // until it returns null public void testCloseStream() throws Exception { OutputStreamDataSource sr = new OutputStreamDataSource(512); OutputStream out = sr.getOutputStream(); out.write(1); out.flush(); out.write(2); out.flush(); out.write(3); out.flush(); out.close(); Buffer buf = null; buf = sr.read(); assertTrue(buf != null); buf = sr.read(); assertTrue(buf != null); buf = sr.read(); assertTrue(buf != null); buf = sr.read(); assertTrue(buf == null); } public void testCloseStreamThead() throws Exception { OutputStreamDataSource sr = new OutputStreamDataSource(512); Thread3 t = new Thread3(sr); t.start(); OutputStream out = sr.getOutputStream(); out.write(1); out.flush(); out.write(2); out.flush(); out.write(3); out.flush(); out.close(); t.join(1000*60); assertTrue(t.getException() == null); assertEquals(3, t.getCount()); } class Thread3 extends Thread { private Exception exception; private OutputStreamDataSource sr; private int count; public Thread3(OutputStreamDataSource sr) { this.sr = sr; } public Exception getException() { return exception; } public int getCount() { return count; } public void run() { Buffer buf = null; try { while( (buf = sr.read()) != null) { count++; } } catch (Exception e) { exception = e; } } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/PerfMarkerTest.java000066400000000000000000000163601241116057200315260ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.PerfMarker; import org.globus.ftp.exception.PerfMarkerException; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Test PerfMarker **/ public class PerfMarkerTest extends TestCase { private static Log logger = LogFactory.getLog(PerfMarkerTest.class.getName()); private static String nl = System.getProperty("line.separator"); private static String space = " "; public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(PerfMarkerTest.class); } public PerfMarkerTest(String name) { super(name); } /** Test interesting cases of perf marker construction with invalid argument, and ensure that IllegalAgumentException is thrown. **/ public void testConstructorError() { //make sure only IllegalArgumentE gets thrown /* correct: String msg = "Perf Marker" + nl + " Timestamp: 111222333444.5" + nl + " Stripe Index: 5" + nl + " Stripe Bytes Transferred: 987654321987654321" + nl + " Total Stripe Count: 30" + nl + "112 End" + nl; */ // no first line String msg = " Timestamp: 111222333444.5" + nl + " Stripe Index: 5" + nl + " Stripe Bytes Transferred: 987654321987654321" + nl + " Total Stripe Count: 30" + nl + "112 End" + nl; assertConstructorError(msg); // whole reply instead of just message msg = "112-Perf Marker" + nl + " Timestamp: 111222333444.5" + nl + " Stripe Index: 5" + nl + " Stripe Bytes Transferred: 987654321987654321" + nl + " Total Stripe Count: 30" + nl + "112 End" + nl; assertConstructorError(msg); // no timestamp msg = "Perf Marker" + nl + " Stripe Index: 5" + nl + " Stripe Bytes Transferred: 987654321987654321" + nl + " Total Stripe Count: 30" + nl + "112 End" + nl; assertConstructorError(msg); // 211 message instead of 112 msg = "Extensions supported:" + nl + " REST STREAM" + nl + " ESTO" + nl + " ERET" + nl + " MDTM" + nl + " SIZE" + nl + " PARALLEL" + nl + " DCAU" + nl + "211 END"; assertConstructorError(msg); } /** test interesting cases of perf marker construction and examine its get() and has() methods. **/ public void testObject() throws Exception{ // simple String msg = "Perf Marker" + nl + " Timestamp: 111222333444.5" + nl + " Stripe Index: 5" + nl + " Stripe Bytes Transferred: 987654321987654321" + nl + " Total Stripe Count: 30" + nl + "112 End" + nl; testObject(msg, 111222333444.5, true, 5, true, new Long("987654321987654321").longValue(), true, 30); // unordered msg = "Perf Marker" + nl + " Total Stripe Count: 30" + nl + " Stripe Index: 5" + nl + " Stripe Bytes Transferred: 987654321987654321" + nl + " Timestamp: 111222333444.5" + nl + "112 End" + nl; testObject(msg, 111222333444.5, true, 5, true, new Long("987654321987654321").longValue(), true, 30); // missing stripe info msg = "Perf Marker" + nl + " Timestamp: 111222333444.5" + nl + " Total Stripe Count: 30" + nl + "112 End" + nl; testObject(msg, 111222333444.5, false, 0, false, 0, true, 30); // missing count msg = "Perf Marker" + nl + " Timestamp: 111222333444.5" + nl + " Stripe Index: 5" + nl + " Stripe Bytes Transferred: 987654321987654321" + nl + "112 End" + nl; testObject(msg, 111222333444.5, true, 5, true, new Long("987654321987654321").longValue(), false, 0); // missing most info msg = "Perf Marker" + nl + " Timestamp: 111222333444.5" + nl + "112 End" + nl; testObject(msg, 111222333444.5, false, 0, false, 0, false, 0); // zero values msg = "Perf Marker" + nl + " Timestamp: 0" + nl + " Stripe Index: 0" + nl + " Stripe Bytes Transferred: 0" + nl + " Total Stripe Count: 0" + nl + "112 End" + nl; testObject(msg, 0, true, 0, true, 0, true, 0); }//testObject /** test perf marker construction and get() and has() methods. "in" is constructor parameter, other params describe the expected object examination behavior. **/ private void testObject(String in, double ts, boolean hasSI, long si, boolean hasBT, long bt, boolean hasTSC, long tsc) throws Exception{ logger.info("checking object:\n" + in); PerfMarker m = new PerfMarker(in); // time stamp assertTrue(m.getTimeStamp() == ts); // stripe index assertTrue(m.hasStripeIndex() == hasSI); if (m.hasStripeIndex()) { assertTrue(m.getStripeIndex() == si); logger.debug("okay, stripe index matches."); }else { boolean threwOk = false; try { m.getStripeIndex(); } catch (PerfMarkerException e) { threwOk = true; } if (! threwOk ) { fail("method did not throw an exception when it should have"); } logger.debug("okay, throws exception as expected."); } // stripe bytes transferred assertTrue(m.hasStripeBytesTransferred() == hasBT); if (hasBT) { assertTrue(m.getStripeBytesTransferred() == bt); logger.debug("okay, stripe bytes transf matches."); }else { boolean threwOk = false; try { m.getStripeBytesTransferred(); } catch (PerfMarkerException e) { threwOk = true; } if (! threwOk ) { fail("method did not throw an exception when it should have"); } logger.debug("okay, throws exception as expected."); } // total stripe count assertTrue(m.hasTotalStripeCount() == hasTSC); if (hasTSC) { assertTrue(m.getTotalStripeCount() == tsc); logger.debug("okay, stripe count matches."); }else { boolean threwOk = false; try { m.getTotalStripeCount(); } catch (PerfMarkerException e) { threwOk = true; } if (! threwOk ) { fail("method did not throw an exception when it should have"); } logger.debug("okay, throws exception as expected."); } } /** Assume that arg represent an invalid message; ensure that constructor throws IllegalArgumentException. **/ private void assertConstructorError(String arg) { logger.info("checking bad construction:\n" + arg); boolean threwOk = false; try { new PerfMarker(arg); } catch (IllegalArgumentException e) { threwOk = true; } if (! threwOk ) { fail("constructor did not throw an exception when it should have"); } logger.debug("okay, throws exception as expected."); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/ReplyTest.java000066400000000000000000000101121241116057200305500ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.vanilla.Reply; import java.io.BufferedReader; import java.io.StringReader; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.AssertionFailedError; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** test Reply **/ public class ReplyTest extends TestCase { Log logger = LogFactory.getLog(ReplyTest.class.getName()); public static void main(String[] argv) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(ReplyTest.class); } public ReplyTest(String name) { super(name); } public void testReply() { String lineSep = System.getProperty("line.separator"); testReply("230 User pafcio logged in.\r\n", 230, "User pafcio logged in.", false); testReply("200 Command okay.\r\n", 200, "Command okay.", false); testReply("123-First line\r\n" + " Second line\r\n" + " 234 A line beginning with numbers\r\n" + "123 The last line\r\n", 123, "First line" + lineSep + " Second line" + lineSep + " 234 A line beginning with numbers" + lineSep + "123 The last line", true); //superfluous characters after EOL //this is okay; Reply would normally read from stream // so it should not read more than it has to testReply("200 Command okay.\r\naaaa", 200, "Command okay.", false); parseBadReply(""); parseBadReply("\r\n"); parseBadReply("0"); parseBadReply("1 fds\r\n"); parseBadReply(" 1 fds\r\n"); parseBadReply("200p fds\r\n"); parseBadReply("2000 fds\r\n"); parseBadReply("345454"); parseBadReply("345454\r\n"); //no EOL before last line parseBadReply("123-First line\r\n" + " Second line\r\n" + " 234 A line beginning with numbers" + "123 The last line"); } //check if bad reply gets detected private void parseBadReply(String s) { logger.info("bad construction:" + s); boolean thrown = false; try { parseReply(s); } catch (AssertionFailedError e) { thrown = true; } if ( ! thrown) fail("A faulty reply was not detected."); } // fully test reply; check if input values match parsed values private void testReply(String uReplyString, int uCode, String uMessage, boolean uMultiline) { logger.info("testing object: " + uReplyString); int uClass = uCode / 100; try { Reply r = new Reply(new BufferedReader(new StringReader(uReplyString))); int rCode = r.getCode(); arrowQuote("code", rCode); assertTrue(rCode == uCode); int rClass = r.getCategory(); arrowQuote("class", rClass); assertTrue(rClass == uClass); String rMessage = r.getMessage(); arrowQuote("message", rMessage); assertTrue(rMessage.equals(uMessage)); assertTrue(r.isMultiline() == uMultiline); } catch (Exception e) { fail("Exception thrown: " + e.toString()); } } //only parse reply and see if an exception gets thrown private void parseReply(String uReplyString) { logger.debug("parsing: " + uReplyString); try { Reply r = new Reply(new BufferedReader(new StringReader(uReplyString))); } catch (Exception e) { fail("Exception thrown: " + e.toString()); } } private static void arrowQuote(String desc, String content) { //System.out.println(desc + " ->" + content + "<-\n"); } private static void arrowQuote(String desc, int content) { //System.out.println(desc + " ->" + content + "<-\n"); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/SimpleTarTransfer.java000066400000000000000000000060411241116057200322300ustar00rootroot00000000000000package org.globus.ftp.test; import org.globus.ftp.GridFTPClient; import org.globus.ftp.Session; import org.globus.gsi.gssapi.auth.IdentityAuthorization; import org.globus.util.ConfigUtil; import org.gridforum.jgss.ExtendedGSSCredential; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class SimpleTarTransfer { public static void main(String[] args) throws Exception { String tarAlias = "tar"; String host = "localhost";//args[0]; int port = 60000;//new Integer(args[1]).intValue(); String sourceParentDir = "/tmp";// args[2]; String sourceDir = "tartest";//args[3]; String destFile = "/tmp/target.tar"; GSSCredential cred = getDefaultCredential(); String tarCommand = createDownloadTarSiteCommand(sourceParentDir, sourceDir, tarAlias); GridFTPClient client = createClient(host, port, cred, tarCommand); downloadTarToFile(client, sourceDir, destFile); } static GridFTPClient createClient(String host, int port, GSSCredential cred, String tarCommand) throws Exception { GridFTPClient client = null; client = new GridFTPClient(host, port); client.setAuthorization(new IdentityAuthorization("/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand")); client.authenticate(cred); client.setType(Session.TYPE_IMAGE); try { client.site(tarCommand); } catch (Exception e) { throw new Exception("popen driver not supported", e); } client.setPassive(); client.setLocalActive(); return client; } static String createDownloadTarSiteCommand(String sourceParentDir, String sourceDir, String tarAlias) { StringBuffer sb = new StringBuffer(); sb.append("SETDISKSTACK popen:argv=#"); sb.append(tarAlias); sb.append("#cf#-#-C#"); sb.append(sourceParentDir); sb.append("#"); sb.append(sourceDir); return sb.toString(); } static void downloadTarToFile(GridFTPClient client, String sourceDir, String destFile) throws Exception { try { client.get(sourceDir, new File(destFile)); } finally { if (client != null) { client.close(true); } } } static GSSCredential getDefaultCredential() throws IOException, GSSException { File proxyFile = new File(ConfigUtil.discoverProxyLocation()); byte[] proxyBytes = new byte[(int) proxyFile.length()]; FileInputStream in = new FileInputStream(proxyFile); try { in.read(proxyBytes); } finally { in.close(); } ExtendedGSSManager manager = (ExtendedGSSManager) ExtendedGSSManager.getInstance(); return manager.createCredential(proxyBytes, ExtendedGSSCredential.IMPEXP_OPAQUE, GSSCredential.DEFAULT_LIFETIME, null, GSSCredential.INITIATE_AND_ACCEPT); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/TestEnv.java000066400000000000000000000246521241116057200302230ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Properties; import java.io.IOException; import java.io.InputStream; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.HostAuthorization; import org.globus.gsi.gssapi.auth.IdentityAuthorization; /** Utility for tests. This class has two functions. First, it holds in public variables the test properties. Second, it supplies simplified syntax for setting the values for class loggers. **/ public class TestEnv { /** This logger can be used anywhere in the application. **/ public static Log logger = LogFactory.getLog(TestEnv.class.getName()); public static final int UNDEFINED = -1; // local destination directory public static String localDestDir; // local source file (full name) public static String localSrcDir; public static String localSrcFile; public static int localServerPort; //GridFTP server (source) public static String serverAHost; public static int serverAPort; public static String serverASubject; public static String serverADir; public static String serverAFile; public static int serverAFileSize; public static String serverAFileChecksum; public static String serverALargeFile; public static String serverASmallFile; public static String serverANoSuchFile; public static int serverANoSuchPort; //GridFTP server (dest) public static String serverBHost; public static int serverBPort; public static String serverBSubject; public static String serverBDir; public static String serverBFile; public static String serverBNoSuchDir; //non existent server public static String noSuchServer; //FTP server (src) public static String serverFHost; public static int serverFPort; public static String serverFDir; public static String serverFFile; public static int serverFFileSize; public static String serverFUser; public static String serverFPassword; public static String serverFNoSuchFile; public static int serverFNoSuchPort; //FTP server (dest) (optional) // if not supplied in test properties, these variables will be null public static String serverGHost = null; public static int serverGPort = UNDEFINED; public static String serverGDir = null; public static String serverGFile = null; public static String serverGUser = null; public static String serverGPassword = null; public static String serverGNoSuchDir; public static int parallelism; //local file separator public static String fileSeparator; //new line public static String nl; public static boolean failUnset = false; public static final String CONFIG = "./test.properties"; static { InputStream in = null; try { Thread t = Thread.currentThread(); in = t.getContextClassLoader().getResourceAsStream(CONFIG); if (in == null) { throw new IOException("Test configuration file not found: " + CONFIG); } Properties props = new Properties(); props.load(in); String prefix = "org.globus.ftp.test."; // general fileSeparator = System.getProperty("file.separator"); nl = System.getProperty("line.separator"); noSuchServer = props.getProperty(prefix + "noSuchServer.host"); parallelism = toInt( props.getProperty(prefix + "gridftp.parallelism") ); // local localDestDir = props.getProperty(prefix + "local.destDir"); localSrcFile = props.getProperty(prefix + "local.srcFile"); localSrcDir = props.getProperty(prefix + "local.srcDir"); // local server port String lssStr = props.getProperty(prefix + "local.serverPort"); localServerPort = toIntOptional(lssStr); //server A serverAHost = props.getProperty(prefix + "gridftp.serverA.host"); serverAPort = toInt( props.getProperty(prefix + "gridftp.serverA.port") ); serverASubject = props.getProperty(prefix + "gridftp.serverA.subject"); serverADir = props.getProperty(prefix + "gridftp.serverA.dir"); serverAFile = props.getProperty(prefix + "gridftp.serverA.file"); serverAFileSize = toInt( props.getProperty(prefix + "gridftp.serverA.file.size") ); serverAFileChecksum = props.getProperty(prefix + "gridftp.serverA.file.checksum"); serverASmallFile = props.getProperty(prefix + "gridftp.serverA.smallFile"); serverALargeFile = props.getProperty(prefix + "gridftp.serverA.largeFile"); serverANoSuchFile = props.getProperty(prefix + "gridftp.serverA.nosuchfile"); //defining non existent port: //user is allowed not to define it String noSuchPort_str = props.getProperty(prefix + "gridftp.serverA.noSuchPort"); serverANoSuchPort = toIntOptional(noSuchPort_str); // server B serverBHost = props.getProperty(prefix + "gridftp.serverB.host"); serverBPort = toInt( props.getProperty(prefix + "gridftp.serverB.port") ); serverBSubject = props.getProperty(prefix + "gridftp.serverB.subject"); serverBDir = props.getProperty(prefix + "gridftp.serverB.dir"); serverBFile = props.getProperty(prefix + "gridftp.serverB.file"); serverBNoSuchDir = props.getProperty(prefix + "gridftp.serverB.nosuchdir"); // FTP server F (src) serverFHost = props.getProperty(prefix + "serverF.host"); serverFPort = toInt( props.getProperty(prefix + "serverF.port") ); serverFDir = props.getProperty(prefix + "serverF.dir"); serverFFile = props.getProperty(prefix + "serverF.file"); serverFFileSize = toInt( props.getProperty(prefix + "serverF.file.size")); serverFNoSuchFile = props.getProperty(prefix + "serverF.nosuchfile"); serverFUser = props.getProperty(prefix + "serverF.user"); serverFPassword = props.getProperty(prefix + "serverF.password"); //defining non existent port: //user is allowed not to define it String fNoSuchPort_str = props.getProperty(prefix + "gridftp.serverF.noSuchPort"); serverFNoSuchPort = toIntOptional(fNoSuchPort_str); // FTP server G (dest) (optional) serverGHost = props.getProperty(prefix + "serverG.host"); if (serverGHost.equals("")) { serverGHost = null; } else { String portStr = props.getProperty(prefix + "serverG.port"); serverGPort = toInt(portStr); serverGDir = props.getProperty(prefix + "serverG.dir"); serverGFile = props.getProperty(prefix + "serverG.file"); serverGNoSuchDir = props.getProperty(prefix + "serverG.nosuchdir"); serverGUser = props.getProperty(prefix + "serverG.user"); serverGPassword = props.getProperty(prefix + "serverG.password"); } //logger.debug(show()); } catch (Exception e) { if (e instanceof NumberFormatException) { logger.info("Error: Badly formatted numbers in properties file."); } logger.info("stack trace:\n"); e.printStackTrace(); TestCase.fail(e.toString()); } finally { if (in != null) { try { in.close(); } catch(Exception ee) {} } } } /** @return human readable description of current test environment. **/ static String show() { String desc = "Test Environment" + nl + "================" + nl + "parallelism = " + parallelism + nl + "noSuchServer: " + noSuchServer + nl + nl + "local dest dir = " + localDestDir + nl + "local src dir = " + localSrcDir + nl + "local src file = " + localSrcFile + nl + "local server port = " + localServerPort + nl + "================" + nl + "GridFTP source server: " + nl + "serverAHost = " + serverAHost + nl + "serverAPort = " + serverAPort + nl + "serverADir = " + serverADir + nl + "serverAFile = " + serverAFile + nl + "serverALargeFile = " + serverALargeFile + nl + "serverANoSuchFile = " + serverANoSuchFile + nl + "serverANoSuchPort = " + ((serverANoSuchPort == UNDEFINED) ? "UNDEFINED" : Integer.toString(serverANoSuchPort) ) + nl + nl + "GridFTP dest server: " + nl + "serverBHost = " + serverBHost + nl + "serverBPort = " + serverBPort + nl + "serverBDir = " + serverBDir + nl + "serverBFile = " + serverBFile + nl + "ServerBNoSuchDir = " + serverBNoSuchDir + nl + nl + "FTP source server: " + nl + "serverFHost = " + serverFHost + nl + "serverFPort = " + serverFPort + nl + "serverFDir = " + serverFDir + nl + "serverFFile = " + serverFFile + nl + "serverFFileSize = " + serverFFileSize + nl + "serverFUser = " + serverFUser + nl + "serverFPassword = " + serverFPassword + nl + "serverFNoSuchFile = " + serverFNoSuchFile + nl + "serverFNoSuchPort = " + serverFNoSuchPort + nl ; if (serverGHost != null) { desc += nl + "FTP dest server: " + nl + "serverGHost = " + serverGHost + nl + "serverGPort = " + serverGPort + nl + "serverGDir = " + serverGDir + nl + "serverGFile = " + serverGFile + nl + "serverGUser = " + serverGUser + nl + "serverGPassword = " + serverGPassword + nl; } else { desc += nl + "FTP dest server: UNDEFINED"; } return desc; } // convert to integer // an optional argument private static int toIntOptional(String str) throws NumberFormatException { return (str == null || str.equals("")) ? UNDEFINED : toInt(str); } private static int toInt(String str) throws NumberFormatException{ try { return Integer.parseInt(str); } catch (NumberFormatException e) { logger.error("This is not an integer: " + str); throw e; } } public static Authorization getAuthorization(String subject) { if (subject == null) { return HostAuthorization.getInstance(); } else { return new IdentityAuthorization(subject); } } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/java/org/globus/ftp/test/TransferAppTest.java000066400000000000000000000136361241116057200317200ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.ftp.test; import org.globus.ftp.GridFTPSession; import org.globus.ftp.Session; import org.globus.ftp.app.Transfer; import org.globus.ftp.app.TransferParams; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /* Tests for app.Transfer class. they only tell if transfer succeeds or fails. To really know if the commands are being sent correctly, enable control channel debugging and monitor commands being sent: LogFactory.getLog(org.globus.ftp.vanilla.FTPControlChannel.class.getName()).setLevel(Level.INFO); */ public class TransferAppTest extends TestCase { private static Log logger = LogFactory.getLog(TransferAppTest.class.getName()); public static void main(String[] args) throws Exception { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TransferAppTest.class); } public TransferAppTest(String name) { super(name); } public void testDefault() throws Exception{ logger.debug("default parameters"); testA2B(new TransferParams()); } public void testStreamImage() throws Exception{ logger.debug("transfer mode = STREAM, transfer type = IMAGE"); TransferParams params = new TransferParams(); params.transferMode = Session.MODE_STREAM; params.transferType = Session.TYPE_IMAGE; testA2B(params); } public void testStreamAscii() throws Exception{ logger.debug("transfer mode = STREAM, transfer type = ASCII"); TransferParams params = new TransferParams(); params.transferMode = Session.MODE_STREAM; params.transferType = Session.TYPE_ASCII; testA2B(params); } public void testStreamAsciiPasv() throws Exception{ logger.debug("transfer mode = STREAM, sender passive"); TransferParams params = new TransferParams(); params.transferMode = Session.MODE_STREAM; params.serverMode = Session.SERVER_PASSIVE; testA2B(params); } public void testParallel5() throws Exception{ logger.debug("parallelism = 5"); TransferParams params = new TransferParams(); params.parallel = 5; testA2B(params); } public void testParallel3Strip() throws Exception{ logger.debug("parallelism = 3, striping"); TransferParams params = new TransferParams(); params.parallel = 3; params.doStriping = true; testA2B(params); } public void testParallel5Pasv() throws Exception{ logger.debug("parallelism = 5, sender passive (should fail)"); TransferParams params = new TransferParams(); params.parallel = 5; params.serverMode = Session.SERVER_PASSIVE; // this will fail; in mode E sender cannot be passive testFailA2B(params); } public void testParallel3StripPasv() throws Exception{ logger.debug("parallelism = 3, striping, sender passive (should fail)"); TransferParams params = new TransferParams(); params.parallel = 3; params.doStriping = true; params.serverMode = Session.SERVER_PASSIVE; // this will fail; in mode E sender cannot be passive testFailA2B(params); } public void testPBSZ() throws Exception{ logger.debug("protection buffer size = 10000"); TransferParams params = new TransferParams(); params.protectionBufferSize = 10000; testA2B(params); } public void testAuthNone() throws Exception{ logger.debug("data channel auth = none"); TransferParams params = new TransferParams(); params.dataChannelAuthentication = org.globus.ftp.DataChannelAuthentication.NONE; testA2B(params); } public void testAuthSelf() throws Exception{ logger.debug("data channel auth = self"); TransferParams params = new TransferParams(); params.dataChannelAuthentication = org.globus.ftp.DataChannelAuthentication.SELF; testA2B(params); } public void testProtClear() throws Exception{ logger.debug("data channel protection = clear"); TransferParams params = new TransferParams(); params.dataChannelProtection = GridFTPSession.PROTECTION_CLEAR; testA2B(params); } public void testProtPrivate() throws Exception{ logger.debug("data channel protection = private"); TransferParams params = new TransferParams(); params.dataChannelProtection = GridFTPSession.PROTECTION_PRIVATE; testA2B(params); } public void testTCPBufferSmall() throws Exception{ logger.debug("TCPBufferSize = 12345"); TransferParams params = new TransferParams(); params.TCPBufferSize = 12345; testA2B(params); } public void testTCPBufferLarge() throws Exception{ logger.debug("TCPBufferSize = 100000"); TransferParams params = new TransferParams(); params.TCPBufferSize = 100000; testA2B(params); } /** Test transfer from server A to server B */ private void testA2B(TransferParams myParams) throws Exception { Transfer transfer = new Transfer( //source TestEnv.serverAHost, TestEnv.serverAPort, TestEnv.serverASubject, TestEnv.serverADir, TestEnv.serverAFile, //dest TestEnv.serverBHost, TestEnv.serverBPort, TestEnv.serverBSubject, TestEnv.serverBDir, TestEnv.serverBFile, //params myParams); } /** Test transfer from server A to server B which is expected to fail */ private void testFailA2B(TransferParams myParams) { boolean failed = false; try { testA2B(myParams); } catch (Exception e) { failed = true; } assertTrue(failed == true); } } JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/resources/000077500000000000000000000000001241116057200232165ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/resources/org/000077500000000000000000000000001241116057200240055ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/resources/org/globus/000077500000000000000000000000001241116057200253005ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/resources/org/globus/ftp/000077500000000000000000000000001241116057200260715ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/resources/org/globus/ftp/test/000077500000000000000000000000001241116057200270505ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/resources/org/globus/ftp/test/test.properties000066400000000000000000000113561241116057200321530ustar00rootroot00000000000000org.globus.ftp.test.local.destDir=/tmp/tmp.Ghj3abEPzh org.globus.ftp.test.local.srcDir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.local.srcFile=jglobusTest org.globus.ftp.test.local.serverPort=50505 # serverA props org.globus.ftp.test.gridftp.serverA.host=localhost org.globus.ftp.test.gridftp.serverA.port=50505 org.globus.ftp.test.gridftp.serverA.noSuchPort=5680 org.globus.ftp.test.gridftp.serverA.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.gridftp.serverA.smallFile=jglobusSmall org.globus.ftp.test.gridftp.serverA.largeFile=jglobusBig org.globus.ftp.test.gridftp.serverA.file=jglobusTestA org.globus.ftp.test.gridftp.serverA.file.size=2252470 org.globus.ftp.test.gridftp.serverA.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand org.globus.ftp.test.gridftp.serverA.file.checksum=da319627377745e4da0f25fe2a8931d6 org.globus.ftp.test.gridftp.serverA.nosuchfile=nosuchfile org.globus.ftp.test.serverA.host=localhost org.globus.ftp.test.serverA.port=6666 org.globus.ftp.test.serverA.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.serverA.file=jglobusTestA org.globus.ftp.test.serverA.user=anonymous org.globus.ftp.test.serverA.password=poop org.globus.ftp.test.serverA.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand org.globus.ftp.test.serverA.file.size=2569 org.globus.ftp.test.serverA.nosuchdir=nosuchdir # serverB props org.globus.ftp.test.gridftp.serverB.host=localhost org.globus.ftp.test.gridftp.serverB.port=50500 org.globus.ftp.test.gridftp.serverB.noSuchPort=5680 org.globus.ftp.test.gridftp.serverB.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.gridftp.serverB.smallFile=jglobusSmall org.globus.ftp.test.gridftp.serverB.largeFile=jglobusBig org.globus.ftp.test.gridftp.serverB.file=jglobusTestB org.globus.ftp.test.gridftp.serverB.file.size=702306 org.globus.ftp.test.gridftp.serverB.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand org.globus.ftp.test.gridftp.serverB.file.checksum=c1489ac529f8b4e5a767cd83b1cd7246 org.globus.ftp.test.gridftp.serverB.nosuchfile=nosuchfile org.globus.ftp.test.serverB.host=localhost org.globus.ftp.test.serverB.port=7777 org.globus.ftp.test.serverB.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.serverB.file=jglobusTestB org.globus.ftp.test.serverB.user=anonymous org.globus.ftp.test.serverB.password=poop org.globus.ftp.test.serverB.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand org.globus.ftp.test.serverB.file.size=2569 org.globus.ftp.test.serverB.nosuchdir=nosuchdir # serverF props org.globus.ftp.test.gridftp.serverF.host=localhost org.globus.ftp.test.gridftp.serverF.port=8888 org.globus.ftp.test.gridftp.serverF.noSuchPort=5680 org.globus.ftp.test.gridftp.serverF.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.gridftp.serverF.smallFile=jglobusSmall org.globus.ftp.test.gridftp.serverF.largeFile=jglobusBig org.globus.ftp.test.gridftp.serverF.file=jglobusTestF org.globus.ftp.test.gridftp.serverF.file.size=79139 org.globus.ftp.test.gridftp.serverF.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand org.globus.ftp.test.gridftp.serverF.file.checksum=2ba0ee76b5cf79e6001dd24f396d850a org.globus.ftp.test.gridftp.serverF.nosuchfile=nosuchfile org.globus.ftp.test.serverF.host=localhost org.globus.ftp.test.serverF.port=8888 org.globus.ftp.test.serverF.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.serverF.file=jglobusTestF org.globus.ftp.test.serverF.user=anonymous org.globus.ftp.test.serverF.password=poop org.globus.ftp.test.serverF.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand org.globus.ftp.test.serverF.file.size=79139 org.globus.ftp.test.serverF.nosuchdir=nosuchdir # serverG props org.globus.ftp.test.gridftp.serverG.host=localhost org.globus.ftp.test.gridftp.serverG.port=9999 org.globus.ftp.test.gridftp.serverG.noSuchPort=5680 org.globus.ftp.test.gridftp.serverG.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.gridftp.serverG.smallFile=jglobusSmall org.globus.ftp.test.gridftp.serverG.largeFile=jglobusBig org.globus.ftp.test.gridftp.serverG.file=jglobusTestG org.globus.ftp.test.gridftp.serverG.file.size=2569 org.globus.ftp.test.gridftp.serverG.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand org.globus.ftp.test.gridftp.serverG.file.checksum=d7cb26272d95a4586e1d2cde83789d98 org.globus.ftp.test.gridftp.serverG.nosuchfile=nosuchfile org.globus.ftp.test.serverG.host=localhost org.globus.ftp.test.serverG.port=9999 org.globus.ftp.test.serverG.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.serverG.file=jglobusTestG org.globus.ftp.test.serverG.user=anonymous org.globus.ftp.test.serverG.password=poop org.globus.ftp.test.serverG.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand org.globus.ftp.test.serverG.file.size=2569 org.globus.ftp.test.serverG.nosuchdir=nosuchdir org.globus.ftp.test.noSuchServer.host=no.such.server org.globus.ftp.test.gridftp.parallelism=6 JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/resources/org/globus/ftp/test/test.properties.in000066400000000000000000000105061241116057200325540ustar00rootroot00000000000000org.globus.ftp.test.local.destDir=@@DST_DIR@@ org.globus.ftp.test.local.srcDir=@@SRC_DIR@@ org.globus.ftp.test.local.srcFile=@@SRC_FILE@@ org.globus.ftp.test.local.serverPort=@@PORTA@@ # serverA props org.globus.ftp.test.gridftp.serverA.host=@@HOST@@ org.globus.ftp.test.gridftp.serverA.port=@@PORTA@@ org.globus.ftp.test.gridftp.serverA.noSuchPort=5680 org.globus.ftp.test.gridftp.serverA.dir=@@SRC_DIR@@ org.globus.ftp.test.gridftp.serverA.smallFile=@@SMALL_FILE@@ org.globus.ftp.test.gridftp.serverA.largeFile=@@LARGE_FILE@@ org.globus.ftp.test.gridftp.serverA.file=@@SRC_FILEA@@ org.globus.ftp.test.gridftp.serverA.file.size=@@SIZE@@ org.globus.ftp.test.gridftp.serverA.subject=@@SUBJECT@@ org.globus.ftp.test.gridftp.serverA.file.checksum=@@MD5SUMA@@ org.globus.ftp.test.gridftp.serverA.nosuchfile=nosuchfile org.globus.ftp.test.serverA.host=@@HOST@@ org.globus.ftp.test.serverA.port=@@PORTA@@ org.globus.ftp.test.serverA.dir=@@SRC_DIR@@ org.globus.ftp.test.serverA.file=@@SRC_FILEA@@ org.globus.ftp.test.serverA.user=anonymous org.globus.ftp.test.serverA.password=poop org.globus.ftp.test.serverA.subject=@@SUBJECT@@ org.globus.ftp.test.serverA.file.size=@@SIZE@@ org.globus.ftp.test.serverA.nosuchdir=nosuchdir # serverB props org.globus.ftp.test.gridftp.serverB.host=@@HOST@@ org.globus.ftp.test.gridftp.serverB.port=@@PORTB@@ org.globus.ftp.test.gridftp.serverB.noSuchPort=5680 org.globus.ftp.test.gridftp.serverB.dir=@@SRC_DIR@@ org.globus.ftp.test.gridftp.serverB.smallFile=@@SMALL_FILE@@ org.globus.ftp.test.gridftp.serverB.largeFile=@@LARGE_FILE@@ org.globus.ftp.test.gridftp.serverB.file=@@SRC_FILEB@@ org.globus.ftp.test.gridftp.serverB.file.size=@@SIZE@@ org.globus.ftp.test.gridftp.serverB.subject=@@SUBJECT@@ org.globus.ftp.test.gridftp.serverB.file.checksum=@@MD5SUMB@@ org.globus.ftp.test.gridftp.serverB.nosuchfile=nosuchfile org.globus.ftp.test.serverB.host=@@HOST@@ org.globus.ftp.test.serverB.port=@@PORTB@@ org.globus.ftp.test.serverB.dir=@@SRC_DIR@@ org.globus.ftp.test.serverB.file=@@SRC_FILEB@@ org.globus.ftp.test.serverB.user=anonymous org.globus.ftp.test.serverB.password=poop org.globus.ftp.test.serverB.subject=@@SUBJECT@@ org.globus.ftp.test.serverB.file.size=@@SIZE@@ org.globus.ftp.test.serverB.nosuchdir=nosuchdir # serverF props org.globus.ftp.test.gridftp.serverF.host=@@HOST@@ org.globus.ftp.test.gridftp.serverF.port=@@PORTF@@ org.globus.ftp.test.gridftp.serverF.noSuchPort=5680 org.globus.ftp.test.gridftp.serverF.dir=@@SRC_DIR@@ org.globus.ftp.test.gridftp.serverF.smallFile=@@SMALL_FILE@@ org.globus.ftp.test.gridftp.serverF.largeFile=@@LARGE_FILE@@ org.globus.ftp.test.gridftp.serverF.file=@@SRC_FILEF@@ org.globus.ftp.test.gridftp.serverF.file.size=@@SIZE@@ org.globus.ftp.test.gridftp.serverF.subject=@@SUBJECT@@ org.globus.ftp.test.gridftp.serverF.file.checksum=@@MD5SUMF@@ org.globus.ftp.test.gridftp.serverF.nosuchfile=nosuchfile org.globus.ftp.test.serverF.host=@@HOST@@ org.globus.ftp.test.serverF.port=@@PORTF@@ org.globus.ftp.test.serverF.dir=@@SRC_DIR@@ org.globus.ftp.test.serverF.file=@@SRC_FILEF@@ org.globus.ftp.test.serverF.user=anonymous org.globus.ftp.test.serverF.password=poop org.globus.ftp.test.serverF.subject=@@SUBJECT@@ org.globus.ftp.test.serverF.file.size=@@SIZE@@ org.globus.ftp.test.serverF.nosuchdir=nosuchdir # serverG props org.globus.ftp.test.gridftp.serverG.host=@@HOST@@ org.globus.ftp.test.gridftp.serverG.port=@@PORTG@@ org.globus.ftp.test.gridftp.serverG.noSuchPort=5680 org.globus.ftp.test.gridftp.serverG.dir=@@SRC_DIR@@ org.globus.ftp.test.gridftp.serverG.smallFile=@@SMALL_FILE@@ org.globus.ftp.test.gridftp.serverG.largeFile=@@LARGE_FILE@@ org.globus.ftp.test.gridftp.serverG.file=@@SRC_FILEG@@ org.globus.ftp.test.gridftp.serverG.file.size=@@SIZE@@ org.globus.ftp.test.gridftp.serverG.subject=@@SUBJECT@@ org.globus.ftp.test.gridftp.serverG.file.checksum=@@MD5SUMG@@ org.globus.ftp.test.gridftp.serverG.nosuchfile=nosuchfile org.globus.ftp.test.serverG.host=@@HOST@@ org.globus.ftp.test.serverG.port=@@PORTG@@ org.globus.ftp.test.serverG.dir=@@SRC_DIR@@ org.globus.ftp.test.serverG.file=@@SRC_FILEG@@ org.globus.ftp.test.serverG.user=anonymous org.globus.ftp.test.serverG.password=poop org.globus.ftp.test.serverG.subject=@@SUBJECT@@ org.globus.ftp.test.serverG.file.size=@@SIZE@@ org.globus.ftp.test.serverG.nosuchdir=nosuchdir org.globus.ftp.test.noSuchServer.host=no.such.server org.globus.ftp.test.gridftp.parallelism=6 JGlobus-JGlobus-Release-2.1.0/gridftp/src/test/resources/test.properties000066400000000000000000000112461241116057200263170ustar00rootroot00000000000000org.globus.ftp.test.local.destDir=/tmp/tmp.Ghj3abEPzh org.globus.ftp.test.local.srcDir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.local.srcFile=jglobusTest org.globus.ftp.test.local.serverPort=50505 # serverA props org.globus.ftp.test.gridftp.serverA.host=localhost org.globus.ftp.test.gridftp.serverA.port=50505 org.globus.ftp.test.gridftp.serverA.noSuchPort=5680 org.globus.ftp.test.gridftp.serverA.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.gridftp.serverA.smallFile=jglobusSmall org.globus.ftp.test.gridftp.serverA.largeFile=jglobusBig org.globus.ftp.test.gridftp.serverA.file=jglobusTestA org.globus.ftp.test.gridftp.serverA.file.size=2252470 org.globus.ftp.test.gridftp.serverA.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=vg org.globus.ftp.test.gridftp.serverA.file.checksum=da319627377745e4da0f25fe2a8931d6 org.globus.ftp.test.gridftp.serverA.nosuchfile=nosuchfile org.globus.ftp.test.serverA.host=localhost org.globus.ftp.test.serverA.port=6666 org.globus.ftp.test.serverA.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.serverA.file=jglobusTestA org.globus.ftp.test.serverA.user=anonymous org.globus.ftp.test.serverA.password=poop org.globus.ftp.test.serverA.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=vg org.globus.ftp.test.serverA.file.size=2569 org.globus.ftp.test.serverA.nosuchdir=nosuchdir # serverB props org.globus.ftp.test.gridftp.serverB.host=localhost org.globus.ftp.test.gridftp.serverB.port=50500 org.globus.ftp.test.gridftp.serverB.noSuchPort=5680 org.globus.ftp.test.gridftp.serverB.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.gridftp.serverB.smallFile=jglobusSmall org.globus.ftp.test.gridftp.serverB.largeFile=jglobusBig org.globus.ftp.test.gridftp.serverB.file=jglobusTestB org.globus.ftp.test.gridftp.serverB.file.size=702306 org.globus.ftp.test.gridftp.serverB.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=vg org.globus.ftp.test.gridftp.serverB.file.checksum=c1489ac529f8b4e5a767cd83b1cd7246 org.globus.ftp.test.gridftp.serverB.nosuchfile=nosuchfile org.globus.ftp.test.serverB.host=localhost org.globus.ftp.test.serverB.port=7777 org.globus.ftp.test.serverB.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.serverB.file=jglobusTestB org.globus.ftp.test.serverB.user=anonymous org.globus.ftp.test.serverB.password=poop org.globus.ftp.test.serverB.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=vg org.globus.ftp.test.serverB.file.size=2569 org.globus.ftp.test.serverB.nosuchdir=nosuchdir # serverF props org.globus.ftp.test.gridftp.serverF.host=localhost org.globus.ftp.test.gridftp.serverF.port=8888 org.globus.ftp.test.gridftp.serverF.noSuchPort=5680 org.globus.ftp.test.gridftp.serverF.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.gridftp.serverF.smallFile=jglobusSmall org.globus.ftp.test.gridftp.serverF.largeFile=jglobusBig org.globus.ftp.test.gridftp.serverF.file=jglobusTestF org.globus.ftp.test.gridftp.serverF.file.size=79139 org.globus.ftp.test.gridftp.serverF.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=vg org.globus.ftp.test.gridftp.serverF.file.checksum=2ba0ee76b5cf79e6001dd24f396d850a org.globus.ftp.test.gridftp.serverF.nosuchfile=nosuchfile org.globus.ftp.test.serverF.host=localhost org.globus.ftp.test.serverF.port=8888 org.globus.ftp.test.serverF.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.serverF.file=jglobusTestF org.globus.ftp.test.serverF.user=anonymous org.globus.ftp.test.serverF.password=poop org.globus.ftp.test.serverF.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=vg org.globus.ftp.test.serverF.file.size=79139 org.globus.ftp.test.serverF.nosuchdir=nosuchdir # serverG props org.globus.ftp.test.gridftp.serverG.host=localhost org.globus.ftp.test.gridftp.serverG.port=9999 org.globus.ftp.test.gridftp.serverG.noSuchPort=5680 org.globus.ftp.test.gridftp.serverG.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.gridftp.serverG.smallFile=jglobusSmall org.globus.ftp.test.gridftp.serverG.largeFile=jglobusBig org.globus.ftp.test.gridftp.serverG.file=jglobusTestG org.globus.ftp.test.gridftp.serverG.file.size=2569 org.globus.ftp.test.gridftp.serverG.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=vg org.globus.ftp.test.gridftp.serverG.file.checksum=d7cb26272d95a4586e1d2cde83789d98 org.globus.ftp.test.gridftp.serverG.nosuchfile=nosuchfile org.globus.ftp.test.serverG.host=localhost org.globus.ftp.test.serverG.port=9999 org.globus.ftp.test.serverG.dir=/tmp/tmp.Qx3mIuEb2R org.globus.ftp.test.serverG.file=jglobusTestG org.globus.ftp.test.serverG.user=anonymous org.globus.ftp.test.serverG.password=poop org.globus.ftp.test.serverG.subject=/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=vg org.globus.ftp.test.serverG.file.size=2569 org.globus.ftp.test.serverG.nosuchdir=nosuchdir org.globus.ftp.test.noSuchServer.host=no.such.server org.globus.ftp.test.gridftp.parallelism=6 JGlobus-JGlobus-Release-2.1.0/gridftp/test_output.txt000066400000000000000000003675021241116057200226130ustar00rootroot00000000000000[INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building gridftp [INFO] task-segment: [test] [INFO] ------------------------------------------------------------------------ [INFO] [resources:resources {execution: default-resources}] [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory /home/vg/Desktop/JGlobus/JGlobus/gridftp/src/main/resources [INFO] [compiler:compile {execution: default-compile}] [INFO] Nothing to compile - all classes are up to date [INFO] [resources:testResources {execution: default-testResources}] [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 1 resource [INFO] [compiler:testCompile {execution: default-testCompile}] [INFO] Nothing to compile - all classes are up to date [INFO] [surefire:test {execution: default-test}] [INFO] Surefire report directory: /home/vg/Desktop/JGlobus/JGlobus/gridftp/target/surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running org.globus.ftp.test.TransferAppTest Tests run: 15, Failures: 0, Errors: 13, Skipped: 0, Time elapsed: 1.145 sec <<< FAILURE! Running org.globus.ftp.test.DataChannelReuseTest [main] INFO test.DataChannelReuseTest - basic data channel reuse [main] INFO test.DataChannelReuseTest - basic data channel reuse with put [main] INFO test.DataChannelReuseTest - data channel reuse with changing d.c. protection [main] INFO test.DataChannelReuseTest - data channel reuse with put and protection [main] INFO test.DataChannelReuseTest - data channel reuse with changing TCP buffer size [main] INFO test.DataChannelReuseTest - data channel reuse with put and changing tcp buffer [main] INFO test.DataChannelReuseTest - data channel reuse interspersed by setActive/passive [main] INFO test.DataChannelReuseTest - data channel reuse with put and interspersed setActive/passive Tests run: 8, Failures: 0, Errors: 8, Skipped: 0, Time elapsed: 0.337 sec <<< FAILURE! Running org.globus.ftp.test.FTPControlChannelTest [main] INFO test.FTPControlChannelTest - USER/PASS [main] INFO test.FTPControlChannelTest - RETR Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.079 sec Running org.globus.ftp.test.GridFTPRestartMarkerTest [main] INFO test.GridFTPRestartMarkerTest - constructing bad: 111 Range Marker 0-29 [main] INFO test.GridFTPRestartMarkerTest - constructing bad: 129-Perf Marker [main] INFO test.GridFTPRestartMarkerTest - constructing bad: Range Marker 30-45,30-20,50-51 [main] INFO test.GridFTPRestartMarkerTest - constructing bad: Range Marker 30-45,46-2e [main] INFO test.GridFTPRestartMarkerTest - constructing bad: Range Marker -3,70-82 [main] INFO test.GridFTPRestartMarkerTest - constructing bad: Range Marker 30-4570-82 [main] INFO test.GridFTPRestartMarkerTest - constructing: 30-66 -> 30-66 [main] INFO test.GridFTPRestartMarkerTest - constructing: 30-45,60-71,100-134 -> 30-45,60-71,100-134 [main] INFO test.GridFTPRestartMarkerTest - constructing: 0-17,18-50,51-114 -> 0-114 [main] INFO test.GridFTPRestartMarkerTest - constructing: 51-114,18-49,0-16 -> 0-16,18-49,51-114 [main] INFO test.GridFTPRestartMarkerTest - constructing: 44-99,1-5,30-37,0-36 -> 0-37,44-99 [main] INFO test.GridFTPRestartMarkerTest - constructing: 0-134545408 -> 0-134545408 [main] INFO test.GridFTPRestartMarkerTest - constructing: 134545408-298778624 -> 134545408-298778624 [main] INFO test.GridFTPRestartMarkerTest - constructing: 298778624-466747392 -> 298778624-466747392 Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.017 sec Running org.globus.ftp.test.GridFTPClientTest [main] INFO test.GridFTPClientTest - getSize() [main] INFO test.GridFTPClientTest - makeDir() [main] INFO test.GridFTPClientTest - setRestartMarker() [main] INFO test.GridFTPClientTest - 3 party [main] ERROR test.GridFTPClientTest - java.net.SocketException: Socket closed at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99) at java.net.SocketOutputStream.write(SocketOutputStream.java:124) at org.globus.ftp.vanilla.FTPControlChannel.writeStr(FTPControlChannel.java:472) at org.globus.ftp.vanilla.FTPControlChannel.write(FTPControlChannel.java:415) at org.globus.ftp.FTPClient.close(FTPClient.java:946) at org.globus.ftp.test.GridFTPClientTest.test3Party(GridFTPClientTest.java:796) at org.globus.ftp.test.GridFTPClientTest.test3Party(GridFTPClientTest.java:529) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] ERROR test.GridFTPClientTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.GridFTPClientTest.test3Party_setParams(GridFTPClientTest.java:813) at org.globus.ftp.test.GridFTPClientTest.test3Party(GridFTPClientTest.java:789) at org.globus.ftp.test.GridFTPClientTest.test3Party(GridFTPClientTest.java:529) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClientTest - getFeatureList() [main] INFO test.GridFTPClientTest - retrieveOptions() [main] INFO test.GridFTPClientTest - show list output using GridFTPClient [main] INFO test.GridFTPClientTest - show list output using GridFTPClient [main] INFO test.GridFTPClientTest - show list output using GridFTPClient [main] INFO test.GridFTPClientTest - show list output using GridFTPClient [main] INFO test.GridFTPClientTest - show list output using GridFTPClient [main] INFO test.GridFTPClientTest - show list output using GridFTPClient [main] INFO test.GridFTPClientTest - test two consective list, using both list functions, using GridFTPClient [main] INFO test.GridFTPClientTest - 3 party mode E [main] ERROR test.GridFTPClientTest - java.net.SocketException: Socket closed at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99) at java.net.SocketOutputStream.write(SocketOutputStream.java:124) at org.globus.ftp.vanilla.FTPControlChannel.writeStr(FTPControlChannel.java:472) at org.globus.ftp.vanilla.FTPControlChannel.write(FTPControlChannel.java:415) at org.globus.ftp.FTPClient.close(FTPClient.java:946) at org.globus.ftp.test.GridFTPClientTest.test3PartyModeE(GridFTPClientTest.java:850) at org.globus.ftp.test.GridFTPClientTest.test3PartyModeE(GridFTPClientTest.java:502) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] ERROR test.GridFTPClientTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.GridFTPClientTest.test3PartyModeE_setParams(GridFTPClientTest.java:867) at org.globus.ftp.test.GridFTPClientTest.test3PartyModeE(GridFTPClientTest.java:838) at org.globus.ftp.test.GridFTPClientTest.test3PartyModeE(GridFTPClientTest.java:502) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClientTest - 3 party with bad port [main] INFO test.GridFTPClientTest - 3 party with bad server [main] INFO test.GridFTPClientTest - 3 party with bad src file [main] ERROR test.GridFTPClientTest - java.net.SocketException: Socket closed at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99) at java.net.SocketOutputStream.write(SocketOutputStream.java:124) at org.globus.ftp.vanilla.FTPControlChannel.writeStr(FTPControlChannel.java:472) at org.globus.ftp.vanilla.FTPControlChannel.write(FTPControlChannel.java:415) at org.globus.ftp.FTPClient.close(FTPClient.java:946) at org.globus.ftp.test.GridFTPClientTest.test3Party(GridFTPClientTest.java:796) at org.globus.ftp.test.GridFTPClientTest.test3PartyNoSuchSrcFile(GridFTPClientTest.java:704) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClientTest - 3 party with bad dest dir [main] ERROR test.GridFTPClientTest - java.net.SocketException: Socket closed at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99) at java.net.SocketOutputStream.write(SocketOutputStream.java:124) at org.globus.ftp.vanilla.FTPControlChannel.writeStr(FTPControlChannel.java:472) at org.globus.ftp.vanilla.FTPControlChannel.write(FTPControlChannel.java:415) at org.globus.ftp.FTPClient.close(FTPClient.java:946) at org.globus.ftp.test.GridFTPClientTest.test3Party(GridFTPClientTest.java:796) at org.globus.ftp.test.GridFTPClientTest.test3PartyNoSuchDestDir(GridFTPClientTest.java:741) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) Tests run: 30, Failures: 2, Errors: 24, Skipped: 0, Time elapsed: 1.188 sec <<< FAILURE! Running org.globus.ftp.test.ByteRangeListTest [main] INFO test.ByteRangeListTest - merging range: 0-298778624 + 298778624-466747392 [main] INFO test.ByteRangeListTest - merging vector of ranges: 1-6 [main] INFO test.ByteRangeListTest - merging vector of ranges: 1-19 [main] INFO test.ByteRangeListTest - merging vector of ranges: 1-6,9-19 [main] INFO test.ByteRangeListTest - merging vector of ranges: 1-3,6-19 [main] INFO test.ByteRangeListTest - merging vector of ranges: 1-3,6-19 [main] INFO test.ByteRangeListTest - merging vector of ranges: 0-3,9-19 [main] INFO test.ByteRangeListTest - merging vector of ranges: 0-19 [main] INFO test.ByteRangeListTest - merging vector of ranges: 6-19,50-64 [main] INFO test.ByteRangeListTest - merging vector of ranges: 6-7,9-19,50-64 [main] INFO test.ByteRangeListTest - merging vector of ranges: 6-7,9-19 [main] INFO test.ByteRangeListTest - merging vector of ranges: 6-7,30-40 [main] INFO test.ByteRangeListTest - merging vector of ranges: 3-100 [main] INFO test.ByteRangeListTest - merging vector of ranges: 3-100 [main] INFO test.ByteRangeListTest - merging vector of ranges: 1-1,3-3,6-8 [main] INFO test.ByteRangeListTest - merging vector of ranges: 1-4 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 0-5 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 7-11 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 3-15 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 10-18 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 10-23 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 10-30 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 10-50 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 10-53 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 13-16 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 12-17 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 16-31 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 12-100 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 24-26 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 20-23 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 20-29 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 20-30 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 20-49 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 27-27 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 27-30 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 26-40 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 46-51 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 51-52 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 52-53 [main] INFO test.ByteRangeListTest - merging range: 12-17,24-26,31-31,40-45,52-52 + 54-67 Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.036 sec Running org.globus.ftp.test.FileInfoTest Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.011 sec Running org.globus.ftp.test.OutputStreamDataSourceTest Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 22.058 sec Running org.globus.ftp.test.FTPClient2PartyTest [main] INFO test.FTPClient2PartyTest - get [main] INFO test.FTPClient2PartyTest - active, image, stream [main] INFO test.FTPClient2PartyTest - put [main] INFO test.FTPClient2PartyTest - active, image, stream [main] INFO test.FTPClient2PartyTest - get with bad src file [main] INFO test.FTPClient2PartyTest - active, image, stream [main] INFO test.FTPClient2PartyTest - put with bad dest dir [main] INFO test.FTPClient2PartyTest - active, image, stream [main] INFO test.FTPClient2PartyTest - get from non existent port [main] INFO test.FTPClient2PartyTest - active, image, stream [main] INFO test.FTPClient2PartyTest - put to non existent port [main] INFO test.FTPClient2PartyTest - active, image, stream [main] INFO test.FTPClient2PartyTest - get from non existent server [main] INFO test.FTPClient2PartyTest - active, image, stream [main] INFO test.FTPClient2PartyTest - put to non existent server [main] INFO test.FTPClient2PartyTest - active, image, stream Tests run: 6, Failures: 0, Errors: 4, Skipped: 0, Time elapsed: 0.246 sec <<< FAILURE! Running org.globus.ftp.test.InputStreamDataSinkTest Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.061 sec Running org.globus.ftp.test.GridFTPClient2PartyTransferTest [main] INFO test.GridFTPClient2PartyTransferTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTransferTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTransferTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTransferTest - with configuration: nodcau, clear Tests run: 4, Failures: 0, Errors: 4, Skipped: 0, Time elapsed: 0.343 sec <<< FAILURE! Running org.globus.ftp.test.FTPClientTest [main] INFO test.FTPClientTest - getSize() [main] INFO test.FTPClientTest - makeDir() [main] INFO test.FTPClientTest - setActive()/setPassive() [main] INFO test.FTPClientTest - setRestartMarker() [main] INFO test.FTPClientTest - 3 party [main] INFO test.FTPClientTest - 3 party with bad port [main] INFO test.FTPClientTest - 3 party with bad server [main] INFO test.FTPClientTest - 3 party with bad server [main] INFO test.FTPClientTest - 3 party with bad src file [main] INFO test.FTPClientTest - 3 party with bad dest dir Tests run: 11, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 34.608 sec <<< FAILURE! Running org.globus.ftp.test.HostPortTest Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 sec Running org.globus.ftp.test.MarkerTest [main] ERROR test.MarkerTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.MarkerTest.setParams(MarkerTest.java:188) at org.globus.ftp.test.MarkerTest.testModeEMarkers(MarkerTest.java:152) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] ERROR test.MarkerTest - java.net.SocketException: Socket closed at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99) at java.net.SocketOutputStream.write(SocketOutputStream.java:124) at org.globus.ftp.vanilla.FTPControlChannel.writeStr(FTPControlChannel.java:472) at org.globus.ftp.vanilla.FTPControlChannel.write(FTPControlChannel.java:415) at org.globus.ftp.vanilla.FTPControlChannel.exchange(FTPControlChannel.java:432) at org.globus.ftp.vanilla.FTPControlChannel.execute(FTPControlChannel.java:459) at org.globus.ftp.FTPClient.close(FTPClient.java:948) at org.globus.ftp.FTPClient.close(FTPClient.java:930) at org.globus.ftp.test.MarkerTest.testModeEMarkers(MarkerTest.java:171) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.083 sec <<< FAILURE! Running org.globus.ftp.test.GridFTPClient2PartyTest [main] INFO test.GridFTPClient2PartyTest - testing get [main] INFO test.GridFTPClient2PartyTest - with configuration: passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] ERROR test.GridFTPClient2PartyTest - Defective credential detected . Caused by org.globus.gsi.CredentialException: proxy not found at org.globus.gsi.X509Credential.(X509Credential.java:136) at org.globus.gsi.X509Credential.reloadDefaultCredential(X509Credential.java:480) at org.globus.gsi.X509Credential.getDefaultCredential(X509Credential.java:465) at org.globus.gsi.gssapi.GlobusGSSManagerImpl.createCredential(GlobusGSSManagerImpl.java:130) at org.globus.gsi.gssapi.GlobusGSSManagerImpl.createCredential(GlobusGSSManagerImpl.java:71) at org.globus.ftp.test.GridFTPClient2PartyTest.getCredential(GridFTPClient2PartyTest.java:632) at org.globus.ftp.test.GridFTPClient2PartyTest.get(GridFTPClient2PartyTest.java:426) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:391) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:310) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:77) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClient2PartyTest - testing put [main] INFO test.GridFTPClient2PartyTest - with configuration: active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] ERROR test.GridFTPClient2PartyTest - Defective credential detected . Caused by org.globus.gsi.CredentialException: proxy not found at org.globus.gsi.X509Credential.(X509Credential.java:136) at org.globus.gsi.X509Credential.reloadDefaultCredential(X509Credential.java:480) at org.globus.gsi.X509Credential.getDefaultCredential(X509Credential.java:465) at org.globus.gsi.gssapi.GlobusGSSManagerImpl.createCredential(GlobusGSSManagerImpl.java:130) at org.globus.gsi.gssapi.GlobusGSSManagerImpl.createCredential(GlobusGSSManagerImpl.java:71) at org.globus.ftp.test.GridFTPClient2PartyTest.getCredential(GridFTPClient2PartyTest.java:632) at org.globus.ftp.test.GridFTPClient2PartyTest.put(GridFTPClient2PartyTest.java:598) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:563) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:461) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:99) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClient2PartyTest - get from non existent port [main] INFO test.GridFTPClient2PartyTest - with configuration: passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - with configuration: active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - get from non existent server [main] INFO test.GridFTPClient2PartyTest - with configuration: passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - put to non existent server [main] INFO test.GridFTPClient2PartyTest - with configuration: active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - get with bad src file [main] INFO test.GridFTPClient2PartyTest - with configuration: passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] ERROR test.GridFTPClient2PartyTest - Defective credential detected . Caused by org.globus.gsi.CredentialException: proxy not found at org.globus.gsi.X509Credential.(X509Credential.java:136) at org.globus.gsi.X509Credential.reloadDefaultCredential(X509Credential.java:480) at org.globus.gsi.X509Credential.getDefaultCredential(X509Credential.java:465) at org.globus.gsi.gssapi.GlobusGSSManagerImpl.createCredential(GlobusGSSManagerImpl.java:130) at org.globus.gsi.gssapi.GlobusGSSManagerImpl.createCredential(GlobusGSSManagerImpl.java:71) at org.globus.ftp.test.GridFTPClient2PartyTest.getCredential(GridFTPClient2PartyTest.java:632) at org.globus.ftp.test.GridFTPClient2PartyTest.get(GridFTPClient2PartyTest.java:426) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:391) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:310) at org.globus.ftp.test.GridFTPClient2PartyTest.testGetNoSuchSrcFile(GridFTPClient2PartyTest.java:244) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClient2PartyTest - put with bad dest dir [main] INFO test.GridFTPClient2PartyTest - with configuration: active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] ERROR test.GridFTPClient2PartyTest - Defective credential detected . Caused by org.globus.gsi.CredentialException: proxy not found at org.globus.gsi.X509Credential.(X509Credential.java:136) at org.globus.gsi.X509Credential.reloadDefaultCredential(X509Credential.java:480) at org.globus.gsi.X509Credential.getDefaultCredential(X509Credential.java:465) at org.globus.gsi.gssapi.GlobusGSSManagerImpl.createCredential(GlobusGSSManagerImpl.java:130) at org.globus.gsi.gssapi.GlobusGSSManagerImpl.createCredential(GlobusGSSManagerImpl.java:71) at org.globus.ftp.test.GridFTPClient2PartyTest.getCredential(GridFTPClient2PartyTest.java:632) at org.globus.ftp.test.GridFTPClient2PartyTest.put(GridFTPClient2PartyTest.java:598) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:563) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:461) at org.globus.ftp.test.GridFTPClient2PartyTest.testPutNoSuchDestDir(GridFTPClient2PartyTest.java:277) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) Tests run: 6, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 0.167 sec <<< FAILURE! Running org.globus.ftp.test.GridFTPClient2PartyAsynchTransferTest [main] INFO test.GridFTPClient2PartyTransferTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTransferTest - with configuration: nodcau, clear Tests run: 4, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 0.076 sec <<< FAILURE! Running org.globus.ftp.test.FTPClientListTest [main] INFO test.FTPClientListTest - test two consective list, using both list functions Tests run: 3, Failures: 0, Errors: 3, Skipped: 0, Time elapsed: 0.108 sec <<< FAILURE! Running org.globus.ftp.test.ReplyTest [main] INFO test.ReplyTest - testing object: 230 User pafcio logged in. [main] INFO test.ReplyTest - testing object: 200 Command okay. [main] INFO test.ReplyTest - testing object: 123-First line Second line 234 A line beginning with numbers 123 The last line [main] INFO test.ReplyTest - testing object: 200 Command okay. aaaa [main] INFO test.ReplyTest - bad construction: [main] INFO test.ReplyTest - bad construction: [main] INFO test.ReplyTest - bad construction:0 [main] INFO test.ReplyTest - bad construction:1 fds [main] INFO test.ReplyTest - bad construction: 1 fds [main] INFO test.ReplyTest - bad construction:200p fds [main] INFO test.ReplyTest - bad construction:2000 fds [main] INFO test.ReplyTest - bad construction:345454 [main] INFO test.ReplyTest - bad construction:345454 [main] INFO test.ReplyTest - bad construction:123-First line Second line 234 A line beginning with numbers123 The last line Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.01 sec Running org.globus.ftp.test.PerfMarkerTest [main] INFO test.PerfMarkerTest - checking object: Perf Marker Timestamp: 111222333444.5 Stripe Index: 5 Stripe Bytes Transferred: 987654321987654321 Total Stripe Count: 30 112 End [main] INFO test.PerfMarkerTest - checking object: Perf Marker Total Stripe Count: 30 Stripe Index: 5 Stripe Bytes Transferred: 987654321987654321 Timestamp: 111222333444.5 112 End [main] INFO test.PerfMarkerTest - checking object: Perf Marker Timestamp: 111222333444.5 Total Stripe Count: 30 112 End [main] INFO test.PerfMarkerTest - checking object: Perf Marker Timestamp: 111222333444.5 Stripe Index: 5 Stripe Bytes Transferred: 987654321987654321 112 End [main] INFO test.PerfMarkerTest - checking object: Perf Marker Timestamp: 111222333444.5 112 End [main] INFO test.PerfMarkerTest - checking object: Perf Marker Timestamp: 0 Stripe Index: 0 Stripe Bytes Transferred: 0 Total Stripe Count: 0 112 End [main] INFO test.PerfMarkerTest - checking bad construction: Timestamp: 111222333444.5 Stripe Index: 5 Stripe Bytes Transferred: 987654321987654321 Total Stripe Count: 30 112 End [main] INFO test.PerfMarkerTest - checking bad construction: 112-Perf Marker Timestamp: 111222333444.5 Stripe Index: 5 Stripe Bytes Transferred: 987654321987654321 Total Stripe Count: 30 112 End [main] INFO test.PerfMarkerTest - checking bad construction: Perf Marker Stripe Index: 5 Stripe Bytes Transferred: 987654321987654321 Total Stripe Count: 30 112 End [main] INFO test.PerfMarkerTest - checking bad construction: Extensions supported: REST STREAM ESTO ERET MDTM SIZE PARALLEL DCAU 211 END Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.01 sec Running org.globus.ftp.test.MlsxTest [main] INFO test.MlsxTest - test creation of MlsxEntry [main] INFO test.MlsxTest - test MLST [main] INFO test.MlsxTest - show mlsd output using GridFTPClient [main] INFO test.MlsxTest - get mlsd output using GridFTPClient, EBlock, Image [main] INFO test.MlsxTest - test two consective mlsd, using both mlsd functions, using GridFTPClient Tests run: 5, Failures: 0, Errors: 4, Skipped: 0, Time elapsed: 0.161 sec <<< FAILURE! Running org.globus.ftp.test.DataChannelReuseVaryingParTest [main] INFO test.DataChannelReuseVaryingParTest - data channel reuse with get and changing parallelism [main] INFO test.DataChannelReuseVaryingParTest - data channel reuse with put and changing parallelism Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 0.071 sec <<< FAILURE! Running org.globus.ftp.test.GridFTPClient2PartyParallelTest [main] INFO test.GridFTPClient2PartyTest - Testing: [main] INFO test.GridFTPClient2PartyTest - parallel 2 party transfer [main] INFO test.GridFTPClient2PartyTest - testing get [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] ERROR test.GridFTPClient2PartyTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.get(GridFTPClient2PartyParallelTest.java:133) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:391) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.testGet(GridFTPClient2PartyParallelTest.java:95) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:77) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.testGet(GridFTPClient2PartyParallelTest.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClient2PartyTest - Testing: [main] INFO test.GridFTPClient2PartyTest - parallel 2 party transfer [main] INFO test.GridFTPClient2PartyTest - testing put [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] ERROR test.GridFTPClient2PartyTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.put(GridFTPClient2PartyParallelTest.java:177) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:563) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.testPut(GridFTPClient2PartyParallelTest.java:115) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:99) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.testPut(GridFTPClient2PartyParallelTest.java:77) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClient2PartyTest - get from non existent port [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - get from non existent server [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - put to non existent server [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - get with bad src file [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - put with bad dest dir [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear Tests run: 6, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 0.15 sec <<< FAILURE! Running org.globus.ftp.test.GridFTPClient2PartyStripingTest [main] INFO test.GridFTPClient2PartyTest - Testing: [main] INFO test.GridFTPClient2PartyTest - striped 2 party transfer [main] INFO test.GridFTPClient2PartyTest - testing get [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] ERROR test.GridFTPClient2PartyTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.GridFTPClient2PartyStripingTest.get(GridFTPClient2PartyStripingTest.java:77) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:391) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.testGet(GridFTPClient2PartyParallelTest.java:95) at org.globus.ftp.test.GridFTPClient2PartyTest.testGet(GridFTPClient2PartyTest.java:77) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.testGet(GridFTPClient2PartyParallelTest.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClient2PartyTest - Testing: [main] INFO test.GridFTPClient2PartyTest - striped 2 party transfer [main] INFO test.GridFTPClient2PartyTest - testing put [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] ERROR test.GridFTPClient2PartyTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.GridFTPClient2PartyStripingTest.put(GridFTPClient2PartyStripingTest.java:128) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:563) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.testPut(GridFTPClient2PartyParallelTest.java:115) at org.globus.ftp.test.GridFTPClient2PartyTest.testPut(GridFTPClient2PartyTest.java:99) at org.globus.ftp.test.GridFTPClient2PartyParallelTest.testPut(GridFTPClient2PartyParallelTest.java:77) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPClient2PartyTest - get from non existent port [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - get from non existent server [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - put to non existent server [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - get with bad src file [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, passive, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear [main] INFO test.GridFTPClient2PartyTest - put with bad dest dir [main] INFO test.GridFTPClient2PartyTest - with configuration: parallel, active, image, eblock [main] INFO test.GridFTPClient2PartyTest - with configuration: nodcau, clear Tests run: 6, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 0.145 sec <<< FAILURE! Running org.globus.ftp.test.GridFTPControlChannelTest [main] INFO test.GridFTPControlChannelTest - 3rd party [main] ERROR test.GridFTPControlChannelTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:140) at org.globus.ftp.test.GridFTPControlChannelTest.test3Party(GridFTPControlChannelTest.java:183) at org.globus.ftp.test.GridFTPControlChannelTest.test3Party(GridFTPControlChannelTest.java:98) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPControlChannelTest - 3rd party parallel (using OPTS RETR Parallelism) [main] ERROR test.GridFTPControlChannelTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:140) at org.globus.ftp.test.GridFTPControlChannelTest.test3PartyParallel(GridFTPControlChannelTest.java:277) at org.globus.ftp.test.GridFTPControlChannelTest.test3PartyParallel(GridFTPControlChannelTest.java:56) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPControlChannelTest - authenticate() [main] ERROR test.GridFTPControlChannelTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:140) at org.globus.ftp.test.GridFTPControlChannelTest.testAuth(GridFTPControlChannelTest.java:153) at org.globus.ftp.test.GridFTPControlChannelTest.testAuth(GridFTPControlChannelTest.java:82) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.GridFTPControlChannelTest - 3rd party striping (using SPAS/SPOR) [main] ERROR test.GridFTPControlChannelTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:140) at org.globus.ftp.test.GridFTPControlChannelTest.test3PartyStriping(GridFTPControlChannelTest.java:435) at org.globus.ftp.test.GridFTPControlChannelTest.test3PartyStriping(GridFTPControlChannelTest.java:124) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) Tests run: 4, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 0.151 sec <<< FAILURE! Running org.globus.ftp.test.ByteRangeTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec Running org.globus.ftp.test.MultipleTransfersTest [main] INFO test.MultipleTransfersTest - GridFTP client - client-server - multiple files - stream mode [main] INFO test.MultipleTransfersTest - GridFTP client - client-server - multiple files - stream mode - no d.c. reuse [main] INFO test.MultipleTransfersTest - GridFTP client - 3 party - multiple files - stream mode [main] ERROR test.MultipleTransfersTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.MultipleTransfersTest.setParamsModeS(MultipleTransfersTest.java:193) at org.globus.ftp.test.MultipleTransfersTest.test3PartyMultipleTransfers(MultipleTransfersTest.java:157) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] ERROR test.MultipleTransfersTest - java.net.SocketException: Socket closed at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99) at java.net.SocketOutputStream.write(SocketOutputStream.java:124) at org.globus.ftp.vanilla.FTPControlChannel.writeStr(FTPControlChannel.java:472) at org.globus.ftp.vanilla.FTPControlChannel.write(FTPControlChannel.java:415) at org.globus.ftp.vanilla.FTPControlChannel.exchange(FTPControlChannel.java:432) at org.globus.ftp.vanilla.FTPControlChannel.execute(FTPControlChannel.java:459) at org.globus.ftp.FTPClient.close(FTPClient.java:948) at org.globus.ftp.FTPClient.close(FTPClient.java:930) at org.globus.ftp.test.MultipleTransfersTest.test3PartyMultipleTransfers(MultipleTransfersTest.java:176) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] INFO test.MultipleTransfersTest - GridFTPClient - 3 party - multiple files - mode E [main] ERROR test.MultipleTransfersTest - org.globus.ftp.exception.ServerException: Server refused performing the request. Custom message: Server refused GSSAPI authentication. (error code 1) [Nested exception message: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End.]. Nested exception is org.globus.ftp.exception.UnexpectedReplyCodeException: Custom message: Unexpected reply: 530-globus_xio: Server side credential failure 530-globus_gsi_gssapi: Error with gss credential handle 530-globus_credential: Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Valid credentials could not be found in any of the possible locations specified by the credential search order. 530-Attempt 1 530-globus_credential: Error reading host credential 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: Error with certificate filename 530-globus_sysconfig: File is not owned by current user: /etc/grid-security/hostcert.pem is not owned by current user 530-Attempt 2 530-globus_credential: Error reading proxy credential 530-globus_sysconfig: Could not find a valid proxy certificate file location 530-globus_sysconfig: Error with key filename 530-globus_sysconfig: File does not exist: /tmp/x509up_u1000 is not a valid file 530-Attempt 3 530-globus_credential: Error reading user credential 530-globus_credential: Key is password protected: GSI does not currently support password protected private keys. 530-OpenSSL Error: pem_lib.c:406: in library: PEM routines, function PEM_do_header: bad password read 530 End. at org.globus.ftp.extended.GridFTPControlChannel.authenticate(GridFTPControlChannel.java:171) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:127) at org.globus.ftp.GridFTPClient.authenticate(GridFTPClient.java:103) at org.globus.ftp.test.MultipleTransfersTest.setParamsModeE(MultipleTransfersTest.java:262) at org.globus.ftp.test.MultipleTransfersTest.test3PartyMultipleTransfersModeE(MultipleTransfersTest.java:229) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) [main] ERROR test.MultipleTransfersTest - java.net.SocketException: Socket closed at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99) at java.net.SocketOutputStream.write(SocketOutputStream.java:124) at org.globus.ftp.vanilla.FTPControlChannel.writeStr(FTPControlChannel.java:472) at org.globus.ftp.vanilla.FTPControlChannel.write(FTPControlChannel.java:415) at org.globus.ftp.vanilla.FTPControlChannel.exchange(FTPControlChannel.java:432) at org.globus.ftp.vanilla.FTPControlChannel.execute(FTPControlChannel.java:459) at org.globus.ftp.FTPClient.close(FTPClient.java:948) at org.globus.ftp.FTPClient.close(FTPClient.java:930) at org.globus.ftp.test.MultipleTransfersTest.test3PartyMultipleTransfersModeE(MultipleTransfersTest.java:245) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:213) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140) at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127) at org.apache.maven.surefire.Surefire.run(Surefire.java:177) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009) Tests run: 4, Failures: 2, Errors: 2, Skipped: 0, Time elapsed: 0.224 sec <<< FAILURE! Running org.globus.ftp.test.FTPExceptionTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec Running org.globus.ftp.test.AsciiTranslatorTest Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 sec Running org.globus.ftp.test.TestEnv Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec Running org.globus.ftp.test.HostPortListTest [main] INFO test.HostPortListTest - testing construction from String [main] INFO test.HostPortListTest - checking bad message: MODE E ok. [main] INFO test.HostPortListTest - checking bad message: Extensions supported: REST STREAM ESTO ERET MDTM SIZE PARALLEL DCAU 211 END [main] INFO test.HostPortListTest - testing construction from HostPort object [main] INFO test.HostPortListTest - testing construction from String, and later modification by add(HostPort) Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec Running org.globus.ftp.test.FeatureListTest [main] INFO test.FeatureListTest - testing parsed feature set: [main] INFO test.FeatureListTest - okay, contains REST STREAM [main] INFO test.FeatureListTest - okay, contains ESTO [main] INFO test.FeatureListTest - okay, contains DCAU [main] INFO test.FeatureListTest - okay, contains PARALLEL [main] INFO test.FeatureListTest - okay, contains PARALLEL [main] INFO test.FeatureListTest - okay, contains SIZE [main] INFO test.FeatureListTest - okay, contains MDTM [main] INFO test.FeatureListTest - okay, contains ERET [main] INFO test.FeatureListTest - okay, does not contain Extensions supported: [main] INFO test.FeatureListTest - okay, does not contain 211 END [main] INFO test.FeatureListTest - okay, throws exception as expected. [main] INFO test.FeatureListTest - okay, does not contain [main] INFO test.FeatureListTest - okay, does not contain TVFS Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec Results : Failed tests: test3Party(org.globus.ftp.test.GridFTPClientTest) test3PartyModeE(org.globus.ftp.test.GridFTPClientTest) testModeEMarkers(org.globus.ftp.test.MarkerTest) testGet(org.globus.ftp.test.GridFTPClient2PartyTest) testPut(org.globus.ftp.test.GridFTPClient2PartyTest) testGetNoSuchSrcFile(org.globus.ftp.test.GridFTPClient2PartyTest) testPutNoSuchDestDir(org.globus.ftp.test.GridFTPClient2PartyTest) testGet(org.globus.ftp.test.GridFTPClient2PartyParallelTest) testPut(org.globus.ftp.test.GridFTPClient2PartyParallelTest) testGet(org.globus.ftp.test.GridFTPClient2PartyStripingTest) testPut(org.globus.ftp.test.GridFTPClient2PartyStripingTest) test3Party(org.globus.ftp.test.GridFTPControlChannelTest) test3PartyParallel(org.globus.ftp.test.GridFTPControlChannelTest) testAuth(org.globus.ftp.test.GridFTPControlChannelTest) test3PartyStriping(org.globus.ftp.test.GridFTPControlChannelTest) test3PartyMultipleTransfers(org.globus.ftp.test.MultipleTransfersTest) test3PartyMultipleTransfersModeE(org.globus.ftp.test.MultipleTransfersTest) Tests in error: testDefault(org.globus.ftp.test.TransferAppTest) testStreamImage(org.globus.ftp.test.TransferAppTest) testStreamAscii(org.globus.ftp.test.TransferAppTest) testStreamAsciiPasv(org.globus.ftp.test.TransferAppTest) testParallel5(org.globus.ftp.test.TransferAppTest) testParallel3Strip(org.globus.ftp.test.TransferAppTest) testPBSZ(org.globus.ftp.test.TransferAppTest) testAuthNone(org.globus.ftp.test.TransferAppTest) testAuthSelf(org.globus.ftp.test.TransferAppTest) testProtClear(org.globus.ftp.test.TransferAppTest) testProtPrivate(org.globus.ftp.test.TransferAppTest) testTCPBufferSmall(org.globus.ftp.test.TransferAppTest) testTCPBufferLarge(org.globus.ftp.test.TransferAppTest) testBasicGet(org.globus.ftp.test.DataChannelReuseTest) testBasicPut(org.globus.ftp.test.DataChannelReuseTest) testGetProtection(org.globus.ftp.test.DataChannelReuseTest) testPutProtection(org.globus.ftp.test.DataChannelReuseTest) testGetTCPBuffer(org.globus.ftp.test.DataChannelReuseTest) testPutTCPBuffer(org.globus.ftp.test.DataChannelReuseTest) testGetTearing(org.globus.ftp.test.DataChannelReuseTest) testPutTearing(org.globus.ftp.test.DataChannelReuseTest) testSize(org.globus.ftp.test.GridFTPClientTest) testDir(org.globus.ftp.test.GridFTPClientTest) testRestartMarker(org.globus.ftp.test.GridFTPClientTest) testControlChannelProtectionEnc(org.globus.ftp.test.GridFTPClientTest) testControlChannelProtectionSig(org.globus.ftp.test.GridFTPClientTest) testExists(org.globus.ftp.test.GridFTPClientTest) testFeature(org.globus.ftp.test.GridFTPClientTest) testQuote(org.globus.ftp.test.GridFTPClientTest) testSite(org.globus.ftp.test.GridFTPClientTest) testDirRename(org.globus.ftp.test.GridFTPClientTest) testOptions(org.globus.ftp.test.GridFTPClientTest) testAllocate(org.globus.ftp.test.GridFTPClientTest) testChecksum(org.globus.ftp.test.GridFTPClientTest) testListAscii(org.globus.ftp.test.GridFTPClientTest) testSetChecksum(org.globus.ftp.test.GridFTPClientTest) testListEblock(org.globus.ftp.test.GridFTPClientTest) testNListAscii(org.globus.ftp.test.GridFTPClientTest) testNListEblock(org.globus.ftp.test.GridFTPClientTest) testMListAscii(org.globus.ftp.test.GridFTPClientTest) testMListEblock(org.globus.ftp.test.GridFTPClientTest) testList2(org.globus.ftp.test.GridFTPClientTest) testConnectionReset1(org.globus.ftp.test.GridFTPClientTest) testConnectionReset2(org.globus.ftp.test.GridFTPClientTest) testConnectionReset3(org.globus.ftp.test.GridFTPClientTest) testGet(org.globus.ftp.test.FTPClient2PartyTest) testPut(org.globus.ftp.test.FTPClient2PartyTest) testGetNoSuchSrcFile(org.globus.ftp.test.FTPClient2PartyTest) testPutNoSuchDestDir(org.globus.ftp.test.FTPClient2PartyTest) testGetPassive(org.globus.ftp.test.GridFTPClient2PartyTransferTest) testGetActive(org.globus.ftp.test.GridFTPClient2PartyTransferTest) testPutPassive(org.globus.ftp.test.GridFTPClient2PartyTransferTest) testPutActive(org.globus.ftp.test.GridFTPClient2PartyTransferTest) testSize(org.globus.ftp.test.FTPClientTest) test3Party(org.globus.ftp.test.FTPClientTest) testGetPassive(org.globus.ftp.test.GridFTPClient2PartyAsynchTransferTest) testPutPassive(org.globus.ftp.test.GridFTPClient2PartyAsynchTransferTest) testListPassive(org.globus.ftp.test.FTPClientListTest) testListActive(org.globus.ftp.test.FTPClientListTest) test2(org.globus.ftp.test.FTPClientListTest) testMlst(org.globus.ftp.test.MlsxTest) test3(org.globus.ftp.test.MlsxTest) test4(org.globus.ftp.test.MlsxTest) test5(org.globus.ftp.test.MlsxTest) testGetVarPar(org.globus.ftp.test.DataChannelReuseVaryingParTest) testPutVarPar(org.globus.ftp.test.DataChannelReuseVaryingParTest) test2PartyMultipleTransfers(org.globus.ftp.test.MultipleTransfersTest) test2PartyMultipleTransfersModeE(org.globus.ftp.test.MultipleTransfersTest) Tests run: 160, Failures: 17, Errors: 68, Skipped: 0 [INFO] ------------------------------------------------------------------------ [ERROR] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] There are test failures. Please refer to /home/vg/Desktop/JGlobus/JGlobus/gridftp/target/surefire-reports for the individual test results. [INFO] ------------------------------------------------------------------------ [INFO] For more information, run Maven with the -e switch [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1 minute 10 seconds [INFO] Finished at: Fri Mar 30 09:38:07 CDT 2012 [INFO] Final Memory: 8M/19M [INFO] ------------------------------------------------------------------------ JGlobus-JGlobus-Release-2.1.0/gss/000077500000000000000000000000001241116057200165735ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/README.textile000066400000000000000000000000001241116057200211160ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/pom.xml000066400000000000000000000014751241116057200201170ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 gss GSS-API implementation for SSL with proxies junit junit test ${project.groupId} jsse ${project.version} JGlobus-JGlobus-Release-2.1.0/gss/src/000077500000000000000000000000001241116057200173625ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/000077500000000000000000000000001241116057200203065ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/000077500000000000000000000000001241116057200212275ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/000077500000000000000000000000001241116057200220165ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/000077500000000000000000000000001241116057200233115ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/000077500000000000000000000000001241116057200240735ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/000077500000000000000000000000001241116057200253615ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/ClosedGSSException.java000066400000000000000000000003051241116057200316670ustar00rootroot00000000000000package org.globus.gsi.gssapi; import org.ietf.jgss.GSSException; public class ClosedGSSException extends GSSException { public ClosedGSSException() { super(CONTEXT_EXPIRED); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/GSSConstants.java000066400000000000000000000145061241116057200305630ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import org.ietf.jgss.Oid; /** * Defines common GSI-GSS constants. */ public abstract class GSSConstants { /** Globus GSI GSS mechanism Oid */ public static final Oid MECH_OID; /** Context option. It is used to configure the GSS mode. It can be set to * {@link org.globus.gsi.GSIConstants#MODE_GSI GSIConstants.MODE_GSI} or * {@link org.globus.gsi.GSIConstants#MODE_SSL GSIConstants.MODE_SSL}. * By default GSI mode is enabled. */ public static final Oid GSS_MODE; /** Context option. It is used to enable/disable the rejection of * limited proxies during authentication. In can be set to either * Boolean.TRUE or Boolean.FALSE. * By default limited proxies are accepted.*/ public static final Oid REJECT_LIMITED_PROXY; /** Context option. It is used to configure delegation type to be * performed either during authentication or using the delegation API. * It can be set to {@link org.globus.gsi.GSIConstants#DELEGATION_TYPE_LIMITED * GSIConstants.DELEGATION_TYPE_LIMITED} or * {@link org.globus.gsi.GSIConstants#DELEGATION_TYPE_FULL * GSIConstants.DELEGATION_TYPE_FULL} * By default limited delegation is performed. */ public static final Oid DELEGATION_TYPE; /** Context option. It is used to enable/disable context expiration * checking for methods like wrap, unwrap, verifyMIC, getMIC. * In can be set to either Boolean.TRUE or * Boolean.FALSE. By default context expiration checking * is disabled. */ public static final Oid CHECK_CONTEXT_EXPIRATION; /** Context option. It is used to enable/disable client authentication * on acceptor side. In can be set to either Boolean.TRUE * or Boolean.FALSE. By default client authentication is * enabled.*/ public static final Oid REQUIRE_CLIENT_AUTH; /** Context option. It is only used when client authentication is enabled. * In can be set to either Boolean.TRUE or * Boolean.FALSE. If set to Boolean.TRUE * a context will be successfully established even though client * send no certificates and client authentication was required. * If set to Boolean.FALSE, the context establishment will fail * if client does not send its certificates and client authentication * was requested. */ public static final Oid ACCEPT_NO_CLIENT_CERTS; /** Context option. It is used to set a policy handler for * GRIM credentials. The value is an instance of * {@link org.globus.gsi.proxy.ProxyPolicyHandler * ProxyPolicyHandler} * @deprecated Please use {@link GSSConstants#PROXY_POLICY_HANDLERS * GSSConstants.PROXY_POLICY_HANDLERS} option instead. */ public static final Oid GRIM_POLICY_HANDLER; /** Context option. It is used to pass a set of proxy policy handlers. * The value if a Map type. It contains mappings of * proxy policy language oids and instances of * {@link org.globus.gsi.proxy.ProxyPolicyHandler ProxyPolicyHandler} */ public static final Oid PROXY_POLICY_HANDLERS; /** Context option. It is used to set a list of trusted certificates * to use during authentication (by default, the trusted certificates * are loaded from a standard location) The value is an instance of * {@link org.globus.gsi.TrustedCertificates TrustedCertificates} */ public static final Oid TRUSTED_CERTIFICATES; /** Used in inquireByOid function. Returns the certificate chain. */ public static final Oid X509_CERT_CHAIN; /** Used in inquireByOid method. Retuns if peer presented a * limited credential */ public static final Oid RECEIVED_LIMITED_PROXY; /** Context option. It is set to a Boolean value and if false, * client authorization requirement with delegation is disabled. By * default, client side authorization (to authorize the server) is * required for delegation of credentials. */ public static final Oid AUTHZ_REQUIRED_WITH_DELEGATION; /** Context option. It is set to a Boolean value and if true, * the GSI/GSSAPI layer will force the underlying SSL/TLS to * use SSLv3 and a narrow set of cipher suites so communication * with GRAM servers can succeed. */ public static final Oid FORCE_SSLV3_AND_CONSTRAIN_CIPHERSUITES_FOR_GRAM; /** Quality-of-Protection (QOP) value, indicates large block size support. * Can be passed to wrap or set by unwrap * methods */ public static final int GSI_BIG = 1; // GSS_C_QOP_GLOBUS_GSSAPI_OPENSSL_BIG static { try { // globus mech oid MECH_OID = new Oid("1.3.6.1.4.1.3536.1.1"); // options GSS_MODE = new Oid("1.3.6.1.4.1.3536.1.1.1"); DELEGATION_TYPE = new Oid("1.3.6.1.4.1.3536.1.1.2"); CHECK_CONTEXT_EXPIRATION = new Oid("1.3.6.1.4.1.3536.1.1.3"); REJECT_LIMITED_PROXY = new Oid("1.3.6.1.4.1.3536.1.1.4"); REQUIRE_CLIENT_AUTH = new Oid("1.3.6.1.4.1.3536.1.1.5"); GRIM_POLICY_HANDLER = new Oid("1.3.6.1.4.1.3536.1.1.6"); TRUSTED_CERTIFICATES = new Oid("1.3.6.1.4.1.3536.1.1.7"); X509_CERT_CHAIN = new Oid("1.3.6.1.4.1.3536.1.1.8"); ACCEPT_NO_CLIENT_CERTS = new Oid("1.3.6.1.4.1.3536.1.1.19"); PROXY_POLICY_HANDLERS = new Oid("1.3.6.1.4.1.3536.1.1.20"); RECEIVED_LIMITED_PROXY = new Oid("1.3.6.1.4.1.3536.1.1.21"); AUTHZ_REQUIRED_WITH_DELEGATION = new Oid("1.3.6.1.4.1.3536.1.1.22"); FORCE_SSLV3_AND_CONSTRAIN_CIPHERSUITES_FOR_GRAM = new Oid("1.3.6.1.4.1.3536.1.1.23"); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/GlobusGSSContextImpl.java000066400000000000000000003110631241116057200322270ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.util.ProxyCertificateUtil; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; import org.ietf.jgss.MessageProp; import org.ietf.jgss.ChannelBinding; import org.gridforum.jgss.ExtendedGSSContext; import org.gridforum.jgss.ExtendedGSSCredential; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.ArrayList; import java.util.LinkedList; import java.util.Date; import java.util.Calendar; import java.util.Map; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.security.KeyPair; import java.security.GeneralSecurityException; import java.security.interfaces.RSAPublicKey; import java.security.interfaces.RSAPrivateKey; import org.globus.gsi.ProviderLoader; import org.globus.gsi.stores.ResourceSigningPolicyStore; import java.security.cert.CertStore; import java.security.cert.CertificateFactory; import java.security.KeyStore; import org.globus.gsi.GSIConstants; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.X509Credential; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.bc.BouncyCastleUtil; import org.globus.gsi.bc.BouncyCastleCertProcessingFactory; import org.globus.util.I18n; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import org.globus.gsi.jsse.SSLConfigurator; import org.bouncycastle.jce.provider.X509CertificateObject; /* import COM.claymoresystems.ptls.SSLConn; import COM.claymoresystems.ptls.SSLRecord; import COM.claymoresystems.ptls.SSLDebug; import COM.claymoresystems.ptls.SSLCipherSuite; import COM.claymoresystems.ptls.SSLCipherState; import COM.claymoresystems.ptls.SSLHandshake; import COM.claymoresystems.sslg.SSLPolicyInt; import COM.claymoresystems.sslg.CertVerifyPolicyInt; import COM.claymoresystems.cert.X509Cert; import COM.claymoresystems.util.Util; */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.gsi.stores.Stores; /** * Implementation of SSL/GSI mechanism for Java GSS-API. The implementation * is based on JSSE (for SSL API) and the * BouncyCastle library * (for certificate processing API). *
    * The implementation is not designed to be thread-safe. */ public class GlobusGSSContextImpl implements ExtendedGSSContext { private static Log logger = LogFactory.getLog(GlobusGSSContextImpl.class.getName()); private static I18n i18n = I18n.getI18n("org.globus.gsi.gssapi.errors", GlobusGSSContextImpl.class.getClassLoader()); static { new ProviderLoader(); } /*DEL private static Log sslLog = LogFactory.getLog(SSLDebug.class.getName()); */ /** * KeyPair generation with cache of keypairs if configured */ private KeyPairCache keyPairCache = KeyPairCache.getKeyPairCache(); /** Used to distinguish between a token created by * wrap with {@link GSSConstants#GSI_BIG * GSSConstants.GSI_BIG} * QoP and a regular token created by wrap. */ public static final int GSI_WRAP = 26; /** SSL3_RT_GSSAPI_OPENSSL */ private static final int GSI_SEQUENCE_SIZE = 8; private static final int GSI_MESSAGE_DIGEST_PADDING = 12; private static final String [] ENABLED_PROTOCOLS = {"TLSv1", "SSLv3"}; // TODO: Delete this once GRAM server is fixed and we no longer // would be talking to old GRAM servers. private static final String [] GRAM_PROTOCOLS = {"SSLv3"}; /*DEL private static final short [] NO_ENCRYPTION = {SSLPolicyInt.TLS_RSA_WITH_NULL_MD5}; */ private static final String [] NO_ENCRYPTION = {"SSL_RSA_WITH_NULL_SHA", "SSL_RSA_WITH_NULL_MD5"}; // TODO: Delete these once GRAM server is fixed and we no longer // would be talking to old GRAM servers. private static final String [] GRAM_ENCRYPTION_CIPHER_SUITES = {"SSL_RSA_WITH_3DES_EDE_CBC_SHA"}; private static final String [] GRAM_NO_ENCRYPTION_CIPHER_SUITES = {"SSL_RSA_WITH_NULL_SHA"}; private static final byte[] DELEGATION_TOKEN = new byte[] {GSIConstants.DELEGATION_CHAR}; private static final int UNDEFINED = 0, INITIATE = 1, ACCEPT = 2; /** Handshake state */ protected int state = HANDSHAKE; /* handshake states */ private static final int HANDSHAKE = 0, CLIENT_START_DEL = 2, CLIENT_END_DEL = 3, SERVER_START_DEL = 4, SERVER_END_DEL = 5; /** Delegation state */ protected int delegationState = DELEGATION_START; /* delegation states */ private static final int DELEGATION_START = 0, DELEGATION_SIGN_CERT = 1, DELEGATION_COMPLETE_CRED = 2; /** Credential delegated using delegation API */ protected ExtendedGSSCredential delegatedCred; /** Delegation finished indicator */ protected boolean delegationFinished = false; // gss context state variables protected boolean credentialDelegation = false; protected boolean anonymity = false; protected boolean encryption = true; protected boolean established = false; /** The name of the context initiator */ protected GSSName sourceName = null; /** The name of the context acceptor */ protected GSSName targetName = null; /** Context role */ protected int role = UNDEFINED; /** Credential delegated during context establishment */ protected ExtendedGSSCredential delegCred; // these can be set via setOption /*DEL protected Integer delegationType = GSIConstants.DELEGATION_TYPE_LIMITED; */ protected GSIConstants.DelegationType delegationType = GSIConstants.DelegationType.LIMITED; protected Integer gssMode = GSIConstants.MODE_GSI; protected Boolean checkContextExpiration = Boolean.FALSE; protected Boolean rejectLimitedProxy = Boolean.FALSE; protected Boolean requireClientAuth = Boolean.TRUE; protected Boolean acceptNoClientCerts = Boolean.FALSE; protected Boolean requireAuthzWithDelegation = Boolean.TRUE; protected Boolean forceSSLv3AndConstrainCipherSuitesForGram = Boolean.FALSE; // *** implementation-specific variables *** /** Credential of this context. Might be anonymous */ protected GlobusGSSCredentialImpl ctxCred; /** Expected target name. Used for authorization in initiator */ protected GSSName expectedTargetName = null; /** Context expiration date. */ protected Date goodUntil = null; protected SSLConfigurator sslConfigurator = null; protected SSLContext sslContext = null; protected SSLEngine sslEngine = null; /*DEL protected SSLConn conn; */ protected boolean conn = false; /*DEL protected PureTLSContext context; protected SSLPolicyInt policy; protected TokenInputStream in; protected ByteArrayOutputStream out; */ private byte[] savedInBytes = null; private ByteBuffer outByteBuff = null; protected BouncyCastleCertProcessingFactory certFactory; /** Used during delegation */ protected KeyPair keyPair; protected TrustedCertificates tc; protected Map proxyPolicyHandlers; /** Limited peer credentials */ protected Boolean peerLimited = null; private String[] bannedCiphers = new String[0]; /** * @param target expected target name. Can be null. * @param cred credential. Cannot be null. Might be anonymous. */ public GlobusGSSContextImpl(GSSName target, GlobusGSSCredentialImpl cred) throws GSSException { if (cred == null) { throw new GSSException(GSSException.NO_CRED); } this.expectedTargetName = target; this.ctxCred = cred; /*DEL this.context = new PureTLSContext(); */ try { this.sslConfigurator = new SSLConfigurator(); // Need to set this so we are able to communicate properly with // GT4.0.8 servers that use only SSLv3 (no TLSv1). Thanks to // Jon Siwek for pointing this and the following link out: // http://java.sun.com/j2se/1.4.2/relnotes.html#security if (System.getProperty("com.sun.net.ssl.rsaPreMasterSecretFix") == null) System.setProperty("com.sun.net.ssl.rsaPreMasterSecretFix", "true"); // WARNING WARNING: // The new jglobus2-based srm-client is not compatible with old bestman2 // servers UNLESS we change this setting. // // The protection we are turning off helps against the BEAST attack. // When enabled, it will insert empty TLS application records into the // stream. However, the old server will deadlock on the extra records. // // To our knowledge, the BEAST attack is not applicable to this client as // we don't have any concurrent insecure connections. Regardless, we ought // to remove this as soon as we can drop support for the old servers. // // -BB. Sept 24, 2012. // System.setProperty("jsse.enableCBCProtection", "false"); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } /*DEL CertVerifyPolicyInt certPolicy = PureTLSUtil.getDefaultCertVerifyPolicy(); this.policy = new SSLPolicyInt(); this.policy.negotiateTLS(false); this.policy.waitOnClose(false); this.policy.setCertVerifyPolicy(certPolicy); this.context.setPolicy(policy); // TODO setSSLDebugging(); */ } /*DEL private void setSSLDebugging() { if (sslLog.isTraceEnabled()) { SSLDebug.setDebug( 0xffff ); } else if (sslLog.isDebugEnabled()) { SSLDebug.setDebug( SSLDebug.DEBUG_CERT ); } } */ /* * If the result indicates that we have outstanding tasks to do, * go ahead and run them in this thread. */ private void runDelegatedTasks(SSLEngine engine) throws Exception { Runnable runnable; while ((runnable = engine.getDelegatedTask()) != null) { logger.debug("\trunning delegated task..."); runnable.run(); } SSLEngineResult.HandshakeStatus hsStatus = engine.getHandshakeStatus(); if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) { throw new Exception( "handshake shouldn't need additional tasks"); } logger.debug("\tnew HandshakeStatus: " + hsStatus); } private X509Certificate bcConvert(X509Certificate cert) throws GSSException { if (!(cert instanceof X509CertificateObject)) { ByteArrayInputStream inputStream = null; try { inputStream = new ByteArrayInputStream(cert.getEncoded()); return CertificateLoadUtil.loadCertificate(inputStream); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); }finally{ if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { logger.warn("Unable to close streamreader."); } } } } else { return cert; } } /** * This function drives the accepting side of the context establishment * process. It is expected to be called in tandem with the * {@link #initSecContext(byte[], int, int) initSecContext} function. *
    * The behavior of context establishment process can be modified by * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * and {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} context options. If the * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option is set to * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * the context establishment process will be compatible with regular SSL * (no credential delegation support). If the option is set to * {@link GSIConstants#MODE_GSI GSIConstants.MODE_GSI} * credential delegation during context establishment process will be accepted. * If the {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, a peer * presenting limited proxy credential will be automatically * rejected and the context establishment process will be aborted. * * @return a byte[] containing the token to be sent to the peer. * null indicates that no token is generated (needs more data) */ public byte[] acceptSecContext(byte[] inBuff, int off, int len) throws GSSException { logger.debug("enter acceptSecContext"); if (!this.conn) { this.role = ACCEPT; logger.debug("enter initializing in acceptSecContext"); if (this.ctxCred.getName().isAnonymous()) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "acceptCtx00"); } if (this.ctxCred.getUsage() != GSSCredential.ACCEPT_ONLY && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "badCredUsage"); } setCredential(); try { init(this.role); } catch (SSLException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn = true; logger.debug("done initializing in acceptSecContext"); } /*DEL this.out.reset(); this.in.putToken(inBuff, off, len); */ this.outByteBuff.clear(); ByteBuffer inByteBuff; if (savedInBytes != null) { if (len > 0) { byte[] allInBytes = new byte[savedInBytes.length + len]; logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n"); System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length); System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len); inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length); } else { inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length); } savedInBytes = null; } else { inByteBuff = ByteBuffer.wrap(inBuff, off, len); } switch (state) { case HANDSHAKE: try { logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString()); SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus(); if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // return null; throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!"); } else { outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff); } logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString()); outByteBuff.flip(); /*DEL if (this.conn.getHandshake().finishedP()) { */ if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // the wrap/unwrap above has resulted in handshaking // being complete on our end. logger.debug("acceptSecContext handshake finished"); handshakeFinished(); // acceptor for (X509Certificate cert : this.ctxCred.getCertificateChain()) { setGoodUntil(cert.getNotAfter()); } this.targetName = this.ctxCred.getName(); // initiator - peer /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain; try { chain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { chain = null; } if (chain == null || chain.length == 0) { this.sourceName = new GlobusGSSName(); this.anonymity = true; } else { /*DEL X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1); setGoodUntil(crt.getValidityNotAfter()); String identity = verifyChain(chain); */ for (X509Certificate cert : (X509Certificate[])chain) { setGoodUntil(cert.getNotAfter()); } String identity = BouncyCastleUtil.getIdentity(bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate [])chain))); this.sourceName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false)); this.peerLimited = Boolean.valueOf(ProxyCertificateUtil.isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate)chain[0]))); logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName + " Limited Proxy: " + this.peerLimited.toString()); this.anonymity = false; } if (this.gssMode == GSIConstants.MODE_GSI) { this.state = SERVER_START_DEL; } else { setDone(); } } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } break; case SERVER_START_DEL: try { if (inByteBuff.remaining() <= 0) { return null; } /*DEL int delChar = this.conn.getInStream().read(); */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); byte [] delChar = new byte[outByteBuff.remaining()]; outByteBuff.get(delChar, 0, delChar.length); /*DEL if (delChar != GSIConstants.DELEGATION_CHAR) { */ if (!Arrays.equals(delChar, DELEGATION_TOKEN)) { setDone(); break; } /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain; try { chain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { chain = null; } if (chain == null || chain.length == 0) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.DELEGATION_ERROR, "noClientCert"); } X509Certificate tmpCert = (X509Certificate) chain[0]; /*DEL PureTLSUtil.convertCert((X509Cert)chain.lastElement()); */ byte [] req = generateCertRequest(tmpCert); /*DEL this.conn.getOutStream().write(req, 0, req.length); */ inByteBuff = ByteBuffer.wrap(req, 0, req.length); outByteBuff.clear(); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.state = SERVER_END_DEL; break; case SERVER_END_DEL: try { if (inByteBuff.remaining() <= 0) { return null; } /*DEL X509Certificate certificate = CertUtil.loadCertificate(this.conn.getInStream()); */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (!outByteBuff.hasRemaining()) break; byte [] buf = new byte[outByteBuff.remaining()]; outByteBuff.get(buf, 0, buf.length); ByteArrayInputStream inStream = new ByteArrayInputStream(buf, 0, buf.length); CertificateFactory cf = null; X509Certificate certificate = null; try{ cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate)cf.generateCertificate(inStream); }finally{ inStream.close(); } if (logger.isTraceEnabled()) { logger.trace("Received delegated cert: " + certificate.toString()); } verifyDelegatedCert(certificate); /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain = this.sslEngine.getSession().getPeerCertificates(); int chainLen = chain.length; X509Certificate [] newChain = new X509Certificate[chainLen + 1]; newChain[0] = bcConvert((X509Certificate)certificate); for (int i=0;i 0) ? this.out.toByteArray() : null; */ if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte [] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; } // Meant for non-handshake processing private ByteBuffer sslDataWrap(ByteBuffer inBBuff, ByteBuffer outBBuff) throws GSSException { try { if (sslEngine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { throw new Exception("SSLEngine handshaking needed! " + "HandshakeStatus: " + sslEngine.getHandshakeStatus().toString()); } int iter = 0; do { logger.debug("PROCESSING DATA (WRAP) " + ++iter + ": " + inBBuff.remaining()); SSLEngineResult result = sslEngine.wrap(inBBuff, outBBuff); if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) { runDelegatedTasks(sslEngine); continue; } if (result.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW) { // just increase it to the size needed. int pktSize = sslEngine.getSession().getPacketBufferSize(); ByteBuffer b = ByteBuffer.allocate(pktSize + outBBuff.position()); outBBuff.flip(); b.put(outBBuff); outBBuff = b; continue; } else if (result.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) { throw new GlobusGSSException(GSSException.FAILURE, new Exception("Unexpected BUFFER_UNDERFLOW;" + " Handshaking status: " + sslEngine.getHandshakeStatus())); } if (result.getStatus() != SSLEngineResult.Status.OK) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.TOKEN_FAIL, result.getStatus().toString()); } } while (inBBuff.hasRemaining()); return outBBuff; } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } } // Not all in inBBuff might be consumed by this method!!! private ByteBuffer sslDataUnwrap(ByteBuffer inBBuff, ByteBuffer outBBuff) throws GSSException { try { int iter = 0; if (sslEngine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { throw new Exception("SSLEngine handshaking needed! " + "HandshakeStatus: " + sslEngine.getHandshakeStatus().toString()); } do { logger.debug("PROCESSING DATA (UNWRAP) " + ++iter + ": " + inBBuff.remaining()); SSLEngineResult result = sslEngine.unwrap( inBBuff, outBBuff); if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) { runDelegatedTasks(sslEngine); continue; } if (result.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW) { // increase it to the size needed. int appSize = sslEngine.getSession().getApplicationBufferSize(); ByteBuffer b = ByteBuffer.allocate(appSize + outBBuff.position()); outBBuff.flip(); b.put(outBBuff); outBBuff = b; continue; } else if (result.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) { // More data needed from peer break; } else if (result.getStatus() == SSLEngineResult.Status.CLOSED) { throw new ClosedGSSException(); } if (result.getStatus() != SSLEngineResult.Status.OK) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.TOKEN_FAIL, result.getStatus().toString()); } } while (inBBuff.hasRemaining()); return outBBuff; } catch (IllegalArgumentException e) { throw new GlobusGSSException(GSSException.DEFECTIVE_TOKEN, e); } catch (SSLException e) { if (e.toString().endsWith("bad record MAC")) throw new GlobusGSSException(GSSException.BAD_MIC, e); else if (e.toString().endsWith("ciphertext sanity check failed")) throw new GlobusGSSException(GSSException.DEFECTIVE_TOKEN, e); else throw new GlobusGSSException(GSSException.FAILURE, e); } catch (GSSException e) { throw e; } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } } private ByteBuffer sslProcessHandshake(ByteBuffer inBBuff, ByteBuffer outBBuff) throws GSSException { // Loopon until we need more from peer or we are done with handshaking. try { done: do { while (sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP) { SSLEngineResult result = sslEngine.wrap(inBBuff, outBBuff); if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) { runDelegatedTasks(sslEngine); continue; } if (result.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW) { // increase it to the size needed. int pktSize = sslEngine.getSession().getPacketBufferSize(); ByteBuffer b = ByteBuffer.allocate(pktSize + outBBuff.position()); outBBuff.flip(); b.put(outBBuff); outBBuff = b; continue; } else if (result.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) { throw new GlobusGSSException(GSSException.FAILURE, new Exception("Unexpected BUFFER_UNDERFLOW;" + " Handshaking status: " + sslEngine.getHandshakeStatus())); } if (result.getStatus() != SSLEngineResult.Status.OK) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.TOKEN_FAIL, result.getStatus().toString()); } } int iter = 0; while (sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) { logger.debug("PROCESSING " + ++iter + ": " + inBBuff.remaining()); SSLEngineResult result = sslEngine.unwrap( inBBuff, outBBuff); if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) { runDelegatedTasks(sslEngine); continue; } if (result.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW) { // increase it to the size needed. int appSize = sslEngine.getSession().getApplicationBufferSize(); ByteBuffer b = ByteBuffer.allocate(appSize + outBBuff.position()); outBBuff.flip(); b.put(outBBuff); outBBuff = b; continue; } else if (result.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) { // More data needed from peer // break out of outer loop break done; } if (result.getStatus() != SSLEngineResult.Status.OK) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.TOKEN_FAIL, result.getStatus().toString()); } } } while (sslEngine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING); return outBBuff; } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } } /** * This function drives the initiating side of the context establishment * process. It is expected to be called in tandem with the * {@link #acceptSecContext(byte[], int, int) acceptSecContext} function. *
    * The behavior of context establishment process can be modified by * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}, * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE}, and * {@link GSSConstants#REJECT_LIMITED_PROXY GSSConstants.REJECT_LIMITED_PROXY} * context options. If the {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option is set to {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * the context establishment process will be compatible with regular SSL * (no credential delegation support). If the option is set to * {@link GSIConstants#MODE_GSI GSIConstants.GSS_MODE_GSI} * credential delegation during context establishment process will performed. * The delegation type to be performed can be set using the * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE} * context option. If the {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, * a peer presenting limited proxy credential will be automatically * rejected and the context establishment process will be aborted. * * @return a byte[] containing the token to be sent to the peer. * null indicates that no token is generated (needs more data). */ public byte[] initSecContext(byte[] inBuff, int off, int len) throws GSSException { logger.debug("enter initSecContext"); if (!this.conn) { this.role = INITIATE; logger.debug("enter initializing in initSecContext"); if (this.anonymity || this.ctxCred.getName().isAnonymous()) { this.anonymity = true; } else { this.anonymity = false; setCredential(); if (this.ctxCred.getUsage() != GSSCredential.INITIATE_ONLY && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "badCredUsage"); } } if (getCredDelegState()) { if (this.gssMode == GSIConstants.MODE_SSL) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx00"); } if (this.anonymity) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx01"); } } try { init(this.role); } catch (SSLException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn = true; logger.debug("done initializing in initSecContext"); } // Unless explicitly disabled, check if delegation is // requested and expected target is null logger.debug("Require authz with delegation: " + this.requireAuthzWithDelegation); if (!Boolean.FALSE.equals(this.requireAuthzWithDelegation)) { if (this.expectedTargetName == null && getCredDelegState()) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx02"); } } /*DEL this.out.reset(); this.in.putToken(inBuff, off, len); */ this.outByteBuff.clear(); ByteBuffer inByteBuff; if (savedInBytes != null) { if (len > 0) { byte[] allInBytes = new byte[savedInBytes.length + len]; logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n"); System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length); System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len); inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length); } else { inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length); } savedInBytes = null; } else { inByteBuff = ByteBuffer.wrap(inBuff, off, len); } switch (state) { case HANDSHAKE: try { logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString()); SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus(); if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // return null; throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!"); } else { outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff); } logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString()); outByteBuff.flip(); /*DEL this.conn.getHandshake().processHandshake(); if (this.conn.getHandshake().finishedP()) { */ if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // the wrap/unwrap above has resulted in handshaking // being complete on our end. logger.debug("initSecContext handshake finished"); handshakeFinished(); /*DEL Vector chain = this.conn.getCertificateChain(); X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1); setGoodUntil(crt.getValidityNotAfter()); */ Certificate[] chain = this.sslEngine.getSession().getPeerCertificates(); if (!(chain instanceof X509Certificate[])) { throw new Exception("Certificate chain not of type X509Certificate"); } for (X509Certificate cert : (X509Certificate[])chain) { setGoodUntil(cert.getNotAfter()); } // acceptor - peer /*DEL String identity = verifyChain(chain); */ // chain verification would have already been done by // JSSE String identity = BouncyCastleUtil.getIdentity(bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate [])chain))); this.targetName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false)); this.peerLimited = Boolean.valueOf(ProxyCertificateUtil.isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate)chain[0]))); logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName + " Limited Proxy: " + this.peerLimited.toString()); // initiator if (this.anonymity) { this.sourceName = new GlobusGSSName(); } else { for (X509Certificate cert : this.ctxCred.getCertificateChain()) { setGoodUntil(cert.getNotAfter()); } this.sourceName = this.ctxCred.getName(); } // mutual authentication test if (this.expectedTargetName != null && !this.expectedTargetName.equals(this.targetName)) { throw new GlobusGSSException(GSSException.UNAUTHORIZED, GlobusGSSException.BAD_NAME, "authFailed00", new Object[] {this.expectedTargetName, this.targetName}); } if (this.gssMode == GSIConstants.MODE_GSI) { this.state = CLIENT_START_DEL; // if there is data to return then // break. otherwise we fall through!!! if (this.outByteBuff.remaining() > 0) { break; } } else { setDone(); break; } } else { break; } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } case CLIENT_START_DEL: logger.debug("CLIENT_START_DEL"); // sanity check - might be invalid state if (this.state != CLIENT_START_DEL || this.outByteBuff.remaining() > 0) { throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { throw new GlobusGSSException(GSSException.FAILURE, new Exception("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus())); } this.outByteBuff.clear(); try { String deleg; if (getCredDelegState()) { deleg = Character.toString(GSIConstants.DELEGATION_CHAR); this.state = CLIENT_END_DEL; } else { deleg = Character.toString('0'); setDone(); } byte[] a = deleg.getBytes("US-ASCII"); inByteBuff = ByteBuffer.wrap(a, 0, a.length); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } break; case CLIENT_END_DEL: logger.debug("CLIENT_END_DEL"); if (!inByteBuff.hasRemaining()) { throw new GSSException(GSSException.DEFECTIVE_TOKEN); } ByteArrayInputStream byteArrayInputStream = null; try { /*DEL if (this.in.available() <= 0) { return null; } */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (!outByteBuff.hasRemaining()) break; byte [] certReq = new byte[outByteBuff.remaining()]; outByteBuff.get(certReq, 0, certReq.length); X509Certificate [] chain = this.ctxCred.getCertificateChain(); byteArrayInputStream = new ByteArrayInputStream(certReq); X509Certificate cert = this.certFactory.createCertificate(byteArrayInputStream, chain[0], this.ctxCred.getPrivateKey(), -1, /*DEL getDelegationType(chain[0])); */ BouncyCastleCertProcessingFactory.decideProxyType(chain[0], this.delegationType)); byte [] enc = cert.getEncoded(); /*DEL this.conn.getOutStream().write(enc, 0, enc.length); */ inByteBuff = ByteBuffer.wrap(enc, 0, enc.length); outByteBuff.clear(); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); setDone(); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); }finally{ if (byteArrayInputStream != null) { try { byteArrayInputStream.close(); } catch (Exception e) { logger.warn("Unable to close stream."); } } } break; default: throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { // Likely BUFFER_UNDERFLOW; save the // inByteBuff bytes here like in the unwrap() case logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus()); logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n"); savedInBytes = new byte[inByteBuff.remaining()]; inByteBuff.get(savedInBytes, 0, savedInBytes.length); } logger.debug("exit initSecContext"); //XXX: Why is here a check for CLIENT_START_DEL? // if (this.outByteBuff.hasRemaining() || this.state == CLIENT_START_DEL) { if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte [] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; } private void setDone() { logger.debug("DONE with Handshaking and any initial cred delegation"); this.established = true; } private void setGoodUntil(Date date) { if (this.goodUntil == null) { this.goodUntil = date; } else if (date.before(this.goodUntil)) { this.goodUntil = date; } } private void init(int how) throws GSSException, SSLException { /*DEL short [] cs; if (this.encryption) { // always make sure to add NULL cipher at the end short [] ciphers = this.policy.getCipherSuites(); short [] newCiphers = new short[ciphers.length + 1]; System.arraycopy(ciphers, 0, newCiphers, 0, ciphers.length); newCiphers[ciphers.length] = SSLPolicyInt.TLS_RSA_WITH_NULL_MD5; cs = newCiphers; } else { // encryption not requested - accept only one cipher // XXX: in the future might want to iterate through // all cipher and enable only the null encryption ones cs = NO_ENCRYPTION; } this.policy.setCipherSuites(cs); this.policy.requireClientAuth(this.requireClientAuth.booleanValue()); this.policy.setAcceptNoClientCert(this.acceptNoClientCerts.booleanValue()); setTrustedCertificates(); this.in = new TokenInputStream(); this.out = new ByteArrayOutputStream(); try { this.conn = new SSLConn(null, this.in, this.out, this.context, how); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn.init(); */ try { // set trust parameters in SSLConfigurator if(this.tc == null){ KeyStore trustStore = Stores.getDefaultTrustStore(); sslConfigurator.setTrustAnchorStore(trustStore); CertStore crlStore = Stores.getDefaultCRLStore(); sslConfigurator.setCrlStore(crlStore); ResourceSigningPolicyStore sigPolStore = Stores.getDefaultSigningPolicyStore(); sslConfigurator.setPolicyStore(sigPolStore); } this.sslConfigurator.setRejectLimitProxy(rejectLimitedProxy); if (proxyPolicyHandlers != null) sslConfigurator.setHandlers(proxyPolicyHandlers); this.sslContext = this.sslConfigurator.getSSLContext(); this.sslEngine = this.sslContext.createSSLEngine(); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } if (this.forceSSLv3AndConstrainCipherSuitesForGram.booleanValue()) this.sslEngine.setEnabledProtocols(GRAM_PROTOCOLS); else this.sslEngine.setEnabledProtocols(ENABLED_PROTOCOLS); logger.debug("SUPPORTED PROTOCOLS: " + Arrays.toString(this.sslEngine.getSupportedProtocols()) + "; ENABLED PROTOCOLS: " + Arrays.toString(this.sslEngine.getEnabledProtocols())); ArrayList cs = new ArrayList(); if (this.encryption) { if (this.forceSSLv3AndConstrainCipherSuitesForGram.booleanValue()) for (String cipherSuite : GRAM_ENCRYPTION_CIPHER_SUITES) cs.add(cipherSuite); else // Simply retain the default-enabled Cipher Suites cs.addAll(Arrays.asList(this.sslEngine.getEnabledCipherSuites())); } else { if (this.forceSSLv3AndConstrainCipherSuitesForGram.booleanValue()) for (String cipherSuite : GRAM_NO_ENCRYPTION_CIPHER_SUITES) cs.add(cipherSuite); else { for (String cipherSuite : NO_ENCRYPTION) cs.add(cipherSuite); cs.addAll(Arrays.asList(this.sslEngine.getEnabledCipherSuites())); } } cs.removeAll(Arrays.asList(bannedCiphers)); String[] testSuite = new String[0]; this.sslEngine.setEnabledCipherSuites(cs.toArray(testSuite)); logger.debug("CIPHER SUITE IS: " + Arrays.toString( this.sslEngine.getEnabledCipherSuites())); // TODO: Document the following behavior // NOTE: requireClientAuth Vs. acceptNoClientCerts // which one takes precedence? for now err on the side of security if (this.requireClientAuth.booleanValue() == Boolean.TRUE) { this.sslEngine.setNeedClientAuth(this.requireClientAuth.booleanValue()); } else this.sslEngine.setWantClientAuth(!this.acceptNoClientCerts.booleanValue()); this.sslEngine.setUseClientMode(how == INITIATE); this.certFactory = BouncyCastleCertProcessingFactory.getDefault(); this.state = HANDSHAKE; int appSize = sslEngine.getSession().getApplicationBufferSize(); this.outByteBuff = ByteBuffer.allocate(appSize); this.sslEngine.beginHandshake(); } /* this is called when handshake is done */ private void handshakeFinished() throws IOException { /*DEL // this call just forces some internal library // variables to be initailized this.conn.finishHandshake(); */ String cs = this.sslEngine.getSession().getCipherSuite(); this.encryption = !cs.contains("WITH_NULL"); logger.debug("encryption alg: " + cs); } /*DEL // allows bypass of PureTLS checks - since they were // already performed during SSL hashshake static class GSSProxyPathValidator extends ProxyPathValidator { public void validate(X509Certificate [] certPath, TrustedCertificates trustedCerts, CertificateRevocationLists crlsList) throws ProxyPathValidatorException { super.validate(certPath, trustedCerts, crlsList); } } private String verifyChain(Vector peerCerts) throws GSSException { X509Certificate[] peerChain = null; try { peerChain = PureTLSUtil.certificateChainToArray(peerCerts); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e); } GSSProxyPathValidator validator = new GSSProxyPathValidator(); if (this.proxyPolicyHandlers != null) { Iterator iter = this.proxyPolicyHandlers.keySet().iterator(); String oid; ProxyPolicyHandler handler; while(iter.hasNext()) { oid = (String)iter.next(); handler = (ProxyPolicyHandler)this.proxyPolicyHandlers.get(oid); validator.setProxyPolicyHandler(oid, handler); } } CertificateRevocationLists certRevList = CertificateRevocationLists.getDefaultCertificateRevocationLists(); validator.setRejectLimitedProxyCheck( this.rejectLimitedProxy.booleanValue()); try { validator.validate(peerChain, this.tc, certRevList); } catch (ProxyPathValidatorException e) { // COMMENT FIXME we don't have an error code if (e.getErrorCode() == ProxyPathValidatorException.LIMITED_PROXY_ERROR) { throw new GlobusGSSException(GSSException.UNAUTHORIZED, e); } else { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e); } } // C code also sets a flag RECEIVED_LIMITED_PROXY // when recevied certs is a limited proxy this.peerLimited = (validator.isLimited()) ? Boolean.TRUE : Boolean.FALSE; return validator.getIdentity(); } */ private void setCredential() throws GSSException { try { /*DEL this.context.setCredential(this.ctxCred.getX509Credential()); */ KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); X509Credential cred = this.ctxCred.getX509Credential(); keyStore.setKeyEntry("default", cred.getPrivateKey(), "password".toCharArray(), cred.getCertificateChain()); this.sslConfigurator.setCredentialStore(keyStore); this.sslConfigurator.setCredentialStorePassword("password"); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } } /*DEL private void setTrustedCertificates() throws GSSException { if (this.tc == null) { this.tc = PureTLSTrustedCertificates.getDefaultPureTLSTrustedCertificates(); } if (this.tc == null) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "noCaCerts"); } try { // COMMENT: move use of PureTLS from TrustCertificates this.context.setRootList(PureTLSUtil.certificateChainToVector(this.tc.getCertificates())); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } } */ /** * Wraps a message for integrity and protection. * A regular SSL-wrapped token is returned. */ public byte[] wrap(byte []inBuf, int off, int len, MessageProp prop) throws GSSException { checkContext(); logger.debug("enter wrap"); byte [] token = null; boolean doGSIWrap = false; if (prop != null) { if (prop.getQOP() != 0 && prop.getQOP() != GSSConstants.GSI_BIG) { throw new GSSException(GSSException.BAD_QOP); } doGSIWrap = (!prop.getPrivacy() && prop.getQOP() == GSSConstants.GSI_BIG); } if (doGSIWrap) { throw new GSSException(GSSException.UNAVAILABLE); /*DEL byte [] mic = getMIC(inBuf, off, len, null); byte [] wtoken = new byte[5 + len + mic.length]; wtoken[0] = GSI_WRAP; wtoken[1] = 3; wtoken[2] = 0; wtoken[3] = (byte)(mic.length >>> 8); wtoken[4] = (byte)(mic.length >>> 0); System.arraycopy(mic, 0, wtoken, 5, mic.length); System.arraycopy(inBuf, off, wtoken, 5+mic.length, len); token = wtoken; */ } else { token = wrap(inBuf, off, len); if (prop != null) { prop.setPrivacy(this.encryption); prop.setQOP(0); } } logger.debug("exit wrap"); return token; } private byte[] wrap(byte[] inBuf, int off, int len) throws GSSException { try { /*DEL this.conn.getOutStream().write(inBuf, off, len); */ ByteBuffer inByteBuff = ByteBuffer.wrap(inBuf, off, len); this.outByteBuff.clear(); outByteBuff = this.sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (inByteBuff.hasRemaining()) { throw new Exception("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus()); } } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte [] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; /*DEL return this.out.toByteArray(); */ } /** * Unwraps a token generated by wrap method on the other side of the context. */ public byte[] unwrap(byte []inBuf, int off, int len, MessageProp prop) throws GSSException { checkContext(); logger.debug("enter unwrap"); byte [] token = null; /* * see if the token is a straight SSL packet or * one of ours made by wrap using get_mic */ if (inBuf[off] == GSI_WRAP && inBuf[off+1] == 3 && inBuf[off+2] == 0) { throw new GSSException(GSSException.UNAVAILABLE); /*DEL int micLen = SSLUtil.toShort(inBuf[off+3], inBuf[off+4]); int msgLen = len - 5 - micLen; if (micLen > len-5 || msgLen < 0) { throw new GSSException(GSSException.DEFECTIVE_TOKEN); } verifyMIC(inBuf, off+5, micLen, inBuf, off+5+micLen, msgLen, null); if (prop != null) { prop.setPrivacy(false); prop.setQOP(GSSConstants.GSI_BIG); } // extract the data token = new byte[msgLen]; System.arraycopy(inBuf, off+5+micLen, token, 0, msgLen); */ } else { token = unwrap(inBuf, off, len); if (prop != null) { prop.setPrivacy(this.encryption); prop.setQOP(0); } } logger.debug("exit unwrap"); return token; } private byte[] unwrap(byte[] inBuf, int off, int len) throws GSSException { /*DEL ByteArrayInputStream in = new ByteArrayInputStream(inBuf, off, len); ByteArrayOutputStream out = new ByteArrayOutputStream(); // TODO: this might need to be rewritten // to catch lower level exceptions // e.g. mac too long, etc. try { while(in.available() > 0) { SSLRecord r = new SSLRecord(null); r.decode(this.conn, in); switch (r.getType().getValue()) { case SSLRecord.SSL_CT_APPLICATION_DATA: out.write(r.getData().getValue()); break; case SSLRecord.SSL_CT_ALERT: this.conn.getRecordReader().processAlert(r.getData().getValue()); break; default: throw new Exception(i18n.getMessage("tokenFail03")); } } } catch (IOException e) { throw new GlobusGSSException(GSSException.BAD_MIC, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.DEFECTIVE_TOKEN, e); } return out.toByteArray(); */ ByteBuffer inByteBuff; if (savedInBytes != null) { if (len > 0) { byte[] allInBytes = new byte[savedInBytes.length + len]; logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n"); System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length); System.arraycopy(inBuf, off, allInBytes, savedInBytes.length, len); inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length); } else { inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length); } savedInBytes = null; } else { inByteBuff = ByteBuffer.wrap(inBuf, off, len); } this.outByteBuff.clear(); outByteBuff = this.sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (inByteBuff.hasRemaining()) { logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus()); logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n"); savedInBytes = new byte[inByteBuff.remaining()]; inByteBuff.get(savedInBytes, 0, savedInBytes.length); } if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte [] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; } public void dispose() throws GSSException { // doesn't do anything right now logger.debug("dipose"); } public boolean isEstablished() { return this.established; } public void requestCredDeleg(boolean state) throws GSSException { this.credentialDelegation = state; } public boolean getCredDelegState() { return this.credentialDelegation; } public boolean isInitiator() throws GSSException { if (this.role == UNDEFINED) { throw new GSSException(GSSException.FAILURE); } return (this.role == INITIATE); } public boolean isProtReady() { return isEstablished(); } public void requestLifetime(int lifetime) throws GSSException { if (lifetime == GSSContext.INDEFINITE_LIFETIME) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.UNKNOWN, "badLifetime00"); } if (lifetime != GSSContext.DEFAULT_LIFETIME) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, lifetime); setGoodUntil(calendar.getTime()); } } public int getLifetime() { if (this.goodUntil != null) { return (int)((this.goodUntil.getTime() - System.currentTimeMillis())/1000); } else { return -1; } } public Oid getMech() throws GSSException { return GSSConstants.MECH_OID; } public GSSCredential getDelegCred() throws GSSException { return this.delegCred; } public void requestConf(boolean state) throws GSSException { // enabled encryption this.encryption = state; } public boolean getConfState() { return this.encryption; } /** * Returns a cryptographic MIC (message integrity check) * of a specified message. */ public byte[] getMIC(byte [] inBuf, int off, int len, MessageProp prop) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); /*TODO checkContext(); logger.debug("enter getMic"); if (prop != null && (prop.getQOP() != 0 || prop.getPrivacy())) { throw new GSSException(GSSException.BAD_QOP); } SSLCipherState st = this.conn.getWriteCipherState(); SSLCipherSuite cs = st.getCipherSuite(); long sequence = this.conn.getWriteSequence(); byte [] mic = new byte[GSI_MESSAGE_DIGEST_PADDING + cs.getDigestOutputLength()]; System.arraycopy(Util.toBytes(sequence), 0, mic, 0, GSI_SEQUENCE_SIZE); System.arraycopy(Util.toBytes(len, 4), 0, mic, GSI_SEQUENCE_SIZE, 4); this.conn.incrementWriteSequence(); int pad_ct = (cs.getDigestOutputLength()==16) ? 48 : 40; try { MessageDigest md = MessageDigest.getInstance(cs.getDigestAlg()); md.update(st.getMacKey()); for(int i=0;i 0) { // gap token throw new GSSException(GSSException.GAP_TOKEN); } else if (seqTest < 0) { // old token throw new GSSException(GSSException.OLD_TOKEN); } else { this.conn.incrementReadSequence(); } if (prop != null) { prop.setPrivacy(false); prop.setQOP(0); } logger.debug("exit verifyMic"); */ } /** * It works just like {@link #initSecContext(byte[], int, int) initSecContext} method. * It reads one SSL token from input stream, calls * {@link #initSecContext(byte[], int, int) initSecContext} method and * writes the output token to the output stream (if any) * SSL token is not read on the initial call. */ public int initSecContext(InputStream in, OutputStream out) throws GSSException { byte [] inToken = null; try { if (!this.conn) { inToken = new byte[0]; } else { inToken = SSLUtil.readSslMessage(in); } byte [] outToken = initSecContext(inToken, 0, inToken.length); if (outToken != null) { out.write(outToken); return outToken.length; } else { return 0; } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } } /** * It works just like {@link #acceptSecContext(byte[], int, int) acceptSecContext} * method. It reads one SSL token from input stream, calls * {@link #acceptSecContext(byte[], int, int) acceptSecContext} * method and writes the output token to the output stream (if any) */ public void acceptSecContext(InputStream in, OutputStream out) throws GSSException { try { byte [] inToken = SSLUtil.readSslMessage(in); byte [] outToken = acceptSecContext(inToken, 0, inToken.length); if (outToken != null) { out.write(outToken); } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } } public GSSName getSrcName() throws GSSException { return this.sourceName; } public GSSName getTargName() throws GSSException { return this.targetName; } public void requestInteg(boolean state) throws GSSException { if (!state) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION, "integOn"); } } public boolean getIntegState() { return true; // it is always on with ssl } public void requestSequenceDet(boolean state) throws GSSException { if (!state) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION, "seqDet"); } } public boolean getSequenceDetState() { return true; // it is always on with ssl } public void requestReplayDet(boolean state) throws GSSException { if (!state) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION, "replayDet"); } } public boolean getReplayDetState() { return true; // is is always on with ssl } public void requestAnonymity(boolean state) throws GSSException { this.anonymity = state; } public boolean getAnonymityState() { return this.anonymity; } public void requestMutualAuth(boolean state) throws GSSException { if (!state) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION, "mutualAuthOn"); } } public boolean getMutualAuthState() { return true; // always on with gsi i guess } protected byte[] generateCertRequest(X509Certificate cert) throws GeneralSecurityException { int bits = ((RSAPublicKey)cert.getPublicKey()).getModulus().bitLength(); this.keyPair = keyPairCache.getKeyPair(bits); return this.certFactory.createCertificateRequest(cert, this.keyPair); } protected void verifyDelegatedCert(X509Certificate certificate) throws GeneralSecurityException { RSAPublicKey pubKey = (RSAPublicKey)certificate.getPublicKey(); RSAPrivateKey privKey = (RSAPrivateKey)this.keyPair.getPrivate(); if (!pubKey.getModulus().equals(privKey.getModulus())) { throw new GeneralSecurityException(i18n.getMessage("keyMismatch")); } } protected void checkContext() throws GSSException { if (!this.conn || !isEstablished()) { throw new GSSException(GSSException.NO_CONTEXT); } if (this.checkContextExpiration.booleanValue() && getLifetime() <= 0) { throw new GSSException(GSSException.CONTEXT_EXPIRED); } } /*DEL protected int getDelegationType(X509Certificate issuer) throws GeneralSecurityException, GSSException { // GSIConstants.CertificateType certType = BouncyCastleUtil.getCertificateType(issuer, this.tc); // TODO: Is this alright without this.tc being passed? GSIConstants.CertificateType certType = BouncyCastleUtil.getCertificateType(issuer); int dType = this.delegationType.intValue(); if (logger.isDebugEnabled()) { logger.debug("Issuer type: " + certType + " delg. type requested: " + dType); } if (certType == GSIConstants.CertificateType.EEC) { if (dType == GSIConstants.DELEGATION_LIMITED) { if (VersionUtil.isGsi2Enabled()) { return GSIConstants.GSI_2_LIMITED_PROXY; } else if (VersionUtil.isGsi3Enabled()) { return GSIConstants.GSI_3_LIMITED_PROXY; } else { return GSIConstants.GSI_4_LIMITED_PROXY; } } else if (dType == GSIConstants.DELEGATION_FULL) { if (VersionUtil.isGsi2Enabled()) { return GSIConstants.GSI_2_PROXY; } else if (VersionUtil.isGsi3Enabled()) { return GSIConstants.GSI_3_IMPERSONATION_PROXY; } else { return GSIConstants.GSI_4_IMPERSONATION_PROXY; } } else if (ProxyCertificateUtil.isProxy(GSIConstants.CertificateType.get(dType))) { return dType; } } else if (ProxyCertificateUtil.isGsi2Proxy(certType)) { if (dType == GSIConstants.DELEGATION_LIMITED) { return GSIConstants.GSI_2_LIMITED_PROXY; } else if (dType == GSIConstants.DELEGATION_FULL) { return GSIConstants.GSI_2_PROXY; } else if (ProxyCertificateUtil.isGsi2Proxy(GSIConstants.CertificateType.get(dType))) { return dType; } } else if (ProxyCertificateUtil.isGsi3Proxy(certType)) { if (dType == GSIConstants.DELEGATION_LIMITED) { return GSIConstants.GSI_3_LIMITED_PROXY; } else if (dType == GSIConstants.DELEGATION_FULL) { return GSIConstants.GSI_3_IMPERSONATION_PROXY; } else if (ProxyCertificateUtil.isGsi3Proxy(GSIConstants.CertificateType.get(dType))) { return dType; } } else if (ProxyCertificateUtil.isGsi4Proxy(certType)) { if (dType == GSIConstants.DELEGATION_LIMITED) { return GSIConstants.GSI_4_LIMITED_PROXY; } else if (dType == GSIConstants.DELEGATION_FULL) { return GSIConstants.GSI_4_IMPERSONATION_PROXY; } else if (ProxyCertificateUtil.isGsi4Proxy(GSIConstants.CertificateType.get(dType))) { return dType; } } throw new GSSException(GSSException.FAILURE); } */ // ----------------------------------- protected void setGssMode(Object value) throws GSSException { if (!(value instanceof Integer)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object [] {"GSS mode", Integer.class}); } Integer v = (Integer)value; if (v == GSIConstants.MODE_GSI || v == GSIConstants.MODE_SSL) { this.gssMode = v; } else { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION, "badGssMode"); } } protected void setDelegationType(Object value) throws GSSException { GSIConstants.DelegationType v; if (value instanceof GSIConstants.DelegationType) v = (GSIConstants.DelegationType) value; else if (value instanceof Integer) v = GSIConstants.DelegationType.get(((Integer) value).intValue()); else { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"delegation type", GSIConstants.DelegationType.class}); } /*DEL Integer v = (Integer)value; */ if (v == GSIConstants.DelegationType.FULL || v == GSIConstants.DelegationType.LIMITED) { this.delegationType = v; } else { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION, "badDelegType"); } } protected void setCheckContextExpired(Object value) throws GSSException { if (!(value instanceof Boolean)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"check context expired", Boolean.class}); } this.checkContextExpiration = (Boolean)value; } protected void setRejectLimitedProxy(Object value) throws GSSException { if (!(value instanceof Boolean)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"reject limited proxy", Boolean.class}); } this.rejectLimitedProxy = (Boolean)value; } protected void setRequireClientAuth(Object value) throws GSSException { if (!(value instanceof Boolean)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"require client auth", Boolean.class}); } this.requireClientAuth = (Boolean)value; } protected void setRequireAuthzWithDelegation(Object value) throws GSSException { if (!(value instanceof Boolean)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"require authz with delehation", Boolean.class}); } this.requireAuthzWithDelegation = (Boolean)value; } protected void setAcceptNoClientCerts(Object value) throws GSSException { if (!(value instanceof Boolean)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"accept no client certs", Boolean.class}); } this.acceptNoClientCerts = (Boolean)value; } protected void setForceSslV3AndConstrainCipherSuitesForGram( Object value) throws GSSException { if (!(value instanceof Boolean)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"adjust cipher suites for GRAM", Boolean.class}); } this.forceSSLv3AndConstrainCipherSuitesForGram = (Boolean)value; } /*DEL protected void setGrimPolicyHandler(Object value) throws GSSException { if (!(value instanceof ProxyPolicyHandler)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"GRIM policy handler", ProxyPolicyHandler.class}); } if (this.proxyPolicyHandlers == null) { this.proxyPolicyHandlers = new HashMap(); } this.proxyPolicyHandlers.put("1.3.6.1.4.1.3536.1.1.1.7", value); } */ protected void setProxyPolicyHandlers(Object value) throws GSSException { if (!(value instanceof Map)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"Proxy policy handlers", Map.class}); } this.proxyPolicyHandlers = (Map)value; } protected void setTrustedCertificates(Object value) throws GSSException { if (!(value instanceof TrustedCertificates)) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_OPTION_TYPE, "badType", new Object[] {"Trusted certificates", TrustedCertificates.class}); } this.tc = (TrustedCertificates) value; //TODO: set this in SSLConfigurator before creating SSLContext and engine? sslConfigurator.setTrustAnchorStore(((TrustedCertificates)value).getTrustStore()); sslConfigurator.setCrlStore(((TrustedCertificates)value).getcrlStore()); sslConfigurator.setPolicyStore(((TrustedCertificates)value).getsigPolStore()); } public void setOption(Oid option, Object value) throws GSSException { if (option == null) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "nullOption"); } if (value == null) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "nullOptionValue"); } if (option.equals(GSSConstants.GSS_MODE)) { setGssMode(value); } else if (option.equals(GSSConstants.DELEGATION_TYPE)) { setDelegationType(value); } else if (option.equals(GSSConstants.CHECK_CONTEXT_EXPIRATION)) { setCheckContextExpired(value); } else if (option.equals(GSSConstants.REJECT_LIMITED_PROXY)) { setRejectLimitedProxy(value); } else if (option.equals(GSSConstants.REQUIRE_CLIENT_AUTH)) { setRequireClientAuth(value); /*DEL } else if (option.equals(GSSConstants.GRIM_POLICY_HANDLER)) { setGrimPolicyHandler(value); */ } else if (option.equals(GSSConstants.TRUSTED_CERTIFICATES)) { setTrustedCertificates(value); } else if (option.equals(GSSConstants.PROXY_POLICY_HANDLERS)) { setProxyPolicyHandlers(value); } else if (option.equals(GSSConstants.ACCEPT_NO_CLIENT_CERTS)) { setAcceptNoClientCerts(value); } else if (option.equals(GSSConstants .AUTHZ_REQUIRED_WITH_DELEGATION)) { setRequireAuthzWithDelegation(value); } else if (option.equals(GSSConstants .FORCE_SSLV3_AND_CONSTRAIN_CIPHERSUITES_FOR_GRAM)) { setForceSslV3AndConstrainCipherSuitesForGram(value); } else { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.UNKNOWN_OPTION, "unknownOption", new Object[] {option}); } } public Object getOption(Oid option) throws GSSException { if (option == null) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "nullOption"); } if (option.equals(GSSConstants.GSS_MODE)) { return this.gssMode; } else if (option.equals(GSSConstants.DELEGATION_TYPE)) { return this.delegationType; } else if (option.equals(GSSConstants.CHECK_CONTEXT_EXPIRATION)) { return this.checkContextExpiration; } else if (option.equals(GSSConstants.REJECT_LIMITED_PROXY)) { return this.rejectLimitedProxy; } else if (option.equals(GSSConstants.REQUIRE_CLIENT_AUTH)) { return this.requireClientAuth; } else if (option.equals(GSSConstants.TRUSTED_CERTIFICATES)) { return this.tc; } else if (option.equals(GSSConstants.PROXY_POLICY_HANDLERS)) { // return this.proxyPolicyHandlers; throw new GSSException(GSSException.UNAVAILABLE); } else if (option.equals(GSSConstants.ACCEPT_NO_CLIENT_CERTS)) { return this.acceptNoClientCerts; } return null; } /** * Initiate the delegation of a credential. * * This function drives the initiating side of the credential * delegation process. It is expected to be called in tandem with the * {@link #acceptDelegation(int, byte[], int, int) acceptDelegation} * function. *
    * The behavior of this function can be modified by * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE} * and * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} context * options. * The {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE} * option controls delegation type to be performed. The * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option if set to * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * results in tokens that are not wrapped. * * @param credential * The credential to be delegated. May be null * in which case the credential associated with the security * context is used. * @param mechanism * The desired security mechanism. May be null. * @param lifetime * The requested period of validity (seconds) of the delegated * credential. * @return A token that should be passed to acceptDelegation if * isDelegationFinished returns false. May be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public byte[] initDelegation(GSSCredential credential, Oid mechanism, int lifetime, byte[] buf, int off, int len) throws GSSException { logger.debug("Enter initDelegation: " + delegationState); if (mechanism != null && !mechanism.equals(getMech())) { throw new GSSException(GSSException.BAD_MECH); } if (this.gssMode != GSIConstants.MODE_SSL && buf != null && len > 0) { buf = unwrap(buf, off, len); off = 0; len = buf.length; } byte [] token = null; switch (delegationState) { case DELEGATION_START: this.delegationFinished = false; token = DELEGATION_TOKEN; this.delegationState = DELEGATION_SIGN_CERT; break; case DELEGATION_SIGN_CERT: if (credential == null) { // get default credential GSSManager manager = new GlobusGSSManagerImpl(); credential = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT); } if (!(credential instanceof GlobusGSSCredentialImpl)) { throw new GSSException(GSSException.DEFECTIVE_CREDENTIAL); } X509Credential cred = ((GlobusGSSCredentialImpl)credential).getX509Credential(); X509Certificate [] chain = cred.getCertificateChain(); int time = (lifetime == GSSCredential.DEFAULT_LIFETIME) ? -1 : lifetime; ByteArrayInputStream inData = null; ByteArrayOutputStream out = null; try { inData = new ByteArrayInputStream(buf, off, len); X509Certificate cert = this.certFactory.createCertificate(inData, chain[0], cred.getPrivateKey(), time, /*DEL getDelegationType(chain[0])); */ BouncyCastleCertProcessingFactory.decideProxyType(chain[0], this.delegationType)); out = new ByteArrayOutputStream(); out.write(cert.getEncoded()); for (int i=0;i * The behavior of this function can be modified by * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} context * option. The * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option if set to * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * results in tokens that are not wrapped. * * @param lifetime * The requested period of validity (seconds) of the delegated * credential. * @return A token that should be passed to initDelegation if * isDelegationFinished returns false. May be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public byte[] acceptDelegation(int lifetime, byte[] buf, int off, int len) throws GSSException { logger.debug("Enter acceptDelegation: " + delegationState); if (this.gssMode != GSIConstants.MODE_SSL && buf != null && len > 0) { buf = unwrap(buf, off, len); off = 0; len = buf.length; } byte [] token = null; switch (delegationState) { case DELEGATION_START: this.delegationFinished = false; if (len != 1 && buf[off] != GSIConstants.DELEGATION_CHAR) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.DELEGATION_ERROR, "delegError00", new Object[] {new Character((char)buf[off])}); } try { /*DEL Vector certChain = this.conn.getCertificateChain(); */ Certificate[] certChain; try { certChain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { certChain = null; } if (certChain == null || certChain.length == 0) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.DELEGATION_ERROR, "noClientCert"); } X509Certificate tmpCert = /*DEL PureTLSUtil.convertCert((X509Cert)certChain.lastElement()); */ (X509Certificate) certChain[0]; token = generateCertRequest(tmpCert); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.delegationState = DELEGATION_COMPLETE_CRED; break; case DELEGATION_COMPLETE_CRED: ByteArrayInputStream in = null; X509Certificate [] chain = null; LinkedList certList = new LinkedList(); X509Certificate cert = null; try { in = new ByteArrayInputStream(buf, off, len); while(in.available() > 0) { cert = CertificateLoadUtil.loadCertificate(in); certList.add(cert); } chain = new X509Certificate[certList.size()]; chain = (X509Certificate[])certList.toArray(chain); verifyDelegatedCert(chain[0]); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); }finally{ if (in != null) { try { in.close(); } catch (Exception e) { logger.warn("Unable to close streamreader."); } } } X509Credential proxy = new X509Credential(this.keyPair.getPrivate(), chain); this.delegatedCred = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT); this.delegationState = DELEGATION_START; this.delegationFinished = true; break; default: throw new GSSException(GSSException.FAILURE); } logger.debug("Exit acceptDelegation"); if (this.gssMode != GSIConstants.MODE_SSL && token != null) { // XXX: Why wrap() only when not in MODE_SSL? return wrap(token, 0, token.length); } else { return token; } } public GSSCredential getDelegatedCredential() { return this.delegatedCred; } public boolean isDelegationFinished() { return this.delegationFinished; } /** * Retrieves arbitrary data about this context. * Currently supported oid:
      *
    • * {@link GSSConstants#X509_CERT_CHAIN GSSConstants.X509_CERT_CHAIN} * returns certificate chain of the peer (X509Certificate[]). *
    • *
    * * @param oid the oid of the information desired. * @return the information desired. Might be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public Object inquireByOid(Oid oid) throws GSSException { if (oid == null) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "nullOption"); } if (oid.equals(GSSConstants.X509_CERT_CHAIN)) { if (isEstablished()) { // converting certs is slower but keeping coverted certs // takes lots of memory. try { /*DEL Vector peerCerts = this.conn.getCertificateChain(); */ Certificate[] peerCerts; try { peerCerts = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { peerCerts = null; } if (peerCerts != null && peerCerts.length > 0) { /*DEL return PureTLSUtil.certificateChainToArray(peerCerts); */ return (X509Certificate[])peerCerts; } else { return null; } } catch (Exception e) { throw new GlobusGSSException( GSSException.DEFECTIVE_CREDENTIAL, e ); } } } else if (oid.equals(GSSConstants.RECEIVED_LIMITED_PROXY)) { return this.peerLimited; } return null; } public void setBannedCiphers(String[] ciphers) { bannedCiphers = new String[ciphers.length]; System.arraycopy(ciphers, 0, bannedCiphers, 0, ciphers.length); } // ================================================================== // Not implemented below // ================================================================== /** * Currently not implemented. */ public int getWrapSizeLimit(int qop, boolean confReq, int maxTokenSize) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public void wrap(InputStream inStream, OutputStream outStream, MessageProp msgProp) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public void unwrap(InputStream inStream, OutputStream outStream, MessageProp msgProp) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public void getMIC(InputStream inStream, OutputStream outStream, MessageProp msgProp) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public void verifyMIC(InputStream tokStream, InputStream msgStream, MessageProp msgProp) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public void setChannelBinding(ChannelBinding cb) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public boolean isTransferable() throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public byte [] export() throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/GlobusGSSCredentialImpl.java000066400000000000000000000171401241116057200326540ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import org.globus.util.Util; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; import org.gridforum.jgss.ExtendedGSSCredential; import java.security.cert.X509Certificate; import java.security.PrivateKey; import java.io.ByteArrayOutputStream; import java.io.Serializable; import java.io.IOException; import java.io.File; import java.io.FileOutputStream; import org.globus.gsi.X509Credential; import java.security.cert.CertificateEncodingException; import org.globus.gsi.CredentialException; /** * An implementation of GlobusGSSCredential. */ public class GlobusGSSCredentialImpl implements ExtendedGSSCredential, Serializable { private static final long serialVersionUID = 1L; private int usage = 0; private X509Credential cred; private GSSName name; /** * Creates anonymous credential. */ public GlobusGSSCredentialImpl() { this.cred = null; this.name = new GlobusGSSName(); } /** * Creates regular credential from specified * X509Credential object. * * @param cred the credential * @param usage credential usage */ public GlobusGSSCredentialImpl(X509Credential cred, int usage) throws GSSException { if (cred == null) { throw new IllegalArgumentException("cred == null"); } this.cred = cred; this.usage = usage; this.name = new GlobusGSSName(cred.getIdentity()); } @Override public int hashCode() { if (this.cred == null) { return this.usage; } else { return this.cred.hashCode() + this.usage; } } @Override public boolean equals(Object obj) { if (obj instanceof GlobusGSSCredentialImpl) { GlobusGSSCredentialImpl other = (GlobusGSSCredentialImpl)obj; return other.usage == this.usage && (other.cred == this.cred || this.cred != null && this.cred.equals(other.cred)); } return false; } public void dispose() throws GSSException { this.cred = null; } public GSSName getName() throws GSSException { return this.name; } public GSSName getName(Oid mech) throws GSSException { GlobusGSSManagerImpl.checkMechanism(mech); return this.name; } /** * Currently not implemented. */ public void add(GSSName aName, int initLifetime, int acceptLifetime, Oid mech, int usage) throws GSSException { // currently we are not supporting multiple mechanism // credentials throw new GSSException(GSSException.UNAVAILABLE); } public int getUsage() throws GSSException { return usage; } public int getUsage(Oid mech) throws GSSException { GlobusGSSManagerImpl.checkMechanism(mech); return this.usage; } public int getRemainingLifetime() throws GSSException { return (this.cred == null) ? -1 : (int)this.cred.getTimeLeft(); } public int getRemainingInitLifetime(Oid mech) throws GSSException { GlobusGSSManagerImpl.checkMechanism(mech); if (this.usage == INITIATE_ONLY || this.usage == INITIATE_AND_ACCEPT) { return getRemainingLifetime(); } else { throw new GSSException(GSSException.FAILURE); } } public int getRemainingAcceptLifetime(Oid mech) throws GSSException { GlobusGSSManagerImpl.checkMechanism(mech); if (this.usage == ACCEPT_ONLY || this.usage == INITIATE_AND_ACCEPT) { return getRemainingLifetime(); } else { throw new GSSException(GSSException.FAILURE); } } public Oid[] getMechs() throws GSSException { return GlobusGSSManagerImpl.MECHS; } public byte[] export(int option) throws GSSException { return export(option, null); } public byte[] export(int option, Oid mech) throws GSSException { GlobusGSSManagerImpl.checkMechanism(mech); if (this.cred == null) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.CREDENTIAL_ERROR, "anonCred00"); } switch (option) { case IMPEXP_OPAQUE: ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { this.cred.save(bout); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (CertificateEncodingException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } return bout.toByteArray(); case IMPEXP_MECH_SPECIFIC: File file = null; FileOutputStream fout = null; try { file = File.createTempFile("x509up_", ".tmp"); Util.setOwnerAccessOnly(file.getAbsolutePath()); fout = new FileOutputStream(file); this.cred.save(fout); } catch(IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (CertificateEncodingException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } finally { if (fout != null) { try { fout.close(); } catch (Exception e) {} } } String handle = "X509_USER_PROXY=" + file.getAbsolutePath(); return handle.getBytes(); default: throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "unknownOption", new Object[] {new Integer(option)}); } } /** * Retrieves arbitrary data about this credential. * Currently supported oid:
      *
    • * {@link GSSConstants#X509_CERT_CHAIN GSSConstants.X509_CERT_CHAIN} * returns certificate chain of this credential * (X509Certificate[]). *
    • *
    * * @param oid the oid of the information desired. * @return the information desired. Might be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public Object inquireByOid(Oid oid) throws GSSException { if (oid == null) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "nullOption"); } if (oid.equals(GSSConstants.X509_CERT_CHAIN)) { return (this.cred == null) ? null : this.cred.getCertificateChain(); } return null; } /** * Returns actual X509Credential object represented * by this credential (if any). * * @return The credential object. Might be null if * this is an anonymous credential. */ public X509Credential getX509Credential() { return this.cred; } /** * Returns the private key of this credential (if any). * * @return The private key. Might be null if this * is an anonymous credential. */ public PrivateKey getPrivateKey() throws GSSException { try { return (this.cred == null) ? null : this.cred.getPrivateKey(); } catch (CredentialException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } } /** * Returns certificate chain of this credential (if any). * * @return The certificate chain. Might be null if this * is an anonymous credential. */ public X509Certificate [] getCertificateChain() { return (this.cred == null) ? null : this.cred.getCertificateChain(); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/GlobusGSSException.java000066400000000000000000000163471241116057200317260ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import java.io.PrintStream; import java.io.PrintWriter; import java.text.MessageFormat; import java.util.ResourceBundle; import java.util.MissingResourceException; import org.ietf.jgss.GSSException; import javax.net.ssl.SSLException; public class GlobusGSSException extends GSSException { private static final long serialVersionUID = 1366868883920091438L; public static final int PROXY_VIOLATION = 5, BAD_ARGUMENT = 7, BAD_NAME = 25, CREDENTIAL_ERROR = 27, TOKEN_FAIL = 29, DELEGATION_ERROR = 30, BAD_MIC = 33, UNKNOWN_OPTION = 37; public static final int BAD_OPTION_TYPE = 100, BAD_OPTION = 101, UNKNOWN = 102; private static ResourceBundle resources; static { try { resources = ResourceBundle.getBundle("org.globus.gsi.gssapi.errors"); } catch (MissingResourceException e) { throw new RuntimeException(e.getMessage()); } } private final boolean hasCustomMessage; public GlobusGSSException(int majorCode, Throwable cause) { super(majorCode); initCause(cause); hasCustomMessage = false; } public GlobusGSSException(int majorCode, int minorCode, String minorString, Throwable cause) { super(majorCode, minorCode, minorString); initCause(cause); hasCustomMessage = true; } public GlobusGSSException(int majorCode, int minorCode, String key) { this(majorCode, minorCode, key, (Object[])null); } public GlobusGSSException(int majorCode, int minorCode, String key, Object [] args) { super(majorCode); String msg = null; try { msg = MessageFormat.format(resources.getString(key), args); } catch (MissingResourceException e) { //msg = "No msg text defined for '" + key + "'"; throw new RuntimeException("bad" + key); } setMinor(minorCode, msg); initCause(null); hasCustomMessage = true; } /** * Prints this exception's stack trace to System.err. * If this exception has a root exception; the stack trace of the * root exception is printed to System.err instead. */ @Override public void printStackTrace() { printStackTrace( System.err ); } /** * Prints this exception's stack trace to a print stream. * If this exception has a root exception; the stack trace of the * root exception is printed to the print stream instead. * @param ps The non-null print stream to which to print. */ @Override public void printStackTrace(PrintStream ps) { if ( getCause() != null ) { String superString = getLocalMessage(); synchronized ( ps ) { ps.print(superString); ps.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); getCause().printStackTrace( ps ); } } else { super.printStackTrace( ps ); } } /** * Prints this exception's stack trace to a print writer. * If this exception has a root exception; the stack trace of the * root exception is printed to the print writer instead. * @param pw The non-null print writer to which to print. */ @Override public void printStackTrace(PrintWriter pw) { if ( getCause() != null ) { String superString = getLocalMessage(); synchronized (pw) { pw.print(superString); pw.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); getCause().printStackTrace( pw ); } } else { super.printStackTrace( pw ); } } @Override public String getMessage() { Throwable cause = getCause(); if (isBoring(this)) { return getUsefulMessage(cause); } else { StringBuilder message = new StringBuilder(super.getMessage()); if (cause != null) { message.append(" [Caused by: ").append(getUsefulMessage(cause)).append("]"); } return message.toString(); } } /** * Wrapper around getMessage method that tries to provide a meaningful * message. This is needed because many GSSException objects provide no * useful information and the actual useful information is in the Throwable * that caused the exception. */ private static String getUsefulMessage(Throwable throwable) { while(isBoring(throwable)) { throwable = throwable.getCause(); } String message = throwable.getMessage(); if (message == null) { message = throwable.getClass().getName(); } return message; } /** * Use heuristics to determine whether the supplied Throwable has any * semantic content (i.e., does it provide any additional information). * * It seems that many GSSException objects are created with no information. * Instead, the useful information is contained within the causing * Throwable. * * Also, an SSLException may be thrown by SSLEngine that wraps some more * interesting exception but the message has no information. * * As part of a work-around for this problem, this method tries to guess * whether the supplied Throwable contains useful information. * * @return true if the Throwable contains no useful information, false * otherwise. */ private static boolean isBoring(Throwable t) { // Last throwable in the causal chain is never boring. if (t.getCause() == null) { return false; } // Some GSSExceptions have no semantic content, therefore boring. if (t instanceof GSSException) { GSSException g = (GlobusGSSException) t; if (g.getMajor() == GSSException.FAILURE && g.getMinor() == 0) { if (g instanceof GlobusGSSException) { return !((GlobusGSSException)g).hasCustomMessage; } else { // Unfortunately, for GSSException, we must compare the // actual message. return g.getMessage().equals("Failure unspecified at GSS-API level"); } } } // SSLEngine can return a message with no meaning, therefore boring. if (t instanceof SSLException && t.getMessage().equals("General SSLEngine problem")) { return true; } return false; } private String getLocalMessage() { String message = super.getMessage(); return (message == null) ? getClass().getName() : message; } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/GlobusGSSManagerImpl.java000066400000000000000000000254441241116057200321620ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import org.globus.gsi.gssapi.jaas.JaasSubject; import java.io.InputStream; import java.io.FileInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.Provider; import java.util.Set; import java.util.Iterator; import javax.security.auth.Subject; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSContext; import org.ietf.jgss.Oid; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSCredential; import org.globus.gsi.X509Credential; import org.globus.gsi.CredentialException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * An implementation of GlobusGSSManager. */ public class GlobusGSSManagerImpl extends ExtendedGSSManager { private static Log logger = LogFactory.getLog(GlobusGSSManagerImpl.class.getName()); static final Oid[] MECHS; static { try { MECHS = new Oid[] {GSSConstants.MECH_OID}; } catch(Exception e) { throw new RuntimeException(e.getMessage()); } } private GlobusGSSCredentialImpl defaultCred; /** * Acquires GSI GSS credentials. * * @see #createCredential(GSSName, int, Oid, int) */ public GSSCredential createCredential (int usage) throws GSSException { return createCredential(null, GSSCredential.DEFAULT_LIFETIME, (Oid)null, usage); } /** Acquires GSI GSS credentials. First, it tries to find the credentials * in the private credential set of the current JAAS Subject. If the * Subject is not set or credentials are not found in the Subject, it * tries to get a default user credential (usually an user proxy file) * * @param lifetime Only lifetime set to * {@link GSSCredential#DEFAULT_LIFETIME * GSSCredential.DEFAULT_LIFETIME} is allowed. * @see org.globus.gsi.X509Credential#getDefaultCredential() */ public GSSCredential createCredential (GSSName name, int lifetime, Oid mech, int usage) throws GSSException { checkMechanism(mech); if (name != null) { if (name.isAnonymous()) { return new GlobusGSSCredentialImpl(); } else { throw new GSSException(GSSException.UNAVAILABLE); } } X509Credential cred = null; Subject subject = JaasSubject.getCurrentSubject(); if (subject != null) { logger.debug("Getting credential from context"); Set gssCreds = subject.getPrivateCredentials(GlobusGSSCredentialImpl.class); if (gssCreds != null) { Iterator iter = gssCreds.iterator(); if (iter.hasNext()) { GlobusGSSCredentialImpl credImpl = (GlobusGSSCredentialImpl)iter.next(); cred = credImpl.getX509Credential(); } } } if (lifetime == GSSCredential.INDEFINITE_LIFETIME || lifetime > 0) { // lifetime not supported throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "badLifetime01"); } if (cred == null) { logger.debug("Getting default credential"); try { cred = X509Credential.getDefaultCredential(); } catch(CredentialException e) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e); } catch(Exception e) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e); } return getDefaultCredential(cred, usage); } else { return new GlobusGSSCredentialImpl(cred, usage); } } private synchronized GSSCredential getDefaultCredential( X509Credential cred, int usage) throws GSSException { if (this.defaultCred != null && this.defaultCred.getUsage() == usage && this.defaultCred.getX509Credential() == cred) { return this.defaultCred; } else { this.defaultCred = new GlobusGSSCredentialImpl(cred, usage); return this.defaultCred; } } /** * Acquires GSI GSS credentials. * * @see #createCredential(GSSName, int, Oid, int) */ public GSSCredential createCredential(GSSName name, int lifetime, Oid mechs[], int usage) throws GSSException { if (mechs == null || mechs.length == 0) { return createCredential(name, lifetime, (Oid)null, usage); } else { // XXX: not sure this is correct GSSCredential cred = createCredential(name, lifetime, mechs[0], usage); for (int i = 1; i < mechs.length; i++) { cred.add(name, lifetime, lifetime, mechs[i], usage); } return cred; } } /** * Imports a credential. * * @param lifetime Only lifetime set to * {@link GSSCredential#DEFAULT_LIFETIME * GSSCredential.DEFAULT_LIFETIME} is allowed. */ public GSSCredential createCredential (byte[] buff, int option, int lifetime, Oid mech, int usage) throws GSSException { checkMechanism(mech); if (buff == null || buff.length < 1) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "invalidBuf"); } if (lifetime == GSSCredential.INDEFINITE_LIFETIME || lifetime > 0) { // lifetime not supported throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "badLifetime01"); } InputStream input = null; switch (option) { case ExtendedGSSCredential.IMPEXP_OPAQUE: input = new ByteArrayInputStream(buff); break; case ExtendedGSSCredential.IMPEXP_MECH_SPECIFIC: String s = new String(buff); int pos = s.indexOf('='); if (pos == -1) { throw new GSSException(GSSException.FAILURE); } String filename = s.substring(pos+1).trim(); try { input = new FileInputStream(filename); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } break; default: throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "unknownOption", new Object[] {new Integer(option)}); } X509Credential cred = null; try { cred = new X509Credential(input); } catch(CredentialException e) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e); } return new GlobusGSSCredentialImpl(cred, usage); } // for initiators public GSSContext createContext(GSSName peer, Oid mech, GSSCredential cred, int lifetime) throws GSSException { checkMechanism(mech); GlobusGSSCredentialImpl globusCred = null; if (cred == null) { globusCred = (GlobusGSSCredentialImpl)createCredential(GSSCredential.INITIATE_ONLY); } else if (cred instanceof GlobusGSSCredentialImpl) { globusCred = (GlobusGSSCredentialImpl)cred; } else { throw new GSSException(GSSException.NO_CRED); } GSSContext ctx = new GlobusGSSContextImpl(peer, globusCred); ctx.requestLifetime(lifetime); return ctx; } // for acceptors public GSSContext createContext(GSSCredential cred) throws GSSException { GlobusGSSCredentialImpl globusCred = null; if (cred == null) { globusCred = (GlobusGSSCredentialImpl)createCredential(GSSCredential.ACCEPT_ONLY); } else if (cred instanceof GlobusGSSCredentialImpl) { globusCred = (GlobusGSSCredentialImpl)cred; } else { throw new GSSException(GSSException.NO_CRED); } // XXX: don't know about the first argument GSSContext ctx = new GlobusGSSContextImpl(null, globusCred); return ctx; } public Oid[] getMechs() { return MECHS; } public GSSName createName(String nameStr, Oid nameType) throws GSSException { return new GlobusGSSName(nameStr, nameType); } /** * Checks if the specified mechanism matches * the mechanism supported by this implementation. * * @param mech mechanism to check * @exception GSSException if mechanism not supported. */ public static void checkMechanism(Oid mech) throws GSSException { if (mech != null && !mech.equals(GSSConstants.MECH_OID)) { throw new GSSException(GSSException.BAD_MECH); } } // ================================================================== // Not implemented below // ================================================================== /** * Currently not implemented. */ public GSSContext createContext(byte [] interProcessToken) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public Oid[] getNamesForMech(Oid mech) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public Oid[] getMechsForName(Oid nameType) { // not implemented, not needed by Globus return null; } /** * Currently not implemented. */ public GSSName createName(String nameStr, Oid nameType, Oid mech) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public GSSName createName(byte name[], Oid nameType) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public GSSName createName(byte name[], Oid nameType, Oid mech) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public void addProviderAtFront(Provider p, Oid mech) throws GSSException { // this GSSManager implementation does not support an SPI // with a pluggable provider architecture throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public void addProviderAtEnd(Provider p, Oid mech) throws GSSException { // this GSSManager implementation does not support an SPI // with a pluggable provider architecture throw new GSSException(GSSException.UNAVAILABLE); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/GlobusGSSName.java000066400000000000000000000313671241116057200306470ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import java.net.InetAddress; import java.net.UnknownHostException; import org.globus.common.CoGProperties; import org.globus.gsi.util.CertificateUtil; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSException; import org.ietf.jgss.Oid; import javax.security.auth.x500.X500Principal; import java.io.IOException; import java.io.Serializable; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.*; import java.util.regex.Pattern; /** * An implementation of GSSName. */ public class GlobusGSSName implements GSSName, Serializable { static class ReverseDNSCache { static class MapEntry { final Future hostName; Long inserted; public MapEntry(Future hostName, Long inserted) { this.hostName = hostName; this.inserted = inserted; } } // Use TreeMap to avoid clustering in any case final protected Map cache = new TreeMap(); final long duration; final ExecutorService threads = Executors.newCachedThreadPool(new ThreadFactory() { public Thread newThread(Runnable runnable) { Thread t = new Thread(runnable); t.setName("Reverse DNS request"); t.setDaemon(true); return t; } }); long oldest = System.currentTimeMillis(); public ReverseDNSCache(long duration) { this.duration = duration; } protected void enforceConstraints() { if(oldest + duration < System.currentTimeMillis()) { long newOldest = System.currentTimeMillis(); List toClear = new LinkedList(); for(Map.Entry e: cache.entrySet()) { if(e.getValue().inserted + duration < System.currentTimeMillis()) toClear.add(e.getKey()); else if(e.getValue().inserted < newOldest) newOldest = e.getValue().inserted; } for(String k: toClear) cache.remove(k); oldest = newOldest; } } protected synchronized Future getCached(final String ip) { MapEntry inCache = cache.get(ip); if(inCache == null) { Future name = threads.submit(new Callable() { public String call() throws Exception { return queryHost(ip); } }); inCache = new MapEntry(name, System.currentTimeMillis()); cache.put(ip, inCache); } else { inCache.inserted = System.currentTimeMillis(); } enforceConstraints(); return inCache.hostName; } public String resolve(String ip) throws UnknownHostException { try { return getCached(ip).get(); } catch(InterruptedException e) { throw new UnknownHostException(e.getMessage()); } catch(ExecutionException e) { throw new UnknownHostException(e.getMessage()); } } } static String queryHost(String name) throws UnknownHostException { InetAddress i = InetAddress.getByName(name); return InetAddress.getByName(i.getHostAddress()).getHostName(); } final static ReverseDNSCache reverseDNSCache = new ReverseDNSCache(CoGProperties.getDefault().getReveseDNSCacheLifetime()); protected Oid nameType; protected X500Principal name; // set toString called protected String globusID; // set when constructing with GSSName.NT_HOSTBASED_SERVICE as name type // or in the getter protected String hostBasedServiceCN; public GlobusGSSName() { this.nameType = GSSName.NT_ANONYMOUS; this.name = null; } public GlobusGSSName(X500Principal name) { if (name == null) { this.nameType = GSSName.NT_ANONYMOUS; } this.name = name; } public GlobusGSSName(byte[] name) { if (name == null) { this.nameType = GSSName.NT_ANONYMOUS; this.name = null; } else { this.name = new X500Principal(name); } } /** * Creates name from Globus DN * * @param name Globus DN (e.g. /C=US/O=Globus/..) If null * it is considered set as GSSName.ANONYMOUS name type. */ public GlobusGSSName(String name) throws GSSException { if (name == null) { this.nameType = GSSName.NT_ANONYMOUS; this.name = null; } else { try { this.name = CertificateUtil.toPrincipal(name); } catch (Exception e) { throw new GlobusGSSException(GSSException.BAD_NAME, e); } } } /** * Creates name from X509 name of specified type. * * @param name * Globus DN (e.g. /C=US/O=Globus/..) or service@host name. If null * it is considered set as GSSName.ANONYMOUS name type. * @param nameType name type. Only GSSName.NT_ANONYMOUS * or GSSName.NT_HOSTBASED_SERVICE is supported. * Maybe be null. */ public GlobusGSSName(String name, Oid nameType) throws GSSException { if (name == null) { if (nameType != null && !nameType.equals(GSSName.NT_ANONYMOUS)) { throw new GSSException(GSSException.BAD_NAMETYPE); } this.name = null; this.nameType = GSSName.NT_ANONYMOUS; } else { if (nameType != null) { if (nameType.equals(GSSName.NT_HOSTBASED_SERVICE)) { int atPos = name.indexOf('@'); if (atPos == -1 || (atPos+1 >= name.length())) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_NAME, "badName00"); } // performs reverse DNS lookup String host = name.substring(atPos+1); try { if (CoGProperties.getDefault().getReverseDNSCacheType().equals(CoGProperties.THREADED_CACHE)) { host = reverseDNSCache.resolve(host); } else { host = queryHost(host); } } catch (UnknownHostException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } hostBasedServiceCN = name.substring(0, atPos) + "/" + host; this.name = new X500Principal("CN=" + hostBasedServiceCN); } else { throw new GSSException(GSSException.BAD_NAMETYPE); } } else { try { this.name = CertificateUtil.toPrincipal(name); } catch (Exception e) { throw new GlobusGSSException(GSSException.BAD_NAME, e); } } this.nameType = nameType; } // both subject & nameType might be null } public boolean isAnonymous() { return (this.name == null); } public boolean isMN() { return true; } public boolean equals(GSSName another) throws GSSException { if (another == null) { return false; } if (isAnonymous()) { return another.isAnonymous(); } if (another.isAnonymous()) { return false; } if (!(another instanceof GlobusGSSName)) { throw new GSSException(GSSException.FAILURE); } GlobusGSSName other = (GlobusGSSName)another; // both are not anonymous // both have non-null subjects // nametypes might be different! (null) if ((nameType != null && nameType.equals(GSSName.NT_HOSTBASED_SERVICE)) || (other.nameType != null && other.nameType.equals(GSSName.NT_HOSTBASED_SERVICE))) { // perform host based comparison String hp1 = this.getHostBasedServiceCN(true); String hp2 = other.getHostBasedServiceCN(true); if (hp1 == null || hp2 == null) { // something is really wrong return false; } String service1 = getService(hp1); String service2 = getService(hp2); // service types do not match if (!service1.equalsIgnoreCase(service2)) { return false; } String host1 = getHost(hp1); String host2 = getHost(hp2); int i1=0; int i2=0; int s1 = host1.length(); int s2 = host2.length(); char h1; char h2; while (i1 < s1 && i2 < s2) { h1 = Character.toUpperCase(host1.charAt(i1)); h2 = Character.toUpperCase(host2.charAt(i2)); if (h1 == h2) { if (h1 == '.') { return host1.equalsIgnoreCase(host2); } i1++; i2++; } else if (h1 == '.' && h2 == '-') { return compareHost(host2, i2, host1, i1); } else if (h1 == '-' && h2 == '.') { return compareHost(host1, i1, host2, i2); } else { return false; } } return (i1 == i2); } else { // perform regular comparison // cross-check getStringNameType() // that's not implemented right now return toString().equalsIgnoreCase(another.toString()); } } /** * Returns globus ID string representation of the name. * If name represents is an anonymous name string * "" is returned. */ public String toString() { if (this.name == null) { return ""; } else { if (this.globusID == null) { this.globusID = CertificateUtil.toGlobusID(name); } return this.globusID; } } /** * Returns the CN corresponding to the host part of the DN * @param last true if the CN is assumed to be the last CN attribute * in the RFC 2253 formatted DN, else false to assume it is the first DN * attribute * @return the CN of the host based service */ protected String getHostBasedServiceCN(boolean last) { if (hostBasedServiceCN == null) { String dn = name.getName(); int cnStart; if (last) { // use the last instance of CN in the DN cnStart = dn.lastIndexOf("CN=") + 3; } else { // use the first instance of CN in the DN cnStart = dn.indexOf("CN=") + 3; } if (cnStart == -1) { return null; } int cnEnd = dn.indexOf(",", cnStart); if (cnEnd == -1) { int nextAtt = dn.indexOf("=", cnStart); if (nextAtt == -1) { // CN is the last attribute in the DN cnEnd = dn.length(); } else { // unexpected DN format (attributes not comma delimited) return null; } } hostBasedServiceCN = name.getName().substring(cnStart, cnEnd); } return hostBasedServiceCN; } private static String getService(String name) { int pos = name.indexOf('/'); return (pos == -1) ? "host" : name.substring(0, pos); } private static String getHost(String name) { int pos = name.indexOf('/'); return (pos == -1) ? name : name.substring(pos+1); } private static boolean compareHost(String host1, int i, String host2, int j) { if (host1.charAt(i) != '-') { throw new IllegalArgumentException(); } int size = host1.length(); while (i < size ) { if (host1.charAt(i) == '.') { break; } else { i++; } } if (size - i == host2.length() - j) { return host1.regionMatches(i, host2, j, size - i); } else { return false; } } // ---------------------------------- /** * Currently not implemented. */ public Oid getStringNameType() throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public byte[] export() throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } /** * Currently not implemented. */ public GSSName canonicalize(Oid mech) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE); } private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(this.nameType); oos.writeObject(name.getName()); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { this.nameType = (Oid)ois.readObject(); this.name = new X500Principal((String)ois.readObject()); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/JaasGssUtil.java000066400000000000000000000074251241116057200304250ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import org.globus.gsi.gssapi.jaas.GlobusPrincipal; import java.util.Set; import java.util.Iterator; import javax.security.auth.Subject; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSException; /** * An utility class for handling JAAS Subject with GSSCredential. */ public class JaasGssUtil { /** * Creates a new Subject object from specified * GSSCredential. The GSSCredential is added * to the private credential set of the Subject object. * Also, if the GSSCredential.getName() is of type * org.globus.gsi.gssapi.GlobusGSSName * a org.globus.gsi.jaas.GlobusPrincipal * is added to the principals set of the Subject object. */ public static Subject createSubject(GSSCredential cred) throws GSSException { return createSubject(null, cred); } /** * Creates a new Subject object from specified * GSSCredential and GSSName. * If the GSSCredential is specified it is added * to the private credential set of the Subject object. * Also, if the GSSCredential.getName() is of type * org.globus.gsi.gssapi.GlobusGSSName and the * GSSName parameter was not specified a * org.globus.gsi.jaas.GlobusPrincipal * is added to the principals set of the Subject object. * If the GSSName parameter was specified of type * org.globus.gsi.gssapi.GlobusGSSName a * org.globus.gsi.jaas.GlobusPrincipal * is added to the principals set of the Subject object. */ public static Subject createSubject(GSSName name, GSSCredential cred) throws GSSException { if (cred == null && name == null) { return null; } Subject subject = new Subject(); if (cred != null) { subject.getPrivateCredentials().add(cred); if (name == null) { GlobusPrincipal nm = toGlobusPrincipal(cred.getName()); subject.getPrincipals().add(nm); } } if (name != null) { GlobusPrincipal nm = toGlobusPrincipal(name); subject.getPrincipals().add(nm); } return subject; } /** * Converts the specified GSSName to GlobusPrincipal. * The GSSName is converted into the GlobusPrincipal * only if the GSSName is of type * org.globus.gsi.gssapi.GlobusGSSName * and the name is not anonymous. */ public static GlobusPrincipal toGlobusPrincipal(GSSName name) { return (!name.isAnonymous() && (name instanceof GlobusGSSName)) ? new GlobusPrincipal(name.toString()) : null; } /** * Retrieves the first GSSCredential from the * private credential set of the specified Subject * object. * * @return the GSSCredential. Might be null. */ public static GSSCredential getCredential(Subject subject) { if (subject == null) { return null; } Set gssCreds = subject.getPrivateCredentials(GSSCredential.class); if (gssCreds == null) { return null; } Iterator iter = gssCreds.iterator(); return (iter.hasNext()) ? (GSSCredential)iter.next() : null; } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/Java_GSI_GSSAPI.html000066400000000000000000000266771241116057200307220ustar00rootroot00000000000000Java GSI GSS-API Features and LimitationsJava GSI GSS-API  Implementation Features and Limitations

    The Java GSI implementation is an implementation of the Java GSS-API. It supports the GSS-API extensions and the new proxy certificate format specifications as defined by the Global Grid Forum. The implementation is based on JSSE (for SSL API) and the BouncyCastle library (for certificate processing API).

    Features:
    • Implements Java GSS-API
      • wrap/unwrap support SSL wrapped tokens
    • Implements most of the GSS-Extensions including:
      • Context options
        • Supports PROTECTION_FAIL_ON_CONTEXT_EXPIRATION (in Java GSI GSS-API called CHECK_CONTEXT_EXPIRATION)
        • Supports DISALLOW_ENCRYPTION (but only on a per-session basis)
        • Defined additional options: 
          • GSS_MODE
          • DELEGATION_TYPE
          • REJECT_LIMITED_PROXY
          • REQUIRE_CLIENT_AUTH
      • Delegation API
        • both wrapped and unwrapped mode (SSL compatible mode)
      • Import and export of credential
        • both opaque and mechanism specific data import/export
    • Starting with JGlobus 2.0, SHA-2 (specifically SHA-256, SHA-384 and SHA-512) certificates are also supported.
    • Supports GSI and SSL compatibility mode (set via context option interface - GSS_MODE)
    • Supports limited and full delegation both using initSecContext/acceptSecContext and initDelegation/acceptDelegation methods (set via context option interface - DELEGATION_TYPE)
    • Supports enabling / disabling checking of peer credential for limited proxy.
    • Supports enabling / disabling client authentication for acceptors (set via context option interface - REQUIRE_CLIENT_AUTH)
    • Supports checking GSSAPI credential usage, setting/getting context lifetime
    • Supports anonymous authentication and anonymous credentials
    • Supports internationalization of error messages
    • Supports authorization check (on the initiating side, hostbased service, identity, etc.)
    • Support certificate extension checking (certificate chain validation is performed by the ProxyPathValidation library)
      • BasicConstraints and KeyUsage certificate extension are checked.
      • Any certificates with unsupported critical extensions will be rejected.
    Changes in JGlobus 2.0 GSSAPI:
    • With the replacement of PureTLS with JSSE, SHA-2 (specifically SHA-256, SHA-384 and SHA-512) certificates are now supported.
    • getMIC() and verifyMIC() are no longer available because of the underlying JSSE constraints.
    • GSI_BIG QOP no longer available. wrap/unwrap can no longer switch between encrypted and unencrypted communication.
    • setOption(GSSConstants.TRUSTED_CERTIFICATES, TrustedCertificates) and the corresponding getOption no longer supported. Standard GSI mechanisms can be used to specify the Trusted Certificate folder, etc.
    • Previously deprecated setOption(GSSConstants.GRIM_POLICY_HANDLER, value) deleted.
    • GlobusGSSCredentialImpl.getGlobusCredential replaced with GlobusGSSCredentialImpl.getX509Credential
    • The "value" Object parameter to setOption(GSSConstants.DELEGATION_TYPE, value) should be of type GSIConstants.DelegationType, while Integer is supported as well for backward compatibility.
    • Confidentiality service changes/fixes
      • RFC definition
        • Per the GSSAPI Java bindings RFC, only Initiator is allowed to invoke requestConf(). No default specified by the RFC; however per C-bindings (and also implied by the name requestConf), default is taken to be "false".
        • Acceptor and Initiator can check if the established context provides confidentiality by checking the result of getConfState().
        • Ability to selectively apply confidentiality via MessageProp object passed to wrap().
      • GSS-API extensions
        • This document defines an id-gss-ext-context-opts-disallow-encryption option to a new gss_set_sec_context_option call that is available to Acceptor as well as Initiator. When set, this MUST cause the underlying GSS library to disallow any encryption of application data.
      • GSI C GSSAPI behavior
        • Confidentiality is off by default causing the null-encryption cipher suites to be added at the front of the list of cipher suites("eNULL:ALL:!ADH:RC4+RSA:+SSLv2").
        • Initiator or Acceptor can request confidentiality. If confidentiality is requested, the platform's default SSL cipher suite is used, which by default excludes the null-encryption ciphers.
        • Acceptor and Initiator can check if the established context provides confidentiality by checking the return_flags parameter to accept_sec_context() or init_sec_context() respectively. GSI_C_CONF_FLAG in return_flags is only set if the cipher suite uses encryption which is at least 56-bit.
        • Ability to selectively apply confidentiality, but only by requesting confidentiality at context establishment time and later selectively negating confidentiality by use of GSI_BIG QOP.
        • No enforcement of the id-gss-ext-context-opts-disallow-encryption option defined by the GSS-API extensions document
      • OLD JGlobus behavior
        • Confidentiality is ON by default but even when confidentiality is on, TLS_RSA_WITH_NULL_MD5 is added at the end resulting in confidentiality not being guaranteed.
        • Initiator or Acceptor able to explicitly request confidentiality using requestConf() but again this isn't guaranteed since the null cipher suite TLS_RSA_WITH_NULL_MD5 is always added at the end of the list of negotiable cipher suites. If confidentiality is turned off, then only the null cipher suite TLS_RSA_WITH_NULL_MD5 is enabled.
        • Initiator and Acceptor can check if the established context provides confidentiality by checking getConfState().
        • Ability to selectively apply confidentiality, but only by requesting confidentiality at context establishment time and later selectively negating confidentiality by use of GSI_BIG QOP.
        • No support for any equivalent of the id-gss-ext-context-opts-disallow-encryption option defined by the GSS-API extensions document
      • NEW JGlobus behavior
        • Confidentiality is OFF by default causing the null-encryption cipher suites to be added at the front of the list of cipher suites enabled by default by JSSE which are usually non-null cipher suites. This has been done to bring the implementation closer to the GSI C version.
        • Initiator or Acceptor able to request confidentiality using requestConf() in which case only the cipher suites enabled by default by JSSE which are non-null by default are used.
        • In other words:
          • Setting requestConf(true) will cause:
            • cipher suites enabled by default by JSSE to be left enabled
            • TLS_RSA_WITH_NULL_MD5 to no longer be added at the end of enabled cipher suites.
            • NOTE: Requesting confidentiality by invoking requestConf(true) before context establishment does NOT guarantee that confidentiality has been negotiated. Where confidentiality is required, the caller MUST verify after context establishment that confidentiality is available by checking the return value of getConfState().
          • Setting requestConf(false) will cause:
            • the NULL cipher suites SSL_RSA_WITH_NULL_SHA, SSL_RSA_WITH_NULL_MD5 to be enabled
            • all the default JSSE-enabled cipher suites (non-NULL by default) to then be added.
        • Acceptor and Initiator can check if the established context in fact provides confidentiality by checking getConfState().
        • Ability to selectively apply confidentiality no longer available as GSI_BIG QOP is no longer supported.
        • GRAM Contraints: Communication with GRAM servers will currently only succeed with SSLv3 and a narrow set of cipher suites. So, applications attempting communication with GRAM must first invoke GSSContext.setOption(FORCE_SSLV3_AND_CONSTRAIN_CIPHERSUITES_FOR_GRAM, Boolean.TRUE) to force the GSSAPI layer to constrain JSSE to SSLv3 and SSL_RSA_WITH_3DES_EDE_CBC_SHA when confidentiality is requested via requestConf() and SSL_RSA_WITH_NULL_SHA otherwise.
        • WARNING: Applications that require confidentiality are supposed to check GSSContext.getConfState() after context establishment to make sure the confidentiality service is in fact available but none of them in jGlobus appear to do so!
        • No support for any equivalent of the id-gss-ext-context-opts-disallow-encryption option defined by the GSS-API extensions document
    Clarification:
    • setOption(GSSConstants.REQUIRE_CLIENT_AUTH, true) and setOption(GSSConstants.ACCEPT_NO_CLIENT_CERTS, true) will cause the former setting to take precedence; in other words client authentication will be "required".
    • setOption(GSSConstants.REQUIRE_CLIENT_AUTH, false) will cause the setting setOption(GSSConstants.ACCEPT_NO_CLIENT_CERTS, Boolean) to take precedence; "true" will cause client authentication to be "requested" but not required and "false" will cause client authentication to be not desired.
    Limitations:
    • No GAA support. Additional certificate chain validation is performed by the ProxyPathValidation library (this is performed after the SSL library verified the chain)
    • Only looks for a proxy file when asked to load default credentials.
    • Does not support protection key parameter to credential import and export API
    • Does not support extensions parameters in the delegation API
    • There is a few unimplemented methods (e.g.in GSSContext: getWrapSizeLimit(),  export(), isTransferable(), etc) All unimplemented methods return GSSException.UNAVAILABLE error and are marked as unimplemented in JavaDoc. Most of stream based operations defined in Java GSS-API are not implemented (but can be implemented easily)
    • The org.ietf.jgss.Oid is not completely implemented (this might be a problem if the library is used with Java 1.3.x, that class is built in with Java 1.4.x)
    Versions of software used:
    • PureTLS: puretls-0.9b4 with a few custom modifications
    • Cryptix: 3.2 (PureTLS depends on it)
    • Cryptix ASN.1 Kit (Custom version provided by PureTLS)
    • BouncyCastle: 1.17

    JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/KeyPairCache.java000066400000000000000000000114321241116057200305150ustar00rootroot00000000000000package org.globus.gsi.gssapi; import java.util.Map; import java.util.Hashtable; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.common.CoGProperties; /** * Simple cache for key pairs. The cache is used to avoid excessive * CPU consumption from key pair generation. In particular for * purposes of delegation, reusing a key pair is safe. * * @author Gerd Behrmann (behrmann@ndgf.org) */ public class KeyPairCache { static class KeyPairCacheEntry { private long created_at; private KeyPair keys; public KeyPairCacheEntry(KeyPair keys, long created_at) { this.keys = keys; this.created_at = created_at; } public long getCreatedAt() { return created_at; } public KeyPair getKeyPair() { return keys; } } private static Log logger = LogFactory.getLog(GlobusGSSContextImpl.class.getName()); public static final String DEFAULT_ALGORITHM = "RSA"; public static final String DEFAULT_PROVIDER = "BC"; private final String algorithm; private final String provider; private final long lifetime; private static KeyPairCache keyPairCache; /** * Hash table of cache entries. The use of Hashtable * is significant, since we rely on access to the table being * synchronized. */ private final Map entries = new Hashtable(); /** * Creates a KeyPairCache object for the specified algorithm, as * supplied from the specified provider. * * @param algorithm the standard string name of the algorithm. See * Appendix A in the Java Cryptography Architecture API * Specification & Reference for information about standard * algorithm names. * @param provider the string name of the provider. * @param lifetime the lifetime of the cache in milliseconds. */ private KeyPairCache(String algorithm, String provider, long lifetime) { this.algorithm = algorithm; this.provider = provider; this.lifetime = lifetime; } public static synchronized KeyPairCache getKeyPairCache() { if (keyPairCache == null) { keyPairCache = new KeyPairCache(DEFAULT_ALGORITHM, DEFAULT_PROVIDER, CoGProperties.getDefault(). getDelegationKeyCacheLifetime()); } return keyPairCache; } public static synchronized KeyPairCache getKeyPairCache(String algorithm, String provider, long lifetime) { if (keyPairCache == null) { keyPairCache = new KeyPairCache(algorithm, provider, lifetime); } return keyPairCache; } /** * Returns a key pair of size bits. The same key pair * may be returned several times within a period of the cache * lifetime. * * If lifetime was set to zero or less than zero, no keys are cached. * * @param bits the keysize. This is an algorithm-specific metric, * such as modulus length, specified in number of bits. * @throws NoSuchAlgorithmException if the algorithm is not * available in the environment. * @throws NoSuchProviderException if the provider is not * available in the environment. */ public KeyPair getKeyPair(int bits) throws NoSuchAlgorithmException, NoSuchProviderException { if (this.lifetime < 1) { logger.debug("Cache lifetime is less than 1, generating new " + "keypair each time"); KeyPairGenerator generator = KeyPairGenerator.getInstance(this.algorithm, this.provider); generator.initialize(bits); return generator.generateKeyPair(); } long st = System.currentTimeMillis(); Integer keysize = new Integer(bits); KeyPairCacheEntry entry = (KeyPairCacheEntry)entries.get(keysize); if (entry == null || st - entry.getCreatedAt() >= lifetime) { logger.debug("Creating " + bits + " bits keypair"); KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm, provider); generator.initialize(bits); logger.debug("Time to generate key pair: " + (System.currentTimeMillis() - st)); entry = new KeyPairCacheEntry(generator.generateKeyPair(), st); entries.put(keysize, entry); } return entry.getKeyPair(); } }JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/SSLUtil.java000066400000000000000000000151331241116057200275260ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; /** * A collection of SSL-protocol related functions. */ public class SSLUtil { /** * Reads some number of bytes from the input stream. * This function reads maximum data available on the * stream. * * @param in the input stream to read the bytes from. * @param buf the buffer into which read the data is read. * @param off the start offset in array b at which the data is written. * @param len the maximum number of bytes to read. * @exception IOException if I/O error occurs. */ public static int read(InputStream in, byte [] buf, int off, int len) throws IOException { int n = 0; while (n < len) { int count = in.read(buf, off + n, len - n); if (count < 0) { return count; } n += count; } return len; } /** * Reads some number of bytes from the input stream. * This function blocks until all data is read or an I/O * error occurs. * * @param in the input stream to read the bytes from. * @param buf the buffer into which read the data is read. * @param off the start offset in array b at which the data is written. * @param len the maximum number of bytes to read. * @exception IOException if I/O error occurs. */ public static void readFully(InputStream in, byte [] buf, int off, int len) throws IOException { int n = 0; while (n < len) { int count = in.read(buf, off + n, len - n); if (count < 0) throw new EOFException(); n += count; } } /** * Reads an entire SSL message from the specified * input stream. * * @param in the input stream to read the SSL message * from. * @return the byte array containing the SSL message * @exception IOException if I/O error occurs. */ public static byte[] readSslMessage(InputStream in) throws IOException { byte [] header = new byte[5]; readFully(in, header, 0, header.length); int length; if (isSSLv3Packet(header)) length = toShort(header[3], header[4]); else if (isSSLv2HelloPacket(header)) length = (((header[0] & 0x7f) << 8) | (header[1] & 0xff)) - 3; else { throw new IOException("Invalid SSL header"); } byte [] inToken = new byte[header.length + length]; System.arraycopy(header, 0, inToken, 0, header.length); readFully(in, inToken, header.length, length); return inToken; } /** * Determines if a given header is a SSL packet * (has a SSL header) * * @return true if the header is a SSL header. False, otherwise. */ public static final boolean isSSLPacket(byte[] header) { return ( isSSLv3Packet(header) || isSSLv2HelloPacket(header) ); } /** * Determines if a given header is a SSLv3 packet * (has a SSL header) or a backward compatible version of TLS * using the same header format. * * @return true if the header is a SSLv3 header. False, otherwise. */ public static final boolean isSSLv3Packet(byte[] header) { return header[0] >= 20 && header[0] <= 26 && (header[1] == 3 || (header[1] == 2 && header[2] == 0)); } /** * Determines if a given header is a SSLv2 client or server hello packet * * @return true if the header is such a SSLv2 client or server hello * packet. False, otherwise. */ public static final boolean isSSLv2HelloPacket(byte[] header) { return ((header[0] & 0x80) != 0 && (header[2] == 1 || header[2] == 4)); } /** * Converts 2 bytes to a short. * * @param a byte 1 * @param b byte 2 * @return the short value of the 2 bytes */ public static short toShort(byte a, byte b) { return (short)((a << 8) | (b & 0xff)); } /** * Converts 2 bytes to a * unsigned short. * * @param a byte 1 * @param b byte 2 * @return the unsigned short value of the 2 bytes */ public static int toUnsignedShort(byte a, byte b) { int n; n = (a & 0xff) << 8; n |= (b & 0xff); return n; } /** * Converts 4 bytes to an int at * the specified offset in the given byte array. * * @param buf the byte array containing the 4 bytes * to be converted to an int. * @param off offset in the byte array * @return the int value of the 4 bytes. */ public static int toInt(byte[] buf, int off) { int lg = (buf[off] & 0xff) << 24; lg |= (buf[off+1] & 0xff) << 16; lg |= (buf[off+2] & 0xff) << 8; lg |= (buf[off+3] & 0xff); return lg; } /** * Converts the specified int value into * 4 bytes. The bytes are put into the * specified byte array at a given offset * location. * * @param v the int value to convert into 4 bytes. * @param buf the byte array to put the resulting * 4 bytes. * @param off offset in the byte array */ public static void writeInt(int v, byte[] buf, int off) { buf[off] = (byte)((v >>> 24) & 0xFF); buf[off+1] = (byte)((v >>> 16) & 0xFF); buf[off+2] = (byte)((v >>> 8) & 0xFF); buf[off+3] = (byte)((v >>> 0) & 0xFF); } /** * Converts 8 bytes to a long at the * specified offset in the given byte array. * * @param buf the byte array containing the 8 bytes * to be converted to a long. * @param off offset in the byte array * @return the long value of the 8 bytes. */ public static long toLong(byte[]buf, int off) { return ((long)(toInt(buf, off)) << 32) + (toInt(buf, off+4) & 0xFFFFFFFFL); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/TokenInputStream.java000066400000000000000000000064171241116057200315100ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi; import java.io.InputStream; import java.io.IOException; import java.util.LinkedList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Used as token-oriented input stream needed for SSL library I/O abstraction. */ public class TokenInputStream extends InputStream { private static Log logger = LogFactory.getLog(TokenInputStream.class.getName()); private LinkedList tokens; // list of buffers private byte [] buff; // current buffer private int index; // position within current buffer private boolean closed; public TokenInputStream() { this.tokens = new LinkedList(); this.index = 0; this.closed = false; } // main function public void putToken(byte [] buf, int off, int len) { if (buf == null || len <=0) { return; } if (logger.isDebugEnabled()) { logger.debug("put token: " + len); } byte[] localBuf = buf; if (off != 0) { localBuf = new byte[len]; System.arraycopy(buf, off, localBuf, 0, len); } synchronized(this) { if (this.buff == null || this.buff != null && this.buff.length == this.index) { this.buff = localBuf; this.index = 0; } else { this.tokens.add(localBuf); } notify(); } } public int read(byte [] data) throws IOException { return read(data, 0, data.length); } public int read(byte [] data, int off, int len) throws IOException { if (logger.isDebugEnabled()) { logger.debug("read byte array: " + len); } if (!checkData()) { return -1; } int size = Math.min(len, buff.length-index); System.arraycopy(buff, index, data, off, size); index += size; return size; } public int read() throws IOException { logger.debug("read byte"); if (!checkData()) { return -1; } return buff[index++] & 0xff; } protected synchronized boolean checkData() { try { while(!hasData()) { wait(); if (closed) { return false; } } } catch(Exception e) { return false; } return true; } protected boolean hasData() { if (this.buff == null) { return false; } if (this.buff.length == this.index) { if (tokens.isEmpty()) { return false; } else { this.buff = (byte[])tokens.removeFirst(); this.index = 0; return true; } } return true; } public int available() throws IOException { if (!hasData()) { return 0; } else { return buff.length-index; } } public void close() throws IOException { logger.debug("close() called"); synchronized(this) { this.closed = true; notify(); } } public String toString() { return tokens.toString() + " " + index + " " + buff.length; } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/000077500000000000000000000000001241116057200263225ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/Authorization.java000066400000000000000000000036061241116057200320320ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.auth; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSName; /** * Interface for authorization mechanisms. * The authorization is performed once the connection was authenticated. */ public abstract class Authorization { /** * Performes authorization checks. Throws * AuthorizationException if the authorization fails. * Otherwise, the function completes normally. * * @param context the securit context * @param host host address of the peer. * @exception AuthorizationException if the peer is * not authorized to access/use the resource. */ public abstract void authorize(GSSContext context, String host) throws AuthorizationException; protected void generateAuthorizationException(GSSName expected, GSSName target) throws AuthorizationException { String lineSep = System.getProperty("line.separator"); StringBuffer msg = new StringBuffer(); msg.append("Mutual authentication failed").append(lineSep) .append(" Expected target subject name=\"") .append(expected.toString()).append("\"") .append(lineSep) .append(" Target returned subject name=\"") .append(target.toString()) .append("\""); throw new AuthorizationException(msg.toString()); } } AuthorizationException.java000066400000000000000000000016211241116057200336250ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.auth; import org.globus.common.ChainedIOException; public class AuthorizationException extends ChainedIOException { public AuthorizationException(String msg) { super(msg); } public AuthorizationException(String msg, Throwable root) { super(msg, root); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/GSSAuthorization.java000066400000000000000000000023271241116057200324060ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.auth; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSCredential; /** * GSSAPI client authorization. */ public abstract class GSSAuthorization extends Authorization { /** * Returns expected GSSName used for authorization purposes. * Can returns null for self authorization. * * @param cred credentials used * @param host host address of the peer. * @exception GSSException if unable to create the name. */ public abstract GSSName getExpectedName(GSSCredential cred, String host) throws GSSException; } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/HostAuthorization.java000066400000000000000000000076221241116057200326720ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.auth; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements a simple host authorization mechanism. * The peer's host name (in FQDN form) is compared with the * host name specified in the peer's certificate chain. */ public class HostAuthorization extends GSSAuthorization { private static Log logger = LogFactory.getLog(HostAuthorization.class.getName()); public static final HostAuthorization ldapAuthorization = new HostAuthorization("ldap"); private String _service = null; private static HostAuthorization hostAuthorization; public HostAuthorization(String service) { _service = (service == null) ? "host" : service; } /** * Returns an instance of host authentication. * * @return an instance of this class initialized with * host as a service. */ public synchronized static HostAuthorization getInstance() { if (hostAuthorization == null) { hostAuthorization = new HostAuthorization("host"); } return hostAuthorization; } public GSSName getExpectedName(GSSCredential cred, String host) throws GSSException { GSSManager manager = ExtendedGSSManager.getInstance(); return manager.createName(_service + "@" + host, GSSName.NT_HOSTBASED_SERVICE); } /** * Performs host authentication. The hostname of the peer is * compared with the hostname specified in the peer's (topmost) * certificate in the certificate chain. The hostnames must * match exactly (in case-insensitive way) * * @param context the security context * @param host host address of the peer. * @exception AuthorizationException if the hostnames * do not match. */ public void authorize(GSSContext context, String host) throws AuthorizationException { logger.debug("Authorization: HOST"); try { GSSName expected = getExpectedName(null, host); GSSName target = null; if (context.isInitiator()) { target = context.getTargName(); } else { target = context.getSrcName(); } if (!expected.equals(target)) { generateAuthorizationException(expected, target); } } catch (GSSException e) { throw new AuthorizationException("Authorization failure", e); } } public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof HostAuthorization) { HostAuthorization other = (HostAuthorization)o; if (this._service == null) { return (other._service == null); } else { return this._service.equals(other._service); } } return false; } public int hashCode() { return (this._service == null) ? 0 : this._service.hashCode(); } } HostOrSelfAuthorization.java000066400000000000000000000056251241116057200337270ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.auth; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class HostOrSelfAuthorization extends GSSAuthorization { private static Log logger = LogFactory.getLog(HostOrSelfAuthorization.class.getName()); private static HostOrSelfAuthorization authorization; private HostAuthorization hostAuthz; /** * Returns a single instance of this class. * * @return the instance of this class. */ public synchronized static HostOrSelfAuthorization getInstance() { if (authorization == null) { authorization = new HostOrSelfAuthorization("host"); } return authorization; } public HostOrSelfAuthorization(String service) { if (service == null) { service = "host"; } this.hostAuthz = new HostAuthorization(service); } // returning null for now. public GSSName getExpectedName(GSSCredential cred, String host) throws GSSException { return null; } /** * Performs host authorization. If that fails, performs self authorization */ public void authorize(GSSContext context, String host) throws AuthorizationException { logger.debug("Authorization: HOST/SELF"); try { GSSName expected = this.hostAuthz.getExpectedName(null, host); GSSName target = null; if (context.isInitiator()) { target = context.getTargName(); } else { target = context.getSrcName(); } if (!expected.equals(target)) { logger.debug("Host authorization failed. Expected " + expected + " target is " + target); if (!context.getSrcName().equals(context.getTargName())) { if (context.isInitiator()) { expected = context.getSrcName(); } else { expected = context.getTargName(); } generateAuthorizationException(expected, target); } } } catch (GSSException e) { throw new AuthorizationException("Authorization failure", e); } } } IdentityAuthorization.java000066400000000000000000000076431241116057200334720ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.auth; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements a simple identity authorization mechanism. * The given identify is compared with the peer's identity. */ public class IdentityAuthorization extends GSSAuthorization { private static Log logger = LogFactory.getLog(IdentityAuthorization.class.getName()); protected String _identity; /** * Constructor used by superclasses. */ protected IdentityAuthorization() { } /** * Creates a new instance of this class with given * expected identity. * * @param identity the expected identity. Must not be null. */ public IdentityAuthorization(String identity) { setIdentity(identity); } /** * Sets the expected identity for the authorization * check. * * @param identity the expected identity. Must not be null. */ public void setIdentity(String identity) { if (identity == null) { throw new IllegalArgumentException("Identity cannot be null"); } _identity = identity; } /** * Returns the expected identity. * * @return the expected identity. */ public String getIdentity() { return _identity; } public GSSName getExpectedName(GSSCredential cred, String host) throws GSSException { GSSManager manager = ExtendedGSSManager.getInstance(); return manager.createName(_identity, null); } /** * Performs identity authorization. The given identity is compared * with the peer's identity. * * @param context the security context * @param host host address of the peer. * @exception AuthorizationException if the peer's * identity does not match the expected identity. */ public void authorize(GSSContext context, String host) throws AuthorizationException { logger.debug("Authorization: IDENTITY"); try { GSSName expected = getExpectedName(null, host); GSSName target = null; if (context.isInitiator()) { target = context.getTargName(); } else { target = context.getSrcName(); } if (!expected.equals(target)) { generateAuthorizationException(expected, target); } } catch (GSSException e) { throw new AuthorizationException("Authorization failure", e); } } public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof IdentityAuthorization) { IdentityAuthorization other = (IdentityAuthorization)o; if (this._identity == null) { return (other._identity == null); } else { return this._identity.equals(other._identity); } } return false; } public int hashCode() { return (this._identity == null) ? 0 : this._identity.hashCode(); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/NoAuthorization.java000066400000000000000000000035361241116057200323310ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.auth; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the simplest authorization mechanism that does * not do any authorization checks. */ public class NoAuthorization extends GSSAuthorization { private static Log logger = LogFactory.getLog(NoAuthorization.class.getName()); private static NoAuthorization authorization; /** * Returns a single instance of this class. * * @return the instance of this class. */ public synchronized static NoAuthorization getInstance() { if (authorization == null) { authorization = new NoAuthorization(); } return authorization; } /** * Always returns null. */ public GSSName getExpectedName(GSSCredential cred, String host) throws GSSException { return null; } /** * Performs no authorization checks. The function is always * successful. It does not throw any exceptions. * */ public void authorize(GSSContext context, String host) throws AuthorizationException { logger.debug("Authorization: NONE"); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/auth/SelfAuthorization.java000066400000000000000000000047501241116057200326450ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.auth; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Performs the identity authorization check. The identity * is obtained from specified Globus credentials. */ public class SelfAuthorization extends GSSAuthorization { private static Log logger = LogFactory.getLog(SelfAuthorization.class.getName()); private static SelfAuthorization authorization; /** * Returns a single instance of this class. * * @return the instance of this class. */ public synchronized static SelfAuthorization getInstance() { if (authorization == null) { authorization = new SelfAuthorization(); } return authorization; } public GSSName getExpectedName(GSSCredential cred, String host) throws GSSException { if (cred == null) { GSSManager manager = ExtendedGSSManager.getInstance(); cred = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT); } return cred.getName(); } /** * Performs self authorization. */ public void authorize(GSSContext context, String host) throws AuthorizationException { logger.debug("Authorization: SELF"); try { if (!context.getSrcName().equals(context.getTargName())) { GSSName expected = null; GSSName target = null; if (context.isInitiator()) { expected = context.getSrcName(); target = context.getTargName(); } else { expected = context.getTargName(); target = context.getSrcName(); } generateAuthorizationException(expected, target); } } catch (GSSException e) { throw new AuthorizationException("Authorization failure", e); } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/example/000077500000000000000000000000001241116057200270145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/example/GetOpts.java000066400000000000000000000061751241116057200312550ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.example; import org.ietf.jgss.GSSContext; public class GetOpts { public boolean conf = true; public int lifetime = GSSContext.DEFAULT_LIFETIME; public boolean gsiMode = true; public boolean deleg = false; public boolean limitedDeleg = true; public boolean rejectLimitedProxy = false; public boolean anonymity = false; public String auth = null; protected String usage; protected String helpMsg; public GetOpts(String usage, String helpMsg) { this.usage = usage; this.helpMsg = helpMsg; } public int parse(String[] args) { int i = 0; for (i=0;i args.length) { System.err.println(usage); return; } String host = args[pos]; int port = Integer.parseInt(args[pos+1]); // to make sure we use right impl GSSManager manager = new GlobusGSSManagerImpl(); ExtendedGSSContext context = null; Socket s = null; try { s = SocketFactory.getDefault().createSocket(host, port); OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); byte [] inToken = new byte[0]; byte [] outToken = null; GSSName targetName = null; if (opts.auth != null) { if (opts.auth.equals("host")) { targetName = manager.createName("host@" + host, GSSName.NT_HOSTBASED_SERVICE); } else if (opts.auth.equals("self")) { targetName = manager.createCredential(GSSCredential.INITIATE_ONLY).getName(); } else { targetName = manager.createName(opts.auth, null); } } context = (ExtendedGSSContext)manager.createContext(targetName, GSSConstants.MECH_OID, null, opts.lifetime); context.requestCredDeleg(opts.deleg); context.requestConf(opts.conf); context.requestAnonymity(opts.anonymity); context.setOption(GSSConstants.GSS_MODE, (opts.gsiMode) ? GSIConstants.MODE_GSI : GSIConstants.MODE_SSL); if (opts.deleg) { context.setOption(GSSConstants.DELEGATION_TYPE, (opts.limitedDeleg) ? GSIConstants.DELEGATION_TYPE_LIMITED : GSIConstants.DELEGATION_TYPE_FULL); } context.setOption(GSSConstants.REJECT_LIMITED_PROXY, new Boolean(opts.rejectLimitedProxy)); // Loop while there still is a token to be processed while (!context.isEstablished()) { outToken = context.initSecContext(inToken, 0, inToken.length); if (outToken != null) { out.write(outToken); out.flush(); } if (!context.isEstablished()) { inToken = SSLUtil.readSslMessage(in); } } System.out.println("Context established."); System.out.println("Initiator : " + context.getSrcName()); System.out.println("Acceptor : " + context.getTargName()); System.out.println("Lifetime : " + context.getLifetime()); System.out.println("Privacy : " + context.getConfState()); System.out.println("Anonymity : " + context.getAnonymityState()); String msg = "POST ping/jobmanager HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Content-Type: application/x-globus-gram\r\n" + "Content-Length: 0\r\n\r\n"; byte [] tmp = msg.getBytes(); outToken = context.wrap(tmp, 0, tmp.length, null); out.write(outToken); out.flush(); inToken = SSLUtil.readSslMessage(in); outToken = context.unwrap(inToken, 0, inToken.length, null); System.out.println(new String(outToken)); } catch (Exception e) { e.printStackTrace(); } finally { if (s != null) { try { s.close(); } catch(Exception e) {} } if (context != null) { try { System.out.println("closing..."); context.dispose(); } catch (Exception e) { e.printStackTrace(); } } } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/example/GssServer.java000066400000000000000000000111021241116057200315750ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.example; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.globus.gsi.gssapi.SSLUtil; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.GlobusGSSManagerImpl; import org.globus.gsi.GSIConstants; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSCredential; import org.gridforum.jgss.ExtendedGSSContext; import java.io.OutputStream; import java.io.InputStream; import java.net.Socket; import java.net.ServerSocket; public class GssServer { private static final String helpMsg = "Where options are:\n" + " -gss-mode mode\t\t\tmode is: 'ssl' or 'gsi' (default)\n" + " -deleg-type type\t\ttype is: 'none', 'limited' (default), or 'full'\n" + " -lifetime time\t\t\tLifetime of context. time is in seconds.\n" + " -rejectLimitedProxy\t\tEnables checking for limited proxies. By default off\n" + " -anonymous\t\t\tDo not require client authentication\n" + " -enable-conf\t\t\tEnables confidentiality (do encryption) (enabled by default)\n" + " -disable-conf\t\t\tDisables confidentiality (no encryption)"; public static void main(String [] args) { String usage = "Usage: java GssServer [options] [port]"; GetOpts opts = new GetOpts(usage, helpMsg); int pos = opts.parse(args); int port = 0; if (pos < args.length) { port = Integer.parseInt(args[pos]); } try { ServerSocket server = new ServerSocket(port); System.out.println("Server running at: " + server.getLocalPort()); while(true) { Client c = new Client(server.accept(), opts); c.start(); } } catch (Exception e) { e.printStackTrace(); } } } class Client extends Thread { GetOpts opts; Socket s; public Client(Socket s, GetOpts opts) { this.s = s; this.opts = opts; } public void run() { System.out.println("client connected"); // to make sure we use right impl GSSManager manager = new GlobusGSSManagerImpl(); ExtendedGSSContext context = null; try { OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); byte [] inToken = null; byte [] outToken = null; context = (ExtendedGSSContext)manager.createContext((GSSCredential)null); context.requestConf(opts.conf); context.setOption(GSSConstants.GSS_MODE, (opts.gsiMode) ? GSIConstants.MODE_GSI : GSIConstants.MODE_SSL); context.setOption(GSSConstants.REJECT_LIMITED_PROXY, new Boolean(opts.rejectLimitedProxy)); context.setOption(GSSConstants.REQUIRE_CLIENT_AUTH, new Boolean(!opts.anonymity)); // Loop while there still is a token to be processed while (!context.isEstablished()) { inToken = SSLUtil.readSslMessage(in); outToken = context.acceptSecContext(inToken, 0, inToken.length); if (outToken != null) { out.write(outToken); out.flush(); } } System.out.println("Context established."); System.out.println("Initiator : " + context.getSrcName()); System.out.println("Acceptor : " + context.getTargName()); System.out.println("Lifetime : " + context.getLifetime()); System.out.println("Privacy : " + context.getConfState()); GlobusGSSCredentialImpl cred = (GlobusGSSCredentialImpl)context.getDelegCred(); System.out.println("Delegated credential :"); if (cred != null) { System.out.println(cred.getX509Credential()); } else { System.out.println("None"); } inToken = SSLUtil.readSslMessage(in); outToken = context.unwrap(inToken, 0, inToken.length, null); System.out.println(new String(outToken)); byte[] msg = "HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n".getBytes(); outToken = context.wrap(msg, 0, msg.length, null); out.write(outToken); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { s.close(); } catch(Exception e) {} try { context.dispose(); } catch (Exception e) { e.printStackTrace(); } System.out.println("client disconnected"); } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/000077500000000000000000000000001241116057200261475ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/GssInputStream.java000066400000000000000000000054041241116057200317450ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net; import java.io.EOFException; import java.io.InputStream; import java.io.IOException; import org.globus.common.ChainedIOException; import org.globus.gsi.gssapi.ClosedGSSException; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSException; public abstract class GssInputStream extends InputStream { protected InputStream in; protected GSSContext context; protected byte [] buff; protected int index; public GssInputStream(InputStream in, GSSContext context) { this.in = in; this.context = context; this.buff = new byte[0]; this.index = 0; } protected byte[] unwrap(byte [] msg) throws IOException { try { return this.context.unwrap(msg, 0, msg.length, null); } catch (ClosedGSSException e) { throw new EOFException("Remote host terminated connection"); } catch (GSSException e) { throw new ChainedIOException("unwrap failed", e); } } protected abstract void readMsg() throws IOException; public int read(byte [] data) throws IOException { return read(data, 0, data.length); } public int read(byte [] data, int off, int len) throws IOException { if (!hasData()) { return -1; } int max = (index + len > buff.length) ? buff.length - index : len; System.arraycopy(buff, index, data, off, max); index += max; return max; } public int read() throws IOException { if (!hasData()) { return -1; } return buff[index++] & 0xff; } protected boolean hasData() throws IOException { if (this.buff == null) { return false; } if (this.buff.length == this.index) { try { readMsg(); } catch (EOFException e) { return false; } } if (this.buff == null) { return false; } return (this.buff.length != this.index); } /* does not dispose of the context */ public void close() throws IOException { this.buff = null; in.close(); } public int available() throws IOException { if (this.buff == null) { return -1; } int avail = this.buff.length - this.index; return (avail == 0) ? in.available() : avail; } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/GssOutputStream.java000066400000000000000000000056111241116057200321460ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net; import java.io.OutputStream; import java.io.IOException; import org.globus.common.ChainedIOException; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class GssOutputStream extends OutputStream { private static Log logger = LogFactory.getLog(GssOutputStream.class.getName()); protected OutputStream out; protected GSSContext context; protected boolean autoFlush = false; protected byte [] buff; protected int index; public GssOutputStream(OutputStream out, GSSContext context) { this(out, context, 16384); } public GssOutputStream(OutputStream out, GSSContext context, int size) { this.out = out; this.context = context; this.buff = new byte[size]; this.index = 0; } public void setAutoFlush(boolean autoFlush) { this.autoFlush = autoFlush; } public boolean getAutoFlush() { return this.autoFlush; } public void write(int b) throws IOException { if (this.index == this.buff.length) { flushData(); } buff[index++] = (byte)b; if (this.autoFlush) { flushData(); } } public void write(byte[] data) throws IOException { write(data, 0, data.length); } public void write(byte [] data, int off, int len) throws IOException { int max; while (len > 0) { if (this.index + len > this.buff.length) { max = (this.buff.length - this.index); System.arraycopy(data, off, this.buff, this.index, max); this.index += max; flushData(); len -= max; off += max; } else { System.arraycopy(data, off, this.buff, this.index, len); this.index += len; if (this.autoFlush) { flushData(); } break; } } } protected byte[] wrap() throws IOException { try { return context.wrap(this.buff, 0, this.index, null); } catch (GSSException e) { throw new ChainedIOException("wrap failed", e); } } public abstract void flush() throws IOException; private void flushData() throws IOException { flush(); this.index = 0; } public void close() throws IOException { logger.debug("close"); flushData(); this.out.close(); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/GssSocket.java000066400000000000000000000111721241116057200307210ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net; import java.net.Socket; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.globus.common.ChainedIOException; import org.globus.net.WrappedSocket; import org.globus.net.SocketFactory; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class GssSocket extends WrappedSocket { private static Log logger = LogFactory.getLog(GssSocket.class.getName()); protected GSSContext context; protected boolean clientMode; protected InputStream in; protected OutputStream out; protected Authorization authorization = SelfAuthorization.getInstance(); public static final int SSL_MODE = 1; public static final int GSI_MODE = 2; protected int mode = -1; public GssSocket(String host, int port, GSSContext context) throws IOException { this(SocketFactory.getDefault().createSocket(host, port), context); } public GssSocket(Socket socket, GSSContext context) { super(socket); this.context = context; this.clientMode = true; } public void setAuthorization(Authorization auth) { this.authorization = auth; } public Authorization getAuthorization() { return this.authorization; } public void setUseClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean getClientMode() { return this.clientMode; } public void setWrapMode(int mode) { this.mode = mode; } public int getWrapMode() { return this.mode; } public GSSContext getContext() { return this.context; } abstract protected void writeToken(byte [] token) throws IOException; abstract protected byte[] readToken() throws IOException; protected synchronized void authenticateClient() throws IOException, GSSException { byte [] outToken = null; byte [] inToken = new byte[0]; while (!this.context.isEstablished()) { outToken = this.context.initSecContext(inToken, 0, inToken.length); if (outToken != null) { writeToken(outToken); } if (!this.context.isEstablished()) { inToken = readToken(); } } } protected synchronized void authenticateServer() throws IOException, GSSException { byte [] outToken = null; byte [] inToken = null; while (!this.context.isEstablished()) { inToken = readToken(); outToken = this.context.acceptSecContext(inToken, 0, inToken.length); if (outToken != null) { writeToken(outToken); } } } public synchronized void startHandshake() throws IOException { if (this.context.isEstablished()) return; logger.debug("Handshake start"); try { if (this.clientMode) { authenticateClient(); } else { authenticateServer(); } } catch (GSSException e) { throw new ChainedIOException("Authentication failed", e); } logger.debug("Handshake end"); if (this.authorization != null) { logger.debug("Performing authorization."); this.authorization.authorize(this.context, getInetAddress().getHostAddress()); } else { logger.debug("Authorization not set"); } } public synchronized OutputStream getOutputStream() throws IOException { try { startHandshake(); return this.out; } catch (IOException e) { try { close(); } catch (IOException ioe) {} throw e; } } public synchronized InputStream getInputStream() throws IOException { try { startHandshake(); return this.in; } catch (IOException e) { try { close(); } catch (IOException ioe) {} throw e; } } /** * Disposes of the context and closes the connection */ public void close() throws IOException { try { this.context.dispose(); } catch (GSSException e) { throw new ChainedIOException("dispose failed.", e); } finally { this.socket.close(); } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/GssSocketFactory.java000066400000000000000000000037711241116057200322570ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net; import java.net.Socket; import java.io.IOException; import org.ietf.jgss.GSSContext; public abstract class GssSocketFactory { private static GssSocketFactory factory = null; public synchronized static GssSocketFactory getDefault() { if (factory == null) { String className = System.getProperty("org.globus.gsi.gssapi.net.provider"); if (className == null) { className = "org.globus.gsi.gssapi.net.impl.GSIGssSocketFactory"; } try { Class clazz = Class.forName(className); if (!GssSocketFactory.class.isAssignableFrom(clazz)) { throw new RuntimeException("Invalid GssSocketFactory provider class"); } factory = (GssSocketFactory)clazz.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to load '" + className + "' class: " + e.getMessage()); } catch (InstantiationException e) { throw new RuntimeException("Unable to instantiate '" + className + "' class: " + e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to instantiate '" + className + "' class: " + e.getMessage()); } } return factory; } public abstract Socket createSocket(Socket s, String host, int port, GSSContext context); public abstract Socket createSocket(String host, int port, GSSContext context) throws IOException; } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/example/000077500000000000000000000000001241116057200276025ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/example/GetOpts.java000066400000000000000000000024421241116057200320340ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net.example; import org.globus.gsi.gssapi.net.GssSocket; public class GetOpts extends org.globus.gsi.gssapi.example.GetOpts { public int wrapMode = GssSocket.SSL_MODE; public GetOpts(String usage, String helpMsg) { super(usage, helpMsg); } protected int parseArg(String[] args, int i) { if (args[i].equalsIgnoreCase("-wrap-mode")) { String arg = args[++i]; if (arg.equalsIgnoreCase("ssl")) { wrapMode = GssSocket.SSL_MODE; } else if (arg.equalsIgnoreCase("gsi")) { wrapMode = GssSocket.GSI_MODE; } else { error("Invalid -wrap-mode argument: " + arg); } return 1; } else { return super.parseArg(args, i); } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/example/GssClient.java000066400000000000000000000145451241116057200323510ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net.example; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.GlobusGSSManagerImpl; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.GSSAuthorization; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.globus.gsi.gssapi.auth.HostAuthorization; import org.globus.gsi.gssapi.auth.IdentityAuthorization; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSCredential; import org.gridforum.jgss.ExtendedGSSContext; import java.io.OutputStream; import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; public class GssClient { private static final String helpMsg = "Where options are:\n" + " -gss-mode mode\t\t\tmode is: 'ssl' or 'gsi' (default)\n" + " -deleg-type type\t\ttype is: 'none', 'limited' (default), or 'full'\n" + " -lifetime time\t\t\tLifetime of context. time is in seconds.\n" + " -rejectLimitedProxy\t\tEnables checking for limited proxies (off by default)\n" + " -anonymous\t\t\tDo not send certificates to the server\n" + " -enable-conf\t\t\tEnables confidentiality (do encryption) (enabled by default)\n" + " -disable-conf\t\t\tDisables confidentiality (no encryption)\n" + " -auth auth\t\t\tIf auth is 'host' host authorization will be performed.\n" + " \t\t\tIf auth is 'self' self authorization will be performed.\n" + " \t\t\tOtherwise, identity authorization is performed.\n" + " \t\t\tAuthorization is not performed by default.\n" + " -wrap-mode mode\t\tmode is: 'ssl' (default) or 'gsi'"; private Authorization auth; private GSSName targetName; private static GSSCredential cred; private static GSSCredential getCredential(GSSManager manager) throws Exception { // return null if needed to automatically reload the default creds if (cred == null) { cred = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT); } return cred; } public static void main(String [] args) { String usage = "Usage: java GssClient [options] host port"; GetOpts opts = new GetOpts(usage, helpMsg); int pos = opts.parse(args); if (pos + 2 > args.length) { System.err.println(usage); return; } String host = args[pos]; int port = Integer.parseInt(args[pos+1]); GssClient client = new GssClient(); Authorization auth = SelfAuthorization.getInstance(); if (opts.auth != null) { if (opts.auth.equals("host")) { client.auth = HostAuthorization.getInstance(); } else if (opts.auth.equals("self")) { client.auth = SelfAuthorization.getInstance(); } else { client.auth = new IdentityAuthorization(opts.auth); } } // XXX: When doing delegation targetName cannot be null. // additional authorization will be performed after the handshake // in the socket code. if (opts.deleg) { if (auth instanceof GSSAuthorization) { GSSAuthorization gssAuth = (GSSAuthorization)auth; try { client.targetName = gssAuth.getExpectedName(null, host); } catch (Exception e) { e.printStackTrace(); return; } } } client.connect(host, port, opts); } public void connect(String host, int port, GetOpts opts) { // to make sure we use right impl GSSManager manager = new GlobusGSSManagerImpl(); ExtendedGSSContext context = null; Socket s = null; try { context = (ExtendedGSSContext)manager.createContext( this.targetName, GSSConstants.MECH_OID, getCredential(manager), opts.lifetime); context.requestCredDeleg(opts.deleg); context.requestConf(opts.conf); context.requestAnonymity(opts.anonymity); context.setOption(GSSConstants.GSS_MODE, (opts.gsiMode) ? GSIConstants.MODE_GSI : GSIConstants.MODE_SSL); if (opts.deleg) { context.setOption(GSSConstants.DELEGATION_TYPE, (opts.limitedDeleg) ? GSIConstants.DELEGATION_TYPE_LIMITED : GSIConstants.DELEGATION_TYPE_FULL); } context.setOption(GSSConstants.REJECT_LIMITED_PROXY, new Boolean(opts.rejectLimitedProxy)); s = GssSocketFactory.getDefault().createSocket(host, port, context); ((GssSocket)s).setWrapMode(opts.wrapMode); ((GssSocket)s).setAuthorization(this.auth); OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); System.out.println("Context established."); System.out.println("Initiator : " + context.getSrcName()); System.out.println("Acceptor : " + context.getTargName()); System.out.println("Lifetime : " + context.getLifetime()); System.out.println("Privacy : " + context.getConfState()); System.out.println("Anonymity : " + context.getAnonymityState()); String msg = "POST ping/jobmanager HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Content-Type: application/x-globus-gram\r\n" + "Content-Length: 0\r\n\r\n"; byte [] tmp = msg.getBytes(); out.write(tmp); out.flush(); String line = null; BufferedReader r = new BufferedReader(new InputStreamReader(in)); while ( (line = r.readLine()) != null ) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } finally { if (s != null) { try { s.close(); } catch(Exception e) {} } } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/example/GssServer.java000066400000000000000000000120131241116057200323650ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net.example; import org.globus.net.ServerSocketFactory; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.GlobusGSSManagerImpl; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.globus.gsi.gssapi.net.GssSocket; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSCredential; import org.gridforum.jgss.ExtendedGSSContext; import java.io.OutputStream; import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; import java.net.ServerSocket; public class GssServer { private static final String helpMsg = "Where options are:\n" + " -gss-mode mode\t\t\tmode is: 'ssl' or 'gsi' (default)\n" + " -deleg-type type\t\ttype is: 'none', 'limited' (default), or 'full'\n" + " -lifetime time\t\t\tLifetime of context. time is in seconds.\n" + " -rejectLimitedProxy\t\tEnables checking for limited proxies. By default off\n" + " -anonymous\t\t\tDo not require client authentication\n" + " -enable-conf\t\t\tEnables confidentiality (do encryption) (enabled by default)\n" + " -disable-conf\t\t\tDisables confidentiality (no encryption)\n" + " -wrap-mode mode\t\tmode is: 'ssl' (default) or 'gsi'"; public static void main(String [] args) { String usage = "Usage: java GssServer [options] [port]"; GetOpts opts = new GetOpts(usage, helpMsg); int pos = opts.parse(args); int port = 0; if (pos < args.length) { port = Integer.parseInt(args[pos]); } ServerSocketFactory factory = ServerSocketFactory.getDefault(); try { ServerSocket server = factory.createServerSocket(port); System.out.println("Server running at: " + server.getLocalPort()); while(true) { Client c = new Client(server.accept(), opts); c.start(); } } catch (Exception e) { e.printStackTrace(); } } } class Client extends Thread { GetOpts opts; Socket s; private static GSSCredential cred; public Client(Socket s, GetOpts opts) { this.s = s; this.opts = opts; } private static GSSCredential getCredential(GSSManager manager) throws Exception { // return null if needed to automatically reload the default creds if (cred == null) { cred = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT); } return cred; } public void run() { System.out.println("client connected"); // to make sure we use right impl GSSManager manager = new GlobusGSSManagerImpl(); ExtendedGSSContext context = null; try { GSSCredential credd = getCredential(manager); context = (ExtendedGSSContext)manager.createContext(credd); context.requestConf(opts.conf); context.setOption(GSSConstants.GSS_MODE, (opts.gsiMode) ? GSIConstants.MODE_GSI : GSIConstants.MODE_SSL); context.setOption(GSSConstants.REJECT_LIMITED_PROXY, new Boolean(opts.rejectLimitedProxy)); context.setOption(GSSConstants.REQUIRE_CLIENT_AUTH, new Boolean(!opts.anonymity)); s = GssSocketFactory.getDefault().createSocket(s, null, 0, context); // server socket ((GssSocket)s).setUseClientMode(false); ((GssSocket)s).setWrapMode(opts.wrapMode); OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); System.out.println("Context established."); System.out.println("Initiator : " + context.getSrcName()); System.out.println("Acceptor : " + context.getTargName()); System.out.println("Lifetime : " + context.getLifetime()); System.out.println("Privacy : " + context.getConfState()); GlobusGSSCredentialImpl cred = (GlobusGSSCredentialImpl)context.getDelegCred(); System.out.println("Delegated credential :"); if (cred != null) { System.out.println(cred.getX509Credential()); } else { System.out.println("None"); } String line = null; BufferedReader r = new BufferedReader(new InputStreamReader(in)); while ( (line = r.readLine()) != null ) { if (line.length() == 0) { break; } System.out.println(line); } byte[] msg = "HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n".getBytes(); out.write(msg); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { s.close(); } catch(Exception e) {} System.out.println("client disconnected"); } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/impl/000077500000000000000000000000001241116057200271105ustar00rootroot00000000000000GSIGssInputStream.java000066400000000000000000000071471241116057200332000ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/impl/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net.impl; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssInputStream; import org.globus.gsi.gssapi.SSLUtil; import org.ietf.jgss.GSSContext; public class GSIGssInputStream extends GssInputStream { // 32Mb private static final int MAX_LEN = 32 * 1024 * 1024; protected byte [] header; protected int mode; public GSIGssInputStream(InputStream in, GSSContext context) { super(in, context); this.header = new byte[5]; this.mode = -1; } protected void readMsg() throws IOException { do { byte [] token = readToken(); if (token == null) { this.buff = null; break; } this.buff = unwrap(token); } while (buff == null); this.index = 0; } public int getWrapMode() { return this.mode; } public byte[] readHandshakeToken() throws IOException { byte [] token = readToken(); if (token == null) { throw new EOFException(); } return token; } protected byte[] readToken() throws IOException { byte[] buf = null; if (SSLUtil.read(this.in, this.header, 0, this.header.length-1) < 0) { return null; } if (SSLUtil.isSSLv3Packet(this.header)) { this.mode = GssSocket.SSL_MODE; // read the second byte of packet length field if (SSLUtil.read(this.in, this.header, 4, 1) < 0) { return null; } int len = SSLUtil.toUnsignedShort(this.header[3], this.header[4]); buf = new byte[this.header.length + len]; System.arraycopy(this.header, 0, buf, 0, this.header.length); if (SSLUtil.read(this.in, buf, this.header.length, len) < 0) { return null; } } else if (SSLUtil.isSSLv2HelloPacket(this.header)) { this.mode = GssSocket.SSL_MODE; // SSLv2 - assume 2-byte header // read extra 2 bytes so subtract it from total len int len = (((header[0] & 0x7f) << 8) | (header[1] & 0xff)) - 2; buf = new byte[this.header.length-1 + len]; System.arraycopy(this.header, 0, buf, 0, this.header.length-1); if (SSLUtil.read(this.in, buf, this.header.length-1, len) < 0) { return null; } } else { this.mode = GssSocket.GSI_MODE; int len = SSLUtil.toInt(this.header, 0); if (len > MAX_LEN) { throw new IOException("Token length " + len + " > " + MAX_LEN); } else if (len < 0) { throw new IOException("Token length " + len + " < 0"); } buf = new byte[len]; if (SSLUtil.read(this.in, buf, 0, buf.length) < 0) { return null; } } return buf; } } GSIGssOutputStream.java000066400000000000000000000033231241116057200333710ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/impl/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net.impl; import java.io.OutputStream; import java.io.IOException; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssOutputStream; import org.globus.gsi.gssapi.SSLUtil; import org.ietf.jgss.GSSContext; public class GSIGssOutputStream extends GssOutputStream { protected byte [] header; protected int mode; public GSIGssOutputStream(OutputStream out, GSSContext context) { this(out, context, GssSocket.SSL_MODE); } public GSIGssOutputStream(OutputStream out, GSSContext context, int mode) { super(out, context); this.header = new byte[4]; setWrapMode(mode); } public void flush() throws IOException { if (this.index == 0) return; writeToken(wrap()); this.index = 0; } public void setWrapMode(int mode) { this.mode = mode; } public int getWrapMode() { return this.mode; } public void writeToken(byte[] token) throws IOException { if (this.mode == GssSocket.GSI_MODE) { SSLUtil.writeInt(token.length, this.header, 0); this.out.write(this.header); } this.out.write(token); this.out.flush(); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/impl/GSIGssSocket.java000066400000000000000000000034051241116057200322250ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net.impl; import java.net.Socket; import java.io.IOException; import org.globus.gsi.gssapi.net.GssSocket; import org.ietf.jgss.GSSContext; public class GSIGssSocket extends GssSocket { public GSIGssSocket(String host, int port, GSSContext context) throws IOException { super(host, port, context); } public GSIGssSocket(Socket socket, GSSContext context) { super(socket, context); } public void setWrapMode(int mode) { this.mode = mode; } public int getWrapMode() { return this.mode; } protected void writeToken(byte [] token) throws IOException { if (this.out == null) { if (this.mode == -1) { if (this.in != null) { this.mode = ((GSIGssInputStream)in).getWrapMode(); } } this.out = new GSIGssOutputStream(this.socket.getOutputStream(), this.context, this.mode); } ((GSIGssOutputStream)this.out).writeToken(token); } protected byte[] readToken() throws IOException { if (this.in == null) { this.in = new GSIGssInputStream(this.socket.getInputStream(), this.context); } return ((GSIGssInputStream)this.in).readHandshakeToken(); } } GSIGssSocketFactory.java000066400000000000000000000022311241116057200334720ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/net/impl/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net.impl; import java.net.Socket; import java.io.IOException; import org.ietf.jgss.GSSContext; import org.globus.gsi.gssapi.net.GssSocketFactory; public class GSIGssSocketFactory extends GssSocketFactory { public Socket createSocket(Socket s, String host, int port, GSSContext context) { return new GSIGssSocket(s, context); } public Socket createSocket(String host, int port, GSSContext context) throws IOException { return new GSIGssSocket(host, port, context); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/gsi/gssapi/package.html000066400000000000000000000017331241116057200276460ustar00rootroot00000000000000org.globus.example package The Java GSI library is an implementation of the Java GSS-API. It supports the GSS-API extensions and the new proxy certificate format specifications as defined by the Global Grid Forum. The implementation details are documented on the features and limitations page. The Java GSI library is based on the JSSE (for SSL API) and the BouncyCastle library (for certificate processing API).

    JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/000077500000000000000000000000001241116057200240775ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/BaseServer.java000066400000000000000000000201001241116057200267740ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.net.MalformedURLException; import java.net.InetAddress; import java.io.IOException; import org.globus.util.deactivator.DeactivationHandler; import org.globus.util.deactivator.Deactivator; import org.globus.util.Util; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class provides the basics for writing various servers. * Note: Sockets created by this server have a 5 minute default timeout. * The timeout can be changed using the {@link #setTimeout(int) setTimeout()} * function. */ public abstract class BaseServer implements Runnable { private static Log logger = LogFactory.getLog(BaseServer.class.getName()); /** Socket timeout in milliseconds. */ public static final int SO_TIMEOUT = 5*60*1000; protected boolean accept; protected ServerSocket _server = null; private boolean secure = true; protected String url = null; private Thread serverThread = null; protected GSSCredential credentials = null; protected Authorization authorization = null; protected Integer gssMode = GSIConstants.MODE_SSL; protected int timeout = SO_TIMEOUT; public BaseServer() throws IOException { this(null, 0); } public BaseServer(int port) throws IOException { this(null, port); } public BaseServer(GSSCredential cred, int port) throws IOException { this.credentials = cred; this._server = ServerSocketFactory.getDefault().createServerSocket(port); this.secure = true; initialize(); } public BaseServer(boolean secure, int port) throws IOException { this.credentials = null; this._server = ServerSocketFactory.getDefault().createServerSocket(port); this.secure = secure; initialize(); } /** * This method should be called by all subclasses. * */ protected void initialize() { setAuthorization(SelfAuthorization.getInstance()); start(); } /** * Starts the server. */ protected void start() { if (serverThread == null) { accept = true; serverThread = new Thread(this); serverThread.start(); } } /** * Sets timeout for the created sockets. * By default if not set, 5 minute timeout is used. */ public void setTimeout(int timeout) { this.timeout = timeout; } public int getTimeout() { return this.timeout; } /** * Stops the server but does * not stop all the client threads */ public void shutdown() { accept = false; try { _server.close(); } catch(Exception e) {} // this is a hack to ensue the server socket is // unblocked from accpet() // but this is not guaranteed to work still SocketFactory factory = SocketFactory.getDefault(); Socket s = null; try { s = factory.createSocket(InetAddress.getLocalHost(), getPort()); s.getInputStream(); } catch (Exception e) { // can be ignored } finally { if (s != null) { try { s.close(); } catch (Exception e) {} } } // reset everything serverThread = null; _server = null; } public GSSCredential getCredentials() { return this.credentials; } public String getProtocol() { return (secure) ? "https" : "http"; } /** * Returns url of this server * * @return url of this server */ public String getURL() { if (url == null) { StringBuffer buf = new StringBuffer(); buf.append(getProtocol()). append("://"). append(getHost()). append(":"). append(String.valueOf(getPort())); url = buf.toString(); } return url; } /** * Returns port of this server * * @return port number */ public int getPort() { return _server.getLocalPort(); } /** * Returns hostname of this server * * @return hostname */ public String getHostname() { return Util.getLocalHostAddress(); } /** * Returns hostname of this server. The format of the host conforms * to RFC 2732, i.e. for a literal IPv6 address, this method will * return the IPv6 address enclosed in square brackets ('[' and ']'). * * @return hostname */ public String getHost() { String host = Util.getLocalHostAddress(); try { URL u = new URL("http", host, 80, "/"); return u.getHost(); } catch (MalformedURLException e) { return host; } } public void run() { Socket socket = null ; while(accept) { try { socket = _server.accept(); if (!accept) { break; } socket.setSoTimeout(getTimeout()); } catch(IOException e) { if (accept) { // display error message logger.error("Server died: " + e.getMessage(), e); } break; } if (this.secure) { try { socket = wrapSocket(socket); } catch (GSSException e) { logger.error("Failed to secure the socket", e); break; } } handleConnection(socket); } logger.debug("server thread stopped"); } protected Socket wrapSocket(Socket socket) throws GSSException { GSSManager manager = ExtendedGSSManager.getInstance(); ExtendedGSSContext context = (ExtendedGSSContext)manager.createContext(credentials); context.setOption(GSSConstants.GSS_MODE, gssMode); GssSocketFactory factory = GssSocketFactory.getDefault(); GssSocket gsiSocket = (GssSocket)factory.createSocket(socket, null, 0, context); // server socket gsiSocket.setUseClientMode(false); gsiSocket.setAuthorization(this.authorization); return gsiSocket; } public void setGssMode(Integer mode) { this.gssMode = mode; } public void setAuthorization(Authorization auth) { authorization = auth; } /** * This method needs to be implemented by subclasses. * Optimmaly, it should be a non-blocking call starting * a separate thread to handle the client. Note that to * start an SSL handshake, you need to call socket.getInput(Output) * stream(). */ protected abstract void handleConnection(Socket socket) ; /** * Registers a default deactivation handler. It is used * to shutdown the server without having a reference to * the server. Call Deactivate.deactivateAll() to shutdown * all registered servers. */ public void registerDefaultDeactivator() { if (deactivator == null) { deactivator = new AbstractServerDeactivator(this); } Deactivator.registerDeactivation(deactivator); } /** * Unregisters a default deactivation handler. */ public void unregisterDefaultDeactivator() { if (deactivator == null) return; Deactivator.unregisterDeactivation(deactivator); } /** * A handler for the deactivation framework. */ protected AbstractServerDeactivator deactivator = null; } class AbstractServerDeactivator implements DeactivationHandler { private BaseServer server = null; public AbstractServerDeactivator(BaseServer server) { this.server = server; } public void deactivate() { if (server != null) server.shutdown(); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/DatagramSocketFactory.java000066400000000000000000000120061241116057200311620ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.net; import org.globus.common.CoGProperties; import java.net.DatagramSocket; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.BindException; import java.net.SocketException; import java.io.IOException; /** * This factory allows for creating datagram sockets. * If the udp.source.port.range system property is set it will create * datagram sockets within the specified local port range (if the local port * number is set to 0). */ public class DatagramSocketFactory { private static DatagramSocketFactory defaultFactory = null; private PortRange portRange = null; protected DatagramSocketFactory() { this.portRange = PortRange.getUdpSourceInstance(); } /** * Returns the default instance of this class. * * @return DatagramSocketFactory instance of this class. */ public static synchronized DatagramSocketFactory getDefault() { if (defaultFactory == null) { defaultFactory = new DatagramSocketFactory(); } return defaultFactory; } public DatagramSocket createDatagramSocket() throws IOException { return createDatagramSocket(0, null); } public DatagramSocket createDatagramSocket(int port) throws IOException { return createDatagramSocket(port, null); } public DatagramSocket createDatagramSocket(int port, InetAddress localAddr) throws IOException { if (this.portRange.isEnabled() && port == 0) { return new PrDatagramSocket(createDatagramSocket(localAddr)); } else { DatagramSocket socket = new DatagramSocket(port, localAddr); socket.setSoTimeout(CoGProperties.getDefault().getSocketTimeout()); return new DatagramSocket(port, localAddr); } } private DatagramSocket createDatagramSocket(InetAddress localAddr) throws IOException { DatagramSocket socket = null; int localPort = 0; while(true) { localPort = this.portRange.getFreePort(localPort); try { socket = new DatagramSocket(localPort, localAddr); socket.setSoTimeout(CoGProperties.getDefault().getSocketTimeout()); this.portRange.setUsed(localPort); return socket; } catch(BindException e) { // continue on localPort++; } } } class PrDatagramSocket extends DatagramSocket { private DatagramSocket socket; public PrDatagramSocket(DatagramSocket socket) throws SocketException { super.close(); this.socket = socket; } public void connect(InetAddress address, int port) { this.socket.connect(address, port); } public void disconnect() { this.socket.disconnect(); } public InetAddress getInetAddress() { return this.socket.getInetAddress(); } public int getPort() { return this.socket.getPort(); } public void send(DatagramPacket p) throws IOException { this.socket.send(p); } public void receive(DatagramPacket p) throws IOException { this.socket.receive(p); } public InetAddress getLocalAddress() { return this.socket.getLocalAddress(); } public int getLocalPort() { return this.socket.getLocalPort(); } public void setSoTimeout(int timeout) throws SocketException { this.socket.setSoTimeout(timeout); } public int getSoTimeout() throws SocketException { return this.socket.getSoTimeout(); } public void setSendBufferSize(int size) throws SocketException { this.socket.setSendBufferSize(size); } public int getSendBufferSize() throws SocketException { return this.socket.getSendBufferSize(); } public void setReceiveBufferSize(int size) throws SocketException { this.socket.setReceiveBufferSize(size); } public int getReceiveBufferSize() throws SocketException { return this.socket.getReceiveBufferSize(); } public void close() { int port = getLocalPort(); socket.close(); if (port != -1) { portRange.free(port); } } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/GSIHttpURLConnection.java000066400000000000000000000152011241116057200306260ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net; import java.net.Socket; import java.net.URL; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ProtocolException; import org.globus.common.ChainedIOException; import org.globus.util.http.HTTPProtocol; import org.globus.util.http.HTTPResponseParser; import org.globus.util.http.HTTPChunkedInputStream; import org.globus.util.http.HTTPChunkedOutputStream; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSContext; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSContext; public class GSIHttpURLConnection extends GSIURLConnection { public static final int PORT = 8443; private static final String USER_AGENT = "Java-Globus-GASS-HTTP/1.1.0"; private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded"; private Socket socket; private int port; private HTTPResponseParser response; private InputStream is; private OutputStream os; public GSIHttpURLConnection(URL u) { super(u); } public synchronized void connect() throws IOException { if (this.connected) { return; } else { this.connected = true; } this.port = (url.getPort() == -1) ? PORT : url.getPort(); GSSManager manager = ExtendedGSSManager.getInstance(); ExtendedGSSContext context = null; try { context = (ExtendedGSSContext)manager.createContext(getExpectedName(), GSSConstants.MECH_OID, this.credentials, GSSContext.DEFAULT_LIFETIME); switch (this.delegationType) { case GSIConstants.DELEGATION_NONE: context.requestCredDeleg(false); break; case GSIConstants.DELEGATION_LIMITED: context.requestCredDeleg(true); context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_LIMITED); break; case GSIConstants.DELEGATION_FULL: context.requestCredDeleg(true); context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_FULL); break; default: context.requestCredDeleg(true); context.setOption(GSSConstants.DELEGATION_TYPE, new Integer(this.delegationType)); } if (this.gssMode != null) { context.setOption(GSSConstants.GSS_MODE, gssMode); } } catch (GSSException e) { throw new ChainedIOException("Failed to init GSI context", e); } GssSocketFactory factory = GssSocketFactory.getDefault(); socket = factory.createSocket(url.getHost(), this.port, context); ((GssSocket)socket).setAuthorization(authorization); } public synchronized void disconnect() { if (socket != null) { try { socket.close(); } catch (Exception e) {} socket = null; } } public synchronized OutputStream getOutputStream() throws IOException { // maybe already doing a GET, so only input stream if (this.is != null && this.os == null) { throw new ProtocolException( "Cannot write output after reading input"); } if (this.os == null) { connect(); String header = HTTPProtocol.createPUTHeader(url.getFile(), url.getHost() + ":" + port, USER_AGENT, POST_CONTENT_TYPE, -1, true); OutputStream wrapped = socket.getOutputStream(); wrapped.write(header.getBytes()); // create an output stream that will stream // the result using chunked coding this.os = new HTTPChunkedOutputStream(wrapped); } return os; } public synchronized InputStream getInputStream() throws IOException { if (this.is == null) { connect(); if (this.os == null) { // if no output stream already created, send a GET request OutputStream out = socket.getOutputStream(); String msg = HTTPProtocol.createGETHeader(url.getFile(), url.getHost() + ":" + this.port, USER_AGENT); out.write( msg.getBytes() ); out.flush(); } else { // if getOutputStream() was called previously, flush it this.os.flush(); this.os.close(); this.os = null; } InputStream in = socket.getInputStream(); response = new HTTPResponseParser(in); if (!response.isOK()) { throw new IOException(response.getMessage()); } if (response.isChunked()) { is = new HTTPChunkedInputStream(in); } else { is = in; } } return is; } public String getHeaderField(String name) { if (response == null) { return null; } if (name.equalsIgnoreCase("content-type")) { return response.getContentType(); } else if (name.equalsIgnoreCase("content-length")) { return String.valueOf(response.getContentLength()); } else { return null; } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/GSIURLConnection.java000066400000000000000000000056271241116057200300010ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net; import java.net.URL; import java.net.URLConnection; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.GSSAuthorization; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSException; public abstract class GSIURLConnection extends URLConnection { public static final String GSS_MODE_PROPERTY = "gssMode"; protected GSSCredential credentials; protected Authorization authorization; protected int delegationType; protected Integer gssMode; /** * Subclasses must overwrite. */ protected GSIURLConnection(URL url) { super(url); this.delegationType = GSIConstants.DELEGATION_NONE; this.authorization = null; // no authorization? } public abstract void disconnect(); public void setGSSMode(Integer mode) { this.gssMode = mode; } public Integer getGSSMode() { return this.gssMode; } public void setCredentials(GSSCredential credentials) { this.credentials = credentials; } public GSSCredential getCredentials() { return credentials; } public void setAuthorization(Authorization auth) { authorization = auth; } public Authorization getAuthorization() { return authorization; } public void setDelegationType(int delegationType) { this.delegationType = delegationType; } public int getDelegationType() { return delegationType; } protected GSSName getExpectedName() throws GSSException { if (this.authorization instanceof GSSAuthorization) { GSSAuthorization auth = (GSSAuthorization)this.authorization; return auth.getExpectedName(this.credentials, this.url.getHost()); } else { return null; } } public void setRequestProperty(String key, String value) { if (key.equals(GSS_MODE_PROPERTY)) { if (value.equals("ssl")) { setGSSMode(GSIConstants.MODE_SSL); } else if (value.equals("gsi")) { setGSSMode(GSIConstants.MODE_GSI); } else { setGSSMode(null); } } else { super.setRequestProperty(key, value); } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/GlobusURLStreamHandlerFactory.java000066400000000000000000000017311241116057200325640ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net; import java.net.URLStreamHandlerFactory; import java.net.URLStreamHandler; public class GlobusURLStreamHandlerFactory implements URLStreamHandlerFactory { public URLStreamHandler createURLStreamHandler(String protocol) { if (protocol.equalsIgnoreCase("httpg")) { return new org.globus.net.protocol.httpg.Handler(); } return null; } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/PortRange.java000066400000000000000000000145771241116057200266610ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net; import java.io.IOException; import org.globus.common.CoGProperties; /** * This class manages the port ranges. It keeps track of which * ports are used and which ones are open. */ public class PortRange { protected static final byte UNUSED = 0; protected static final byte USED = 1; private boolean portRange = false; private int minPort, maxPort; private byte [] ports; private static PortRange tcpPortRange = null; private static PortRange tcpSourcePortRange = null; private static PortRange udpSourcePortRange = null; protected PortRange() { } /** * Returns PortRange instance for TCP listening sockets. * * @see #getTcpInstance() */ public static PortRange getInstance() { return getTcpInstance(); } /** * Returns PortRange instance for TCP listening sockets. * If the tcp.port.range property is set, the class * will be initialized with the specified port ranges. * * @return PortRange the default instace of this class. */ public static synchronized PortRange getTcpInstance() { if (tcpPortRange == null) { tcpPortRange = new PortRange(); tcpPortRange.init(CoGProperties.getDefault().getTcpPortRange()); } return tcpPortRange; } /** * Returns PortRange instance for TCP source sockets. * If the tcp.source.port.range property is set, the class * will be initialized with the specified port ranges. * * @return PortRange the default instace of this class. */ public static synchronized PortRange getTcpSourceInstance() { if (tcpSourcePortRange == null) { tcpSourcePortRange = new PortRange(); tcpSourcePortRange.init( CoGProperties.getDefault().getTcpSourcePortRange()); } return tcpSourcePortRange; } /** * Returns PortRange instance for UDP source sockets. * If the udp.source.port.range property is set, the class * will be initialized with the specified port ranges. * * @return PortRange the default instace of this class. */ public static synchronized PortRange getUdpSourceInstance() { if (udpSourcePortRange == null) { udpSourcePortRange = new PortRange(); udpSourcePortRange.init( CoGProperties.getDefault().getUdpSourcePortRange()); } return udpSourcePortRange; } /** * Checks if the port range is set. * * @return true if the port range is set, false otherwise. */ public boolean isEnabled() { return portRange; } /** * Returns first available port. * * @param lastPortNumber port number to start finding the next * available port from. Set it to 0 if * called initialy. * @return the next available port number from the lastPortNumber. * @exception IOException if there is no more free ports available or * if the lastPortNumber is incorrect. */ public synchronized int getFreePort(int lastPortNumber) throws IOException { int id = 0; if (lastPortNumber != 0) { id = lastPortNumber - minPort; if (id < 0) { throw new IOException("Port number out of range."); } } for(int i=id;inot * check if it is a free, but only checks if it is within said range. */ public boolean isInRange(int portNumber) { if ((minPort <= portNumber) && (maxPort >= portNumber)) { return true; } return false; } private synchronized void setPort(int portNumber, byte type) { int id = portNumber - minPort; if (id < 0) { throw new IllegalArgumentException("Port number out of range: " + portNumber); } ports[id] = type; } private void init(String portRangeStr) { portRange = false; if (portRangeStr == null) return ; int pos = portRangeStr.indexOf(","); if (pos == -1) { throw new IllegalArgumentException("Missing comma in the port range property: " + portRangeStr); } int min, max; try { min = Integer.parseInt(portRangeStr.substring(0, pos).trim()); } catch(Exception e) { throw new IllegalArgumentException("The minimum port range value is invalid: " + e.getMessage()); } try { max = Integer.parseInt(portRangeStr.substring(pos+1).trim()); } catch(Exception e) { throw new IllegalArgumentException("The maximum port range value is invalid: " + e.getMessage()); } if (min >= max) { throw new IllegalArgumentException("The minimum port range value is greater then " + "the maximum port range value."); } minPort = min; maxPort = max; ports = new byte[ maxPort-minPort ]; portRange = true; } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/ServerSocketFactory.java000066400000000000000000000135351241116057200307200ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net; import java.net.ServerSocket; import java.net.InetAddress; import java.io.IOException; /** * This factory allows for creating regular server sockets. * If the tcp.port.range system property is set it will create * server sockets within the specified port range (if the port * number is set to 0). */ public class ServerSocketFactory { private static ServerSocketFactory defaultFactory = null; private PortRange portRange = null; protected ServerSocketFactory() { this.portRange = PortRange.getTcpInstance(); } /** * Returns the default instance of this class. * * @return ServerSocketFactory instance of this class. */ public static synchronized ServerSocketFactory getDefault() { if (defaultFactory == null) { defaultFactory = new ServerSocketFactory(); } return defaultFactory; } /** * Creates a server socket on a specified port. A port of * 0 creates a socket on any free port or if the * tcp.port.range system property is set it creates a socket * within the specified port range. *

    * The maximum queue length for incoming connection indications (a * request to connect) is set to 50. If a connection * indication arrives when the queue is full, the connection is refused. * * @param port the port number, or 0 to use any * free port or if the tcp.port.range property set * to use any available port within the specified port * range. * @exception IOException if an I/O error occurs when opening the socket. */ public ServerSocket createServerSocket(int port) throws IOException { return createServerSocket(port, 50, null); } /** * Creates a server socket on a specified port. A port of * 0 creates a socket on any free port or if the * tcp.port.range system property is set it creates a socket * within the specified port range. *

    * The maximum queue length for incoming connection indications (a * request to connect) is set to the backlog parameter. If * a connection indication arrives when the queue is full, the * connection is refused. * * @param port the port number, or 0 to use any * free port or if the tcp.port.range property set * to use any available port within the specified port * range. * @param backlog the maximum length of the queue. * @exception IOException if an I/O error occurs when opening the socket. */ public ServerSocket createServerSocket(int port, int backlog) throws IOException { return createServerSocket(port, backlog, null); } /** * Create a server with the specified port, listen backlog, and * local IP address to bind to. The bindAddr argument * can be used on a multi-homed host for a ServerSocket that * will only accept connect requests to one of its addresses. * If bindAddr is null, it will default accepting * connections on any/all local addresses. * The port must be between 0 and 65535, inclusive. * * @param port the local TCP port * @param backlog the listen backlog * @param bindAddr the local InetAddress the server will bind to * @exception IOException if an I/O error occurs when opening the socket. */ public ServerSocket createServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException { if (this.portRange.isEnabled() && port == 0) { return createServerSocket(backlog, bindAddr); } else { return new ServerSocket(port, backlog, bindAddr); } } /** * Tries to find first available port within the port range specified. * If it finds a free port, it first checks if the port is not used * by any other server. If it is, it keeps looking for a next available * port. If none found, it throws an exception. If the port is available * the server instance is returned. */ private ServerSocket createServerSocket(int backlog, InetAddress binAddr) throws IOException { ServerSocket server = null ; int port = 0; while(true) { port = this.portRange.getFreePort(port); try { server = new PrServerSocket(port, backlog, binAddr); this.portRange.setUsed(port); return server; } catch(IOException e) { // continue on port++; } } } class PrServerSocket extends ServerSocket { public PrServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException { super(port, backlog, bindAddr); } public void close() throws IOException { int port = getLocalPort(); try { super.close(); } finally { if (port != -1) { portRange.free(port); } } } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/SocketFactory.java000066400000000000000000000077431241116057200275350ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net; import org.globus.common.CoGProperties; import java.net.InetSocketAddress; import java.net.Socket; import java.net.InetAddress; import java.net.BindException; import java.io.IOException; /** * This factory allows for creating regular sockets. * If the tcp.source.port.range system property is set it will create * sockets within the specified local port range (if the local port * number is set to 0). */ public class SocketFactory { private static SocketFactory defaultFactory = null; private PortRange portRange = null; protected SocketFactory() { this.portRange = PortRange.getTcpSourceInstance(); } /** * Returns the default instance of this class. * * @return SocketFactory instance of this class. */ public static synchronized SocketFactory getDefault() { if (defaultFactory == null) { defaultFactory = new SocketFactory(); } return defaultFactory; } public Socket createSocket(String host, int port) throws IOException { return createSocket(InetAddress.getByName(host), port, null, 0); } public Socket createSocket(InetAddress address, int port) throws IOException { return createSocket(address, port, null, 0); } public Socket createSocket(String host, int port, InetAddress localAddr, int localPort) throws IOException { return createSocket(InetAddress.getByName(host), port, localAddr, localPort); } public Socket createSocket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException { if (this.portRange.isEnabled() && localPort == 0) { return new PrSocket(createSocket(address, port, localAddr)); } else { Socket s = new Socket(); s.setSoTimeout(CoGProperties.getDefault().getSocketTimeout()); s.bind(new InetSocketAddress(localAddr, localPort)); s.connect(new InetSocketAddress(address, port), CoGProperties.getDefault().getSocketTimeout()); return s; } } private Socket createSocket(InetAddress address, int port, InetAddress localAddr) throws IOException { Socket socket = null; int localPort = 0; while(true) { localPort = this.portRange.getFreePort(localPort); try { socket = new Socket(); socket.setSoTimeout(CoGProperties.getDefault().getSocketTimeout()); socket.bind(new InetSocketAddress(localAddr, localPort)); socket.connect(new InetSocketAddress(address, port), CoGProperties.getDefault().getSocketTimeout()); this.portRange.setUsed(localPort); return socket; } catch(BindException e) { // continue on localPort++; } } } class PrSocket extends WrappedSocket { public PrSocket(Socket socket) { super(socket); } public void close() throws IOException { int port = getLocalPort(); try { super.close(); } finally { if (port != -1) { portRange.free(port); } } } } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/WrappedSocket.java000066400000000000000000000063101241116057200275150ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net; import java.net.Socket; import java.net.InetAddress; import java.net.SocketException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class WrappedSocket extends Socket { protected Socket socket; protected WrappedSocket() {} public WrappedSocket(Socket socket) { super(); this.socket = socket; } public Socket getWrappedSocket() { return this.socket; } public OutputStream getOutputStream() throws IOException { return this.socket.getOutputStream(); } public synchronized InputStream getInputStream() throws IOException { return this.socket.getInputStream(); } public void close() throws IOException { this.socket.close(); } public InetAddress getInetAddress() { return this.socket.getInetAddress(); } public boolean getKeepAlive() throws SocketException { return this.socket.getKeepAlive(); } public InetAddress getLocalAddress() { return this.socket.getLocalAddress(); } public int getLocalPort() { return this.socket.getLocalPort(); } public int getPort() { return this.socket.getPort(); } public int getReceiveBufferSize() throws SocketException { return this.socket.getReceiveBufferSize(); } public int getSendBufferSize() throws SocketException { return this.socket.getSendBufferSize(); } public int getSoLinger() throws SocketException { return this.socket.getSoLinger(); } public int getSoTimeout() throws SocketException { return this.socket.getSoTimeout(); } public boolean getTcpNoDelay() throws SocketException { return this.socket.getTcpNoDelay(); } public void setKeepAlive(boolean on) throws SocketException { this.socket.setKeepAlive(on); } public void setReceiveBufferSize(int size) throws SocketException { this.socket.setReceiveBufferSize(size); } public void setSendBufferSize(int size) throws SocketException { this.socket.setSendBufferSize(size); } public void setSoLinger(boolean on, int linger) throws SocketException { this.socket.setSoLinger(on, linger); } public void setSoTimeout(int timeout) throws SocketException { this.socket.setSoTimeout(timeout); } public void setTcpNoDelay(boolean on) throws SocketException { this.socket.setTcpNoDelay(on); } public void shutdownInput() throws IOException { this.socket.shutdownInput(); } public void shutdownOutput() throws IOException { this.socket.shutdownOutput(); } public String toString() { return this.socket.toString(); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/package.html000066400000000000000000000007171241116057200263650ustar00rootroot00000000000000 Contains socket factories for creating regural and secure server sockets behind firewalls or NAT servers. Allows for creating server sockets within specified port ranges.

    Package Specification

    Related Documentation

    JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/protocol/000077500000000000000000000000001241116057200257405ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/protocol/httpg/000077500000000000000000000000001241116057200270665ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/protocol/httpg/Handler.java000066400000000000000000000045051241116057200313120ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net.protocol.httpg; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.lang.reflect.Constructor; public class Handler extends URLStreamHandler { private static final String CLASS = "org.globus.net.GSIHttpURLConnection"; private static final Class[] PARAMS = new Class[] { URL.class }; private static Constructor constructor = null; private static synchronized Constructor initConstructor() { if (constructor == null) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Class clazz = Class.forName(CLASS, true, loader); constructor = clazz.getConstructor(PARAMS); } catch (Exception e) { throw new RuntimeException("Unable to load url handler: " + e.getMessage()); } } return constructor; } protected URLConnection openConnection(URL u) { if (constructor == null) { initConstructor(); } try { return (URLConnection)constructor.newInstance(new Object[] {u}); } catch (Exception e) { throw new RuntimeException("Unable to instantiate url handler: " + e.getMessage()); } } protected int getDefaultPort() { return 8443; } protected void setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref) { if (port == -1) { port = getDefaultPort(); } super.setURL(u, protocol, host, port, authority, userInfo, path, query, ref); } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/protocol/https/000077500000000000000000000000001241116057200271025ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/java/org/globus/net/protocol/https/Handler.java000066400000000000000000000017621241116057200313300ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.net.protocol.https; import java.net.URL; import java.net.URLConnection; public class Handler extends org.globus.net.protocol.httpg.Handler { protected URLConnection openConnection(URL u) { URLConnection conn = super.openConnection(u); conn.setRequestProperty("gssMode", "ssl"); return conn; } protected int getDefaultPort() { return 443; } } JGlobus-JGlobus-Release-2.1.0/gss/src/main/resources/000077500000000000000000000000001241116057200223205ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/resources/log4j.properties000066400000000000000000000004221241116057200254530ustar00rootroot00000000000000log4j.rootCategory=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c{2} %x - %m%n log4j.category.COM.claymoresystems.ptls.SSLDebug=OFF JGlobus-JGlobus-Release-2.1.0/gss/src/main/resources/org/000077500000000000000000000000001241116057200231075ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/resources/org/globus/000077500000000000000000000000001241116057200244025ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/resources/org/globus/gsi/000077500000000000000000000000001241116057200251645ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/resources/org/globus/gsi/gssapi/000077500000000000000000000000001241116057200264525ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/main/resources/org/globus/gsi/gssapi/errors.properties000066400000000000000000000044241241116057200321100ustar00rootroot00000000000000badType = [JGLOBUS-39] Invalid option type. Expected {1} type nullOption = [JGLOBUS-40] Option cannot be null nullOptionValue = [JGLOBUS-41] Option value cannot be null badDelegType = [JGLOBUS-42] Delegation type not supported badGssMode = [JGLOBUS-43] GSS mode not supported unknownOption = [JGLOBUS-44] Option {0} not supported replayDet = [JGLOBUS-45] Replay detection is always enabled seqDet = [JGLOBUS-46] Sequence checking is always enabled integOn = [JGLOBUS-47] Integrity is always enabled mutualAuthOn = [JGLOBUS-48] Mutual authentication is always enabled tokenFail00 = [JGLOBUS-49] Token length of {0} does not match size of message digest {1} tokenFail01 = [JGLOBUS-50] Message buffer length of {0} does not match expected length of {1} in token tokenFail02 = [JGLOBUS-51] Message digest and token's contents are not equal tokenFail03 = [JGLOBUS-52] Invalid token badLifetime00 = [JGLOBUS-53] Indefinite lifetime not supported badLifetime01 = [JGLOBUS-54] Credential lifetime not supported proxyViolation = [JGLOBUS-55] Limited proxies not accepted authFailed00 = [JGLOBUS-56] Authorization failed. Expected "{0}" target but received "{1}" initCtx00 = [JGLOBUS-57] Cannot request delegation in SSL compatibility mode initCtx01 = [JGLOBUS-58] Cannot request delegation and be anonymous initCtx02 = [JGLOBUS-59] Cannot request delegation without authorization (target name null) acceptCtx00 = [JGLOBUS-60] Non-anonymous credential required for acceptor badCredUsage = [JGLOBUS-61] Invalid credential usage noClientCert = [JGLOBUS-62] Client certificates expected invalidBuf = [JGLOBUS-63] Invalid buffer delegError00 = [JGLOBUS-64] Invalid initial hello message, expecting: "D", received: {0} badName00 = [JGLOBUS-65] Bad hostbased service name. "@" missing anonCred00 = [JGLOBUS-66] Cannot export anonymous credential notCACert = [JGLOBUS-67] The signing certificate is not a CA certificate (has no BasicConstraint extension) proxySign = [JGLOBUS-68] Invalid proxy certificate noCaCerts = [JGLOBUS-69] Cannot find any trusted certificates keyMismatch = [JGLOBUS-70] Private/Public key mismatch invalidJaasSubject = [JGLOBUS-71] Invalid JaasSubject provider class: \"{0}\" className loadError = [JGLOBUS-72] Unable to load \"{0}\" class instanError = [JGLOBUS-73] Unable to instantiate \"{0}\" class JGlobus-JGlobus-Release-2.1.0/gss/src/test/000077500000000000000000000000001241116057200203415ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/000077500000000000000000000000001241116057200212625ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/000077500000000000000000000000001241116057200220515ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/000077500000000000000000000000001241116057200233445ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/000077500000000000000000000000001241116057200241265ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/000077500000000000000000000000001241116057200254145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/jaas/000077500000000000000000000000001241116057200263325ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/jaas/GlobusSubjectTest.java000066400000000000000000000100561241116057200326120ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.jaas; import org.globus.gsi.gssapi.jaas.JaasSubject; import java.security.PrivilegedAction; import java.security.AccessController; import javax.security.auth.Subject; import junit.framework.TestCase; public class GlobusSubjectTest extends TestCase { private static final String CRED = "testCred1"; private static final String CRED2 = "testCred2"; public void testSubject() throws Exception { Subject subject = new Subject(); subject.getPublicCredentials().add(CRED); TestAction action = new TestAction(); JaasSubject.doAs(subject, action); assertEquals(subject, action.subject1); assertEquals(subject, action.innerSubject); assertEquals(subject, action.subject2); } class TestAction implements PrivilegedAction { Subject subject1, innerSubject, subject2; public Object run() { this.subject1 = JaasSubject.getCurrentSubject(); this.innerSubject = (Subject)AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return JaasSubject.getCurrentSubject(); } }); this.subject2 = JaasSubject.getCurrentSubject(); return null; } } public void testNestedSubject() throws Exception { Subject subject = new Subject(); subject.getPublicCredentials().add(CRED); Subject anotherSubject = new Subject(); anotherSubject.getPublicCredentials().add(CRED2); NestedTestAction action = new NestedTestAction(anotherSubject); JaasSubject.doAs(subject, action); assertEquals(subject, action.subject1); assertEquals(subject, action.subject2); assertEquals(anotherSubject, action.innerSubject1); assertEquals(anotherSubject, action.innerSubject2); assertEquals(anotherSubject, action.innerInnerSubject); } class NestedTestAction implements PrivilegedAction { Subject subject1, subject2; Subject innerSubject1, innerSubject2, innerInnerSubject; Subject anotherSubject; public NestedTestAction(Subject anotherSubject) { this.anotherSubject = anotherSubject; } public Object run() { this.subject1 = JaasSubject.getCurrentSubject(); TestAction action = new TestAction(); JaasSubject.doAs(anotherSubject, action); this.innerSubject1 = action.subject1; this.innerSubject2 = action.subject2; this.innerInnerSubject = action.innerSubject; this.subject2 = JaasSubject.getCurrentSubject(); return null; } } public void testGetSubjectSameThread() throws Exception { Subject subject = new Subject(); subject.getPublicCredentials().add(CRED); SimpleTestAction action = new SimpleTestAction(); Subject returnedSubject = (Subject)JaasSubject.doAs(subject, action); assertEquals(subject, returnedSubject); } class SimpleTestAction implements PrivilegedAction { public Object run() { return JaasSubject.getCurrentSubject(); } } public void testGetSubjectInheritThread() throws Exception { Subject subject = new Subject(); subject.getPublicCredentials().add(CRED); ThreadTestAction action = new ThreadTestAction(); Subject returnedSubject = (Subject)JaasSubject.doAs(subject, action); assertEquals(subject, returnedSubject); } class ThreadTestAction implements PrivilegedAction { public Object run() { TestThread t = new TestThread(); t.start(); try { t.join(); } catch (Exception e) { } return t.subject; } } class TestThread extends Thread { Subject subject; public void run() { this.subject = JaasSubject.getCurrentSubject(); } } } JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/net/000077500000000000000000000000001241116057200262025ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/net/test/000077500000000000000000000000001241116057200271615ustar00rootroot00000000000000GssOutputStreamTest.java000066400000000000000000000063231241116057200337420ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/net/test/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.net.test; import java.io.OutputStream; import java.io.IOException; import java.io.ByteArrayOutputStream; import org.globus.gsi.gssapi.net.GssOutputStream; import junit.framework.TestCase; public class GssOutputStreamTest extends TestCase { public void test1() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); TestGssOutputStream t = new TestGssOutputStream(out, 5); t.write('A'); t.write('B'); assertEquals(2, t.getIndex()); t.write('C'); t.write('D'); t.write('E'); assertEquals(5, t.getIndex()); t.write('F'); assertEquals(1, t.getIndex()); assertEquals("ABCDE", new String(out.toByteArray())); } public void test2() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); TestGssOutputStream t = new TestGssOutputStream(out, 5); byte [] m1 = new byte[] {'A', 'B'}; t.write(m1); assertEquals(2, t.getIndex()); byte [] m2 = new byte[] {'C', 'D', 'E'}; t.write(m2); assertEquals(5, t.getIndex()); t.write('F'); assertEquals(1, t.getIndex()); assertEquals("ABCDE", new String(out.toByteArray())); } public void test3() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); TestGssOutputStream t = new TestGssOutputStream(out, 5); byte [] m1 = new byte[] {'A', 'B', 'C', 'D', 'E', 'F', 'G'}; t.write(m1); assertEquals(2, t.getIndex()); assertEquals("ABCDE", new String(out.toByteArray())); } public void test4() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); TestGssOutputStream t = new TestGssOutputStream(out, 5); byte [] m1 = new byte[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'}; t.write(m1); assertEquals(3, t.getIndex()); assertEquals("ABCDEFGHIJ", new String(out.toByteArray())); } public void test5() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); TestGssOutputStream t = new TestGssOutputStream(out, 5); byte [] m1 = new byte[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'}; t.write(m1); assertEquals(5, t.getIndex()); assertEquals("ABCDEFGHIJ", new String(out.toByteArray())); t.write('B'); assertEquals(1, t.getIndex()); assertEquals("ABCDEFGHIJKLMNO", new String(out.toByteArray())); } class TestGssOutputStream extends GssOutputStream { public TestGssOutputStream(OutputStream out, int size) { super(out, null, size); } public int getIndex() { return index; } public void flush() throws IOException { out.write(buff, 0, index); index = 0; } } } JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/test/000077500000000000000000000000001241116057200263735ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/test/GlobusGSSContextTest.java000066400000000000000000000774121241116057200332660ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.test; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.X509Credential; import org.globus.gsi.GSIConstants; import org.globus.gsi.GSIConstants.CertificateType; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.MessageProp; import org.ietf.jgss.Oid; import org.gridforum.jgss.ExtendedGSSCredential; import org.gridforum.jgss.ExtendedGSSContext; import org.globus.gsi.gssapi.GlobusGSSManagerImpl; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.cert.X509Certificate; import java.util.Date; import java.net.Socket; import java.net.ServerSocket; import java.net.InetAddress; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class GlobusGSSContextTest extends TestCase { private static final byte [] MSG = "this is a test 1 2 3".getBytes(); private Log logger = LogFactory.getLog(GlobusGSSContextTest.class); GSSContext clientContext; GSSContext serverContext; protected void setUp() throws Exception { System.setProperty("org.globus.gsi.gssapi.provider", "org.globus.gsi.gssapi.GlobusGSSManagerImpl"); if (clientContext != null) { clientContext.dispose(); clientContext = null; } if (serverContext != null) { serverContext.dispose(); serverContext = null; } X509Credential.setDefaultCredential(null); GSSManager manager = getGSSManager(); GSSCredential gssCred = manager.createCredential(GSSCredential.INITIATE_ONLY); GSSName gssName = gssCred.getName(); serverContext = manager.createContext((GSSCredential)null); clientContext = manager.createContext(gssName, GSSConstants.MECH_OID, null, GSSContext.DEFAULT_LIFETIME); } protected void tearDown() throws Exception { if (clientContext != null) { clientContext.dispose(); clientContext = null; } if (serverContext != null) { serverContext.dispose(); serverContext = null; } } protected GSSManager getGSSManager() throws Exception { return new GlobusGSSManagerImpl(); } private void establishContext() throws Exception { assertTrue("client ctx already established.", !clientContext.isEstablished()); assertTrue("server ctx already established.", !serverContext.isEstablished()); byte [] empty = new byte[0]; byte [] inToken = empty; byte [] outToken = null; while (!clientContext.isEstablished()) { if (inToken == null || inToken == empty) { outToken = clientContext.initSecContext(inToken, 0, inToken.length); } else { outToken = clientContext.initSecContext(inToken, 0, inToken.length/2); assertTrue(outToken == null); outToken = clientContext.initSecContext(inToken, inToken.length/2, inToken.length - inToken.length/2); } if (outToken == null || outToken.length == 0) { fail("bad token"); } if (outToken == null || outToken == empty) { inToken = serverContext.acceptSecContext(outToken, 0, outToken.length); } else { inToken = serverContext.acceptSecContext(outToken, 0, outToken.length/2); assertTrue(inToken == null); inToken = serverContext.acceptSecContext(outToken, outToken.length/2, outToken.length - outToken.length/2); } if (inToken == null && !clientContext.isEstablished()) { fail("bad token"); } } assertTrue("client ctx not established.", clientContext.isEstablished()); assertTrue("server ctx not established.", serverContext.isEstablished()); } public void testInquireByOidClientOnly() throws Exception { ExtendedGSSContext cc = (ExtendedGSSContext)clientContext; ExtendedGSSContext sc = (ExtendedGSSContext)serverContext; sc.setOption(GSSConstants.REQUIRE_CLIENT_AUTH, Boolean.FALSE); sc.setOption(GSSConstants.ACCEPT_NO_CLIENT_CERTS, Boolean.TRUE); assertTrue(sc.getOption(GSSConstants.ACCEPT_NO_CLIENT_CERTS) == Boolean.TRUE); clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(false); establishContext(); Object tmp = null; X509Certificate[] chain = null; // should get server's chain tmp = cc.inquireByOid(GSSConstants.X509_CERT_CHAIN); assertTrue(tmp != null); assertTrue(tmp instanceof X509Certificate[]); chain = (X509Certificate[])tmp; assertTrue(chain.length > 0); // should be null since client auth disabled tmp = sc.inquireByOid(GSSConstants.X509_CERT_CHAIN); assertTrue(tmp == null); } public void testInquireByOidServerAlso() throws Exception { ExtendedGSSContext cc = (ExtendedGSSContext)clientContext; ExtendedGSSContext sc = (ExtendedGSSContext)serverContext; sc.setOption(GSSConstants.REQUIRE_CLIENT_AUTH, Boolean.FALSE); clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(false); establishContext(); Object tmp = null; X509Certificate[] chain = null; // should get server's chain tmp = cc.inquireByOid(GSSConstants.X509_CERT_CHAIN); assertTrue(tmp != null); assertTrue(tmp instanceof X509Certificate[]); chain = (X509Certificate[])tmp; assertTrue(chain.length > 0); // should get client's chain tmp = sc.inquireByOid(GSSConstants.X509_CERT_CHAIN); assertTrue(tmp != null); assertTrue(tmp instanceof X509Certificate[]); chain = (X509Certificate[])tmp; assertTrue(chain.length > 0); } // basic delegation tests public void testDelegation() throws Exception { // enable delegation clientContext.requestCredDeleg(true); assertTrue(clientContext.getCredDelegState()); clientContext.requestConf(true); ExtendedGSSContext ctx = (ExtendedGSSContext)clientContext; ctx.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_FULL); assertTrue(ctx.getOption(GSSConstants.DELEGATION_TYPE) == GSIConstants.DelegationType.FULL); ctx.setOption(GSSConstants.AUTHZ_REQUIRED_WITH_DELEGATION, Boolean.TRUE); establishContext(); ExtendedGSSCredential cred = null; cred = (ExtendedGSSCredential)serverContext.getDelegCred(); assertTrue(cred != null); X509Credential proxy = null; proxy = ((GlobusGSSCredentialImpl)cred).getX509Credential(); assertTrue(proxy != null); assertTrue( (proxy.getProxyType() == CertificateType.GSI_2_PROXY) || (proxy.getProxyType() == CertificateType.GSI_3_IMPERSONATION_PROXY) || (proxy.getProxyType() == CertificateType.GSI_4_IMPERSONATION_PROXY)); logger.debug(proxy); GSSManager manager = getGSSManager(); GSSCredential gssCred = manager.createCredential(GSSCredential.INITIATE_ONLY); // create server ctx using delegated cred serverContext = manager.createContext((GSSCredential)null); // create client ctx using default creds clientContext = manager.createContext(gssCred.getName(), GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); clientContext.requestCredDeleg(true); assertTrue(clientContext.getCredDelegState()); establishContext(); cred = (ExtendedGSSCredential)serverContext.getDelegCred(); assertTrue(cred != null); proxy = ((GlobusGSSCredentialImpl)cred).getX509Credential(); assertTrue(proxy != null); assertTrue( (proxy.getProxyType() == CertificateType.GSI_2_LIMITED_PROXY) || (proxy.getProxyType() == CertificateType.GSI_3_LIMITED_PROXY) || (proxy.getProxyType() == CertificateType.GSI_4_LIMITED_PROXY)); logger.debug(proxy); } public void testNewDelegation() throws Exception { // disable delegation clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(true); establishContext(); int i=0; byte [] input = new byte[0]; byte [] output = null; ExtendedGSSContext cl = (ExtendedGSSContext)clientContext; ExtendedGSSContext sr = (ExtendedGSSContext)serverContext; do { output = cl.initDelegation(null, null, 0, input, 0, input.length); if (i == 0) { // first token length should be greater then 1 assertTrue(output.length != 1); } input = sr.acceptDelegation(0, output, 0, output.length); i++; } while (!cl.isDelegationFinished()); assertTrue("client ctx not established.", cl.isDelegationFinished()); assertTrue("server ctx not established.", sr.isDelegationFinished()); ExtendedGSSCredential cred = null; cred = (ExtendedGSSCredential)sr.getDelegatedCredential(); assertTrue(cred != null); // disables wrap/unwrap of delegation tokens cl.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); assertTrue(cl.getOption(GSSConstants.GSS_MODE) == GSIConstants.MODE_SSL); sr.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); int reqLifetime = 240; // 4 minutes i = 0; input = new byte[0]; do { output = cl.initDelegation(cred, null, reqLifetime, input, 0, input.length); if (i == 0) { // first token should be of length 1 assertEquals(1, output.length); } input = sr.acceptDelegation(0, output, 0, output.length); i++; } while (!cl.isDelegationFinished()); assertTrue("client ctx not established.", cl.isDelegationFinished()); assertTrue("server ctx not established.", sr.isDelegationFinished()); cred = (ExtendedGSSCredential)sr.getDelegatedCredential(); assertTrue(cred != null); X509Credential globusCred = ((GlobusGSSCredentialImpl)cred).getX509Credential(); Date notAfter = globusCred.getCertificateChain()[0].getNotAfter(); Date notBefore = globusCred.getCertificateChain()[0].getNotBefore(); logger.debug(globusCred); int seconds = (int)((notAfter.getTime() - notBefore.getTime() - 5*60000) / 1000); assertEquals("lifetime", reqLifetime, seconds); } public void testContextExpiration() throws Exception { // disable delegation int time = 15; // 15 seconds; clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(true); // request short context life time clientContext.requestLifetime(time); // enable context expiration checking ExtendedGSSContext ctx = (ExtendedGSSContext)clientContext; ctx.setOption(GSSConstants.CHECK_CONTEXT_EXPIRATION, Boolean.TRUE); assertTrue(ctx.getOption(GSSConstants.CHECK_CONTEXT_EXPIRATION) == Boolean.TRUE); establishContext(); assertTrue(clientContext.getLifetime() > 0); Thread.sleep((int)(time * 1.3 * 1000)); assertTrue(clientContext.getLifetime() < 0); try { clientContext.wrap(MSG, 0, MSG.length, null); fail("Wrap() did not throw exeption as expected"); } catch (GSSException e) { if (e.getMajor() != GSSException.CONTEXT_EXPIRED) { e.printStackTrace(); fail("Unexpected GSSException"); } } try { clientContext.unwrap(MSG, 0, MSG.length, null); fail("Unwrap() did not throw exeption as expected"); } catch (GSSException e) { if (e.getMajor() != GSSException.CONTEXT_EXPIRED) { e.printStackTrace(); fail("Unexpected GSSException"); } } /* getMIC()/verifyMIC() not supported try { clientContext.getMIC(MSG, 0, MSG.length, null); fail("getMIC() did not throw exeption as expected"); } catch (GSSException e) { if (e.getMajor() != GSSException.CONTEXT_EXPIRED) { e.printStackTrace(); fail("Unexpected GSSException"); } } try { clientContext.verifyMIC(MSG, 0, MSG.length, MSG, 0, MSG.length, null); fail("verifyMIC() did not throw exeption as expected"); } catch (GSSException e) { if (e.getMajor() != GSSException.CONTEXT_EXPIRED) { e.printStackTrace(); fail("Unexpected GSSException"); } } */ } public void testLimitedProxyChecking() throws Exception { clientContext.requestCredDeleg(true); assertTrue(clientContext.getCredDelegState()); clientContext.requestConf(true); establishContext(); ExtendedGSSCredential cred = null; cred = (ExtendedGSSCredential)serverContext.getDelegCred(); assertTrue(cred != null); X509Credential proxy = null; proxy = ((GlobusGSSCredentialImpl)cred).getX509Credential(); assertTrue(proxy != null); assertTrue( (proxy.getProxyType() == CertificateType.GSI_2_LIMITED_PROXY) || (proxy.getProxyType() == CertificateType.GSI_3_LIMITED_PROXY) || (proxy.getProxyType() == CertificateType.GSI_4_LIMITED_PROXY)); GSSManager manager = getGSSManager(); // create server ctx using delegated cred serverContext = manager.createContext((GSSCredential)null); // create client ctx using default creds clientContext = manager.createContext(null, GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); ExtendedGSSContext sr = (ExtendedGSSContext)serverContext; sr.setOption(GSSConstants.REJECT_LIMITED_PROXY, Boolean.TRUE); assertTrue(sr.getOption(GSSConstants.REJECT_LIMITED_PROXY) == Boolean.TRUE); try { establishContext(); fail("establishContext() did not throw exception as expected"); } catch (GSSException e) { } // create server ctx using delegated cred serverContext = manager.createContext(cred); // create client ctx using default creds clientContext = manager.createContext(null, GSSConstants.MECH_OID, null, GSSContext.DEFAULT_LIFETIME); ExtendedGSSContext cl = (ExtendedGSSContext)clientContext; cl.setOption(GSSConstants.REJECT_LIMITED_PROXY, Boolean.TRUE); try { establishContext(); fail("establishContext() did not throw exception as expected"); } catch (GSSException e) { } } /* client has credentials but it requests to be anonymous */ public void testAnonymousClient1() throws Exception { clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); // request anonymity clientContext.requestAnonymity(true); // without this handshake will fail ExtendedGSSContext sr = (ExtendedGSSContext)serverContext; sr.setOption(GSSConstants.REQUIRE_CLIENT_AUTH, Boolean.FALSE); assertTrue(sr.getOption(GSSConstants.REQUIRE_CLIENT_AUTH) == Boolean.FALSE); establishContext(); assertTrue(clientContext.getSrcName().isAnonymous()); assertTrue(clientContext.getAnonymityState()); assertTrue(!clientContext.getTargName().isAnonymous()); assertTrue(serverContext.getSrcName().isAnonymous()); } /* client is initialized with anonymous credentials */ public void testAnonymousClient2() throws Exception { GSSManager manager = getGSSManager(); GSSName anonName = manager.createName((String)null, null); assertTrue(anonName.isAnonymous()); GSSCredential anonCred = manager.createCredential(anonName, GSSCredential.INDEFINITE_LIFETIME, (Oid)null, GSSCredential.INITIATE_AND_ACCEPT); assertTrue(anonCred.getName().isAnonymous()); // client ctx initalized with anon cred clientContext = manager.createContext(null, GSSConstants.MECH_OID, anonCred, GSSContext.DEFAULT_LIFETIME); // without this handshake will fail ExtendedGSSContext sr = (ExtendedGSSContext)serverContext; sr.setOption(GSSConstants.REQUIRE_CLIENT_AUTH, Boolean.FALSE); establishContext(); assertTrue(clientContext.getSrcName().isAnonymous()); assertTrue(clientContext.getAnonymityState()); assertTrue(serverContext.getSrcName().isAnonymous()); } /* checks if anonymity state is set correctly */ public void testAnonymousServer1() throws Exception { clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestAnonymity(false); // request anonymity - this should have no baring on server context serverContext.requestAnonymity(true); establishContext(); // should be false - client is not anonymous assertTrue(!serverContext.getAnonymityState()); } /* checks if anonymity state is set correctly */ public void testAnonymousServer2() throws Exception { clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestAnonymity(true); // request anonymity - this should have no baring on server context serverContext.requestAnonymity(true); // without this handshake will fail ExtendedGSSContext sr = (ExtendedGSSContext)serverContext; sr.setOption(GSSConstants.REQUIRE_CLIENT_AUTH, Boolean.FALSE); establishContext(); // should be true - client is anonymous assertTrue(serverContext.getAnonymityState()); } /* checks if server will catch an error where the cred is anonymous */ public void testAnonymousServer3() throws Exception { GSSManager manager = getGSSManager(); GSSName anonName = manager.createName((String)null, null); assertTrue(anonName.isAnonymous()); GSSCredential anonCred = manager.createCredential(anonName, GSSCredential.INDEFINITE_LIFETIME, (Oid)null, GSSCredential.INITIATE_AND_ACCEPT); assertTrue(anonCred.getName().isAnonymous()); // server ctx initalized with anon cred serverContext = manager.createContext(anonCred); try { establishContext(); fail("establishContext() did not throw exception as expected."); } catch (GSSException e) { if (e.getMajor() != GSSException.DEFECTIVE_CREDENTIAL) { e.printStackTrace(); fail("Unexpected GSSException"); } } } public void testBadUsage1() throws Exception { GSSManager manager = getGSSManager(); GSSCredential cred = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, (Oid)null, GSSCredential.INITIATE_ONLY); // creates an accepter context with credential that is // supposed to be used for initiators serverContext = manager.createContext(cred); try { establishContext(); fail("establishContext() did not throw exception as expected."); } catch (GSSException e) { if (e.getMajor() != GSSException.DEFECTIVE_CREDENTIAL) { e.printStackTrace(); fail("Unexpected GSSException"); } } } public void testBadUsage2() throws Exception { GSSManager manager = getGSSManager(); GSSCredential cred = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, (Oid)null, GSSCredential.ACCEPT_ONLY); // creates an initiator context with credential that is // supposed to be used for acceptor clientContext = manager.createContext(null, GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); try { establishContext(); fail("establishContext() did not throw exception as expected."); } catch (GSSException e) { if (e.getMajor() != GSSException.DEFECTIVE_CREDENTIAL) { e.printStackTrace(); fail("Unexpected GSSException"); } } } // basic request confidentiality tests public void testRequestConf1() throws Exception { // client requests confidentiality but server doesn't support it clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(true); serverContext.requestConf(false); establishContext(); assertTrue(clientContext.getConfState()); } public void testRequestConf2() throws Exception { // client requests No confidentiality but server doesn't support it clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(false); serverContext.requestConf(true); establishContext(); assertTrue(clientContext.getConfState()); } public void testRequestConf3() throws Exception { // Neither client nor server request confidentiality clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(false); serverContext.requestConf(false); establishContext(); assertTrue(!clientContext.getConfState()); } public void testRequestConf4() throws Exception { // client & server request confidentiality clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(true); serverContext.requestConf(true); establishContext(); assertTrue(clientContext.getConfState()); } /*getMIC()/verifyMIC() not supported // getMIC()/verifyMIC tests public void testMic1() throws Exception { clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(false); establishContext(); runMicTests(); } public void testMic2() throws Exception { clientContext.requestCredDeleg(false); assertTrue(!clientContext.getCredDelegState()); clientContext.requestConf(true); establishContext(); runMicTests(); } private void runMicTests() throws Exception { assertTrue("client ctx not established.", clientContext.isEstablished()); assertTrue("server ctx not established.", serverContext.isEstablished()); int [] msgSize = {10, 100, 1000, 10000, 16384, 100000}; for (int i=0;i 0); } public void testSerialisation() throws Exception { GSSCredential cred = manager.createCredential(GSSCredential.ACCEPT_ONLY); GSSCredential copy = serialiseAndDeserialise(cred); assertThat(copy, equalTo(cred)); } public void testEqualsForNull() throws GSSException { GSSCredential credential = manager.createCredential(GSSCredential.ACCEPT_ONLY); assertThat(credential, not(equalTo(null))); } public void testEqualsReflexive() throws GSSException { GSSCredential credential = manager.createCredential(GSSCredential.ACCEPT_ONLY); assertThat(credential, equalTo(credential)); } public void testEqualsForSameCredential() throws GSSException { GSSCredential cred1 = manager.createCredential(GSSCredential.ACCEPT_ONLY); GSSCredential cred2 = manager.createCredential(GSSCredential.ACCEPT_ONLY); assertThat(cred1, equalTo(cred2)); assertThat(cred2, equalTo(cred1)); } public void testEqualsForDifferentUsage() throws GSSException { GSSCredential cred1 = manager.createCredential(GSSCredential.ACCEPT_ONLY); GSSCredential cred2 = manager.createCredential(GSSCredential.DEFAULT_LIFETIME); assertThat(cred1, not(equalTo(cred2))); assertThat(cred2, not(equalTo(cred1))); } public void testEqualsForEqualX509Credential() throws Exception { X509Credential x509 = buildSelfSigned(); GSSCredential cred1 = buildCredential(x509, GSSCredential.DEFAULT_LIFETIME); GSSCredential cred2 = buildCredential(x509, GSSCredential.DEFAULT_LIFETIME); assertThat(cred1, equalTo(cred2)); assertThat(cred2, equalTo(cred1)); } public void testEqualsForDifferentX509Credentials() throws Exception { GSSCredential cred1 = buildSelfSigned(GSSCredential.DEFAULT_LIFETIME); GSSCredential cred2 = buildSelfSigned(GSSCredential.DEFAULT_LIFETIME); assertThat(cred1, not(equalTo(cred2))); assertThat(cred2, not(equalTo(cred1))); } private GSSCredential buildSelfSigned(int usage) throws GeneralSecurityException, GSSException { return buildCredential(buildSelfSigned(), usage); } private GSSCredential buildCredential(X509Credential credential, int usage) throws GSSException { X509Credential.setDefaultCredential(credential); return manager.createCredential(usage); } private X509Credential buildSelfSigned() throws GeneralSecurityException { KeyPair kp = kpg.generateKeyPair(); PrivateKey privateKey = kp.getPrivate(); certificateGenerator.setPublicKey(kp.getPublic()); X509Certificate certificate = certificateGenerator.generate(privateKey); X509Certificate[] certChain = new X509Certificate[]{certificate}; return new X509Credential(privateKey, certChain); } private GlobusGSSCredentialImpl serialiseAndDeserialise(GSSCredential credential) throws IOException, ClassNotFoundException { if(!(credential instanceof GlobusGSSCredentialImpl)) { throw new RuntimeException("credential not a GlobusGSSCredentialImpl"); } ByteArrayOutputStream storage = new ByteArrayOutputStream(); new ObjectOutputStream(storage).writeObject(credential); byte[] data = storage.toByteArray(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data)); return (GlobusGSSCredentialImpl) in.readObject(); } } JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/gsi/gssapi/test/GlobusGSSNameTest.java000066400000000000000000000136421241116057200325150ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.test; import org.globus.gsi.gssapi.GlobusGSSName; import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSException; import junit.framework.TestCase; public class GlobusGSSNameTest extends TestCase { public void testParse() throws Exception { GSSName name = null; name = new GlobusGSSName("/C=US"); name = new GlobusGSSName("/C=US/O=ANL"); name = new GlobusGSSName("/C=US/O=Globus/O=ANL/OU=MCS/CN=gawor/CN=proxy"); name = new GlobusGSSName("/C=US/O=Globus/O=ANL/OU=MCS/CN=gawor/CN=host/tlager-mbp.mcs.anl.gov"); name = new GlobusGSSName("/C=US/O=Globus/O=ANL/OU=MCS/CN=host/tlager-mbp.mcs.anl.gov/CN=gawor"); name = new GlobusGSSName("/C=US/CN=host/pitcairn.mcs.anl.gov/CN=gawor+OU=ANL"); name = new GlobusGSSName("/C=US/CN=gawor+OU=ANL/CN=host/tlager-mbp.mcs.anl.gov"); } public void testAnonymous() throws Exception { GSSName name; name = new GlobusGSSName((String)null); assertTrue(name.isAnonymous()); name = new GlobusGSSName("/C=US/O=Globus/O=ANL/CN=gawor", null); assertTrue(!name.isAnonymous()); } public void testEquals() throws Exception { GSSName n1 = new GlobusGSSName(); GSSName n2 = new GlobusGSSName((String)null); GSSName n3 = new GlobusGSSName("/C=US/O=Globus/O=ANL/OU=MCS/CN=gawor/CN=proxy"); GSSName n4 = new GlobusGSSName("/C=US/O=Globus/O=ANL/OU=MCS/CN=gawor"); GSSName n5 = new GlobusGSSName("/C=US/O=Globus/O=ANL/OU=MCS/CN=gawor/CN=proxy"); assertTrue(n1.equals(n1)); assertTrue(n2.equals(n2)); assertTrue(n3.equals(n3)); assertTrue(n4.equals(n4)); assertTrue(n1.equals(n2)); assertTrue(!n2.equals(n3)); assertTrue(!n3.equals(n4)); assertTrue(n5.equals(n3)); assertTrue(!n5.equals(n4)); } public void testConversion() throws Exception { GSSName n1 = new GlobusGSSName("ftp@140.221.11.99", GSSName.NT_HOSTBASED_SERVICE); assertEquals("/CN=ftp/tlager-mbp.mcs.anl.gov", n1.toString()); GSSName n2 = new GlobusGSSName("/C=US/O=Globus/O=ANL/CN=gawor", null); assertEquals("/C=US/O=Globus/O=ANL/CN=gawor", n2.toString()); } public void testBadHostbasedService() throws Exception { try { GSSName n1 = new GlobusGSSName("host@", GSSName.NT_HOSTBASED_SERVICE); fail("Did not thrown exception."); } catch (GSSException e) { } try { GSSName n2 = new GlobusGSSName("host/tlager-mbp.mcs.anl.gov", GSSName.NT_HOSTBASED_SERVICE); fail("Did not thrown exception."); } catch (GSSException e) { } GSSName n3 = new GlobusGSSName("host@tlager-mbp.mcs.anl.gov", GSSName.NT_HOSTBASED_SERVICE); GSSName n4 = new GlobusGSSName("/C=US/O=Globus/CN=tlager-mbp.mcs-7.anl.gov", null); GSSName n5 = new GlobusGSSName("/C=US/O=Globus/CN=tlager-mbp-8", null); // test with interface name, host cn entry at the end GSSName n6 = new GlobusGSSName("/C=US/O=Globus/CN=tlager-mbp-9.mcs.anl.gov", null); // test with interface name, host cn entry in the middle GSSName n7 = new GlobusGSSName("/C=US/CN=tlager-mbp-9.mcs.anl.gov/O=Globus", null); // test with regular, host cn entry in the middle GSSName n8 = new GlobusGSSName("/C=US/CN=tlager-mbp.mcs.anl.gov/O=Globus", null); // test with regular name, host cn entry at the end GSSName n9 = new GlobusGSSName("/C=US/O=Globus/CN=tlager-mbp.mcs.anl.gov", null); assertTrue(!n3.equals(n4)); assertTrue(!n3.equals(n5)); assertTrue(n3.equals(n6)); assertTrue(n3.equals(n7)); assertTrue(n3.equals(n8)); assertTrue(n3.equals(n9)); } public void testHostbasedService2() throws Exception { GSSName n1 = new GlobusGSSName("host@cvs.globus.org", GSSName.NT_HOSTBASED_SERVICE); GSSName n2 = new GlobusGSSName("/C=US/O=Globus/CN=globuscvs.mcs.anl-external.org", null); assertEquals("/CN=host/globuscvs.mcs.anl-external.org", n1.toString()); assertTrue(n1.equals(n2)); GSSName m1 = new GlobusGSSName("host@dc.isi.edu", GSSName.NT_HOSTBASED_SERVICE); GSSName m2 = new GlobusGSSName("/C=US/O=Globus/CN=dc-user2.isi.edu", null); assertEquals("/CN=host/dc-user2.isi.edu", m1.toString()); assertTrue(m1.equals(m2)); } public void testHostbasedService3() throws Exception { GSSName n1 = new GlobusGSSName("host@tlager-mbp.mcs.anl.gov", GSSName.NT_HOSTBASED_SERVICE); GSSName n2 = new GlobusGSSName("/C=US/O=Globus/CN=host/tlager-mbp.mcs.anl.gov/CN=12345678", null); assertTrue(n1.equals(n2)); } public void testEquals2() throws Exception { GSSName n1 = new GlobusGSSName("host@tlager-mbp.mcs.anl.gov", GSSName.NT_HOSTBASED_SERVICE); GSSName n2 = new GlobusGSSName("/C=US/O=Globus/CN=tlager-mbp.mcs.anl.gov", null); GSSName n3 = new GlobusGSSName("/C=US/O=Globus/CN=host/tlager-mbp.MCS.anl.gov", null); GSSName n4 = new GlobusGSSName("/C=US/O=Globus/CN=ftp/tlager-mbp.mcs.anl.gOv", null); GSSName n5 = new GlobusGSSName("ftp@tlager-mbp.mcs.anl.gov", GSSName.NT_HOSTBASED_SERVICE); GSSName n6 = new GlobusGSSName("host@140.221.11.99", GSSName.NT_HOSTBASED_SERVICE); GSSName n7 = new GlobusGSSName("/C=US/O=Globus/CN=tlager-mbp-9.mcs.anl.gov", null); assertTrue(n1.equals(n1)); assertTrue(n2.equals(n2)); assertTrue(n1.equals(n2)); assertTrue(n2.equals(n1)); assertTrue(n1.equals(n3)); assertTrue(n3.equals(n1)); assertTrue(!n4.equals(n1)); assertTrue(n5.equals(n4)); assertTrue(n4.equals(n5)); assertTrue(!n1.equals(n5)); assertTrue(n1.equals(n6)); assertTrue(n7.equals(n6)); assertTrue(!n2.equals(n3)); assertTrue(!n3.equals(n4)); assertTrue(!n4.equals(n7)); } } JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/net/000077500000000000000000000000001241116057200241325ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/net/test/000077500000000000000000000000001241116057200251115ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/java/org/globus/net/test/GSIHttpURLConnectionTest.java000066400000000000000000000105201241116057200324770ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.net.test; import java.net.URL; import java.net.URLConnection; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import org.globus.net.GlobusURLStreamHandlerFactory; import org.globus.net.GSIURLConnection; import org.globus.net.GSIHttpURLConnection; import org.globus.gsi.GSIConstants; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; // Needs to be improved - parameters loaded from cfg file public class GSIHttpURLConnectionTest extends TestCase { static { URL.setURLStreamHandlerFactory(new GlobusURLStreamHandlerFactory()); } public GSIHttpURLConnectionTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(GSIHttpURLConnectionTest.class); } public void test1() throws Exception { URL u = new URL("httpg://localhost:2119/jobmanager"); URLConnection con = u.openConnection(); assertTrue(con instanceof GSIURLConnection); try { InputStream in = con.getInputStream(); fail("did not throw exception"); } catch (IOException e) { // everything is cool } finally { ((GSIURLConnection)con).disconnect(); } } public void test2() throws Exception { URL u = new URL("httpg://localhost:2119/jobmanager"); URLConnection con = u.openConnection(); assertTrue(con instanceof GSIURLConnection); ((GSIURLConnection)con).setDelegationType(GSIConstants.DELEGATION_FULL); try { InputStream in = con.getInputStream(); fail("did not throw exception"); } catch (IOException e) { // everything is cool } finally { ((GSIURLConnection)con).disconnect(); } } /* public void testGET() throws Exception { URL url = new URL("https://localhost:8443/wsrf/services/ContainerRegistryService?wsdl"); GSIHttpURLConnection con = new GSIHttpURLConnection(url); ((GSIURLConnection)con).setGSSMode(GSIConstants.MODE_SSL); InputStream in = con.getInputStream(); int ch; StringBuffer buf = new StringBuffer(); while( (ch = in.read()) != -1 ) { System.out.print((char)ch); buf.append((char)ch); } con.disconnect(); assertTrue(buf.toString().indexOf("wsdl:import") != -1); } public void testPUT() throws Exception { URL url = new URL("https://localhost:8443/wsrf/services/ContainerRegistryService"); GSIHttpURLConnection con = new GSIHttpURLConnection(url); ((GSIURLConnection)con).setGSSMode(GSIConstants.MODE_SSL); String request = "ns1:Entry"; OutputStream out = con.getOutputStream(); out.write(request.getBytes("UTF8")); out.flush(); InputStream in = con.getInputStream(); int ch; StringBuffer buf = new StringBuffer(); while( (ch = in.read()) != -1 ) { System.out.print((char)ch); buf.append((char)ch); } con.disconnect(); assertTrue(buf.toString().indexOf("ServiceGroupEntryEPR") != -1); } */ } JGlobus-JGlobus-Release-2.1.0/gss/src/test/resources/000077500000000000000000000000001241116057200223535ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/resources/log4j.properties000066400000000000000000000005631241116057200255140ustar00rootroot00000000000000log4j.rootCategory=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c{2} %x - %m%n log4j.category.COM.claymoresystems.ptls.SSLDebug=OFF log4j.category.org.globus.security.gridmap=ERROR log4j.logger.org.globus.security.filestore=INFO JGlobus-JGlobus-Release-2.1.0/gss/src/test/resources/org/000077500000000000000000000000001241116057200231425ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/resources/org/globus/000077500000000000000000000000001241116057200244355ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/resources/org/globus/gsi/000077500000000000000000000000001241116057200252175ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/resources/org/globus/gsi/gssapi/000077500000000000000000000000001241116057200265055ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/gss/src/test/resources/org/globus/gsi/gssapi/errors.properties000066400000000000000000000044241241116057200321430ustar00rootroot00000000000000badType = [JGLOBUS-39] Invalid option type. Expected {1} type nullOption = [JGLOBUS-40] Option cannot be null nullOptionValue = [JGLOBUS-41] Option value cannot be null badDelegType = [JGLOBUS-42] Delegation type not supported badGssMode = [JGLOBUS-43] GSS mode not supported unknownOption = [JGLOBUS-44] Option {0} not supported replayDet = [JGLOBUS-45] Replay detection is always enabled seqDet = [JGLOBUS-46] Sequence checking is always enabled integOn = [JGLOBUS-47] Integrity is always enabled mutualAuthOn = [JGLOBUS-48] Mutual authentication is always enabled tokenFail00 = [JGLOBUS-49] Token length of {0} does not match size of message digest {1} tokenFail01 = [JGLOBUS-50] Message buffer length of {0} does not match expected length of {1} in token tokenFail02 = [JGLOBUS-51] Message digest and token's contents are not equal tokenFail03 = [JGLOBUS-52] Invalid token badLifetime00 = [JGLOBUS-53] Indefinite lifetime not supported badLifetime01 = [JGLOBUS-54] Credential lifetime not supported proxyViolation = [JGLOBUS-55] Limited proxies not accepted authFailed00 = [JGLOBUS-56] Authorization failed. Expected "{0}" target but received "{1}" initCtx00 = [JGLOBUS-57] Cannot request delegation in SSL compatibility mode initCtx01 = [JGLOBUS-58] Cannot request delegation and be anonymous initCtx02 = [JGLOBUS-59] Cannot request delegation without authorization (target name null) acceptCtx00 = [JGLOBUS-60] Non-anonymous credential required for acceptor badCredUsage = [JGLOBUS-61] Invalid credential usage noClientCert = [JGLOBUS-62] Client certificates expected invalidBuf = [JGLOBUS-63] Invalid buffer delegError00 = [JGLOBUS-64] Invalid initial hello message, expecting: "D", received: {0} badName00 = [JGLOBUS-65] Bad hostbased service name. "@" missing anonCred00 = [JGLOBUS-66] Cannot export anonymous credential notCACert = [JGLOBUS-67] The signing certificate is not a CA certificate (has no BasicConstraint extension) proxySign = [JGLOBUS-68] Invalid proxy certificate noCaCerts = [JGLOBUS-69] Cannot find any trusted certificates keyMismatch = [JGLOBUS-70] Private/Public key mismatch invalidJaasSubject = [JGLOBUS-71] Invalid JaasSubject provider class: \"{0}\" className loadError = [JGLOBUS-72] Unable to load \"{0}\" class instanError = [JGLOBUS-73] Unable to instantiate \"{0}\" class JGlobus-JGlobus-Release-2.1.0/io/000077500000000000000000000000001241116057200164065ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/README.textile000066400000000000000000000000001241116057200207310ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/pom.xml000066400000000000000000000016271241116057200177310ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 io Globus IO implementation ${project.groupId} gridftp ${project.version} ${project.groupId} gram ${project.version} junit junit test JGlobus-JGlobus-Release-2.1.0/io/src/000077500000000000000000000000001241116057200171755ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/000077500000000000000000000000001241116057200201215ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/000077500000000000000000000000001241116057200210425ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/000077500000000000000000000000001241116057200216315ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/000077500000000000000000000000001241116057200231245ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/000077500000000000000000000000001241116057200235335ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/000077500000000000000000000000001241116057200244705ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/client/000077500000000000000000000000001241116057200257465ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/client/GassException.java000066400000000000000000000013601241116057200313650ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.gass.client; public class GassException extends Exception { public GassException(String msg) { super(msg); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/client/internal/000077500000000000000000000000001241116057200275625ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/client/internal/GASSProtocol.java000066400000000000000000000051621241116057200327100ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.gass.client.internal; import org.globus.util.http.HTTPProtocol; /** This is a pure Java implementation of the Globus GASS protocol. Normally * one does not need to use this class directly but instead uses the Client * class. */ public class GASSProtocol { /** the default user agent string */ private static final String USER_AGENT = "Java-Globus-GASS-HTTP/1.1.0"; /** the default gass append url */ private static final String APPEND_URI = "/globus-bins/GASSappend?"; private static final String TYPE = "application/octet-stream"; /** This method concatenates a properly formatted header for performing * Globus Gass GETs with the given information. * * @param path the path of the file to get * @param host the host which contains the file to get * * @return String the properly formatted header to be sent to a * gass server */ public static String GET(String path, String host) { return HTTPProtocol.createGETHeader("/" + path, host, USER_AGENT); } /** This method concatenates a properly formatted header for performing * Globus Gass PUTs with the given information. * * @param path the path of the remote file to put to * @param host the host of the remote file to put to * @param length the length of data which will be sent (the size of the file) * @param append append mode * * @return String the properly formatted header to be sent to a * gass server */ public static String PUT(String path, String host, long length, boolean append) { String newPath = null; if (append) { newPath = APPEND_URI + "/" + path; } else { newPath = "/" + path; } return HTTPProtocol.createPUTHeader(newPath, host, USER_AGENT, TYPE, length, append); } public static String SHUTDOWN(String path, String host) { return HTTPProtocol.createPUTHeader(path, host, USER_AGENT, TYPE, 0, false); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/client/internal/package.html000066400000000000000000000010231241116057200320370ustar00rootroot00000000000000 org.globus.gass.client.internal package Low-level protocol classes used by the org.globus.io.gass.client package.

    Package Specification

    (none)

    Related Documentation

    For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/client/package.html000066400000000000000000000010121241116057200302210ustar00rootroot00000000000000 org.globus.gass.client package Provides a pure Java Globus GASS client for transferring files via HTTPS.

    Package Specification

    (none)

    Related Documentation

    For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/package.html000066400000000000000000000020451241116057200267520ustar00rootroot00000000000000 org.globus.io.gass package This library provides client and server GASS functionality. Java GASS implementation is fully compatible with Globus GASS. It allows, for example, a Java GASS client to connect and transfer a file from a Globus GASS server; or a Globus GASS client to connect and transfer a file from a Java GASS server.
    The Java GASS client provides the file-access API, while the Java GASS server provides the 'server-ez' API. Java Globus does not support the cache management functionality at this point; nor does it follow the full client and server C API.

    Package Specification

    Related Documentation

    For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/server/000077500000000000000000000000001241116057200257765ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/server/GassServer.java000066400000000000000000000451151241116057200307330ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.gass.server; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.net.Socket; import java.net.URLDecoder; import java.util.Hashtable; import org.globus.util.GlobusURL; import org.globus.util.http.HttpResponse; import org.globus.io.gass.client.internal.GASSProtocol; import org.globus.net.BaseServer; import org.globus.net.SocketFactory; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.globus.gsi.gssapi.auth.AuthorizationException; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSContext; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The GassServer class acts as a basic multi-threaded HTTPS * server that handles GASS requests. * * @version $Revision 1.21 $ */ public class GassServer extends BaseServer { private static Log logger = LogFactory.getLog(GassServer.class.getName()); public static final int READ_ENABLE = 8; public static final int WRITE_ENABLE = 16; public static final int STDOUT_ENABLE = 32; public static final int STDERR_ENABLE = 64; public static final int CLIENT_SHUTDOWN_ENABLE = 128; public static final String SHUTDOWN_STR = "/dev/globus_gass_client_shutdown"; private Hashtable jobOutputs = null; private int options = 0; /** * Starts Gass Server with default user credentials. * Port of the server will be dynamically assigned */ public GassServer() throws IOException { this(null, 0); } /** * Starts Gass Server on given port with default user credentials. * * @param port * port of the server, if 0 it will be dynamically assigned */ public GassServer(int port) throws IOException { this(null, port); } /** * Starts Gass Server on given port and given credentials. * * @param cred * credentials to use. if null default user credentials * will be used * @param port * port of the server, if 0 it will be dynamically assigned */ public GassServer(GSSCredential cred, int port) throws IOException { super(cred, port); init(); } /** * Starts Gass Server on given port and mode. * If secure mode, it will use default user credentials * * @param secure * if true starts server in secure mode, otherwise unsecure * @param port * port of the server, if 0 it will be dynamically assigned */ public GassServer(boolean secure, int port) throws IOException { super(secure, port); init(); } private void init() { jobOutputs = new Hashtable(); options = READ_ENABLE | WRITE_ENABLE | STDOUT_ENABLE | STDERR_ENABLE; super.initialize(); setAuthorization(SelfAuthorization.getInstance()); } /** * Sets the options of the gass server such * as enabling client shutdown, etc. * * @param options server options */ public void setOptions(int options) { this.options = options; } /** * Returns current options of the server. * * @return options of the server. O if not * none set. */ public int getOptions() { return options; } /** * Registers a output stream with a job. This is * used for job stdout/err redirection. * The label of the job should be the ending of the * job redirected url. For example, given following RSL * (stdout=$(GASS_URL)/dev/stdout-5) the label to register * the output stream with should be 'out-5'. * * @param lb job label as described above. * @param out the output stream to redirect output to. */ public void registerJobOutputStream(String lb, OutputStream out) { jobOutputs.put(lb, out); } /** * Unregisters a job output stream for specified output label. See * registerJobOutputStream() for more details. * * @param lb job output label. */ public void unregisterJobOutputStream(String lb) { jobOutputs.remove(lb); } /** * Unregisters a job output stream. This method is deprecated. */ public void unregisterJobOutputStream(String lb, OutputStream out) { unregisterJobOutputStream(lb); } protected OutputStream getJobOutputStream(String id) { return (OutputStream)jobOutputs.get(id); } protected void handleConnection(Socket socket) { GassClientHandler gcb = new GassClientHandler(this, socket); (new Thread(gcb)).start(); } public String toString() { StringBuffer buf = new StringBuffer("GassServer: "); try { buf.append(getURL()); } catch(Exception e) {} buf.append(" options ("); boolean op = ((options & READ_ENABLE) != 0); buf.append("r:" + ( (op) ? "+" : "-" )); op = ((options & WRITE_ENABLE) != 0); buf.append(" w:" + ( (op) ? "+" : "-" )); op = ((options & STDOUT_ENABLE) != 0); buf.append(" so:" + ( (op) ? "+" : "-")); op = ((options & STDERR_ENABLE) != 0); buf.append(" se:" + ( (op) ? "+" : "-")); op = ((options & CLIENT_SHUTDOWN_ENABLE) != 0); buf.append(" rc:" + ( (op) ? "+" : "-")); buf.append(")"); return buf.toString(); } /** * Shutdowns a remote gass server. The server must have the * CLIENT_SHUTDOWN option enabled for this to work. * * @param cred credentials to use. * @param gassURL the url of the remote gass server. */ public static void shutdown(GSSCredential cred, GlobusURL gassURL) throws IOException, GSSException { OutputStream output = null; InputStream input = null; Socket socket = null; try { if (gassURL.getProtocol().equalsIgnoreCase("https")) { GSSManager manager = ExtendedGSSManager.getInstance(); ExtendedGSSContext context = (ExtendedGSSContext)manager.createContext(null, GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); GssSocketFactory factory = GssSocketFactory.getDefault(); socket = factory.createSocket(gassURL.getHost(), gassURL.getPort(), context); ((GssSocket)socket).setAuthorization(SelfAuthorization.getInstance()); } else { SocketFactory factory = SocketFactory.getDefault(); socket = factory.createSocket(gassURL.getHost(), gassURL.getPort()); } output = socket.getOutputStream(); input = socket.getInputStream(); String msg = GASSProtocol.SHUTDOWN(SHUTDOWN_STR, gassURL.getHost()); if (logger.isTraceEnabled()) { logger.trace("Shutdown msg: " + msg); } output.write( msg.getBytes() ); output.flush(); HttpResponse rp = new HttpResponse(input); if (rp.httpCode == -1 && rp.httpMsg == null) { /* this is a workaround for C gass-server. * The server just shuts down - it does * not send the reply */ } else if (rp.httpCode != 200) { throw new IOException("Remote shutdown failed (" + rp.httpCode + " " + rp.httpMsg + ")"); } } finally { try { if (output != null) output.close(); if (input != null) input.close(); if (socket != null) socket.close(); } catch(Exception e) {} } } } class GassClientHandler implements Runnable { private static Log logger = LogFactory.getLog(GassClientHandler.class.getName()); private static final boolean DEBUG_ON = false; private static final String CRLF = "\r\n"; private static final String OKHEADER = "HTTP/1.1 200 OK\r\n"; private static final String SERVER = "Server: Globus-GASS-HTTP/1.1.0\r\n"; private static final String CONTENT_LENGTH = "Content-Length:"; private static final String TRANSFER_ENCODING = "Transfer-Encoding: chunked"; private static final String JAVA_CLIENT = "User-Agent: Java-Globus-GASS-HTTP/1.1.0"; private static final String HTTP_CONTINUE = "HTTP/1.1 100 Continue\r\n"; private static final String CONTENT_BINARY = "Content-Type: application/octet-stream" + CRLF; private static final String CONTENT_HTML = "Content-Type: text/html" + CRLF; private static final String CONTENT_TEXT = "Content-Type: text/plain" + CRLF; private static final String CONNECTION_CLOSE = "Connection: close\r\n"; private static final String HEADER404 = "HTTP/1.1 404 File Not Found\r\n"; private static final String MSG404 = "404 File Not Found\r\n" + "

    404 File Not Found

    \r\n"; private int BUFFER_SIZE = 4096; private GassServer server; private Socket socket; private int options; public GassClientHandler(GassServer server, Socket socket) { this.server = server; this.socket = socket; this.options = server.getOptions(); } private void write(OutputStream out, String msg) throws IOException { out.write(msg.getBytes()); out.flush(); } private void writeln(OutputStream out, String msg) throws IOException { out.write(msg.getBytes()); out.write(SERVER.getBytes()); out.write(CRLF.getBytes()); out.flush(); } /** * Listen on the server socket for a client, start another thread to * keep listening on the server socket, then deal with the client. */ public void run() { InputStream in = null; OutputStream out = null; try { in = socket.getInputStream(); out = socket.getOutputStream(); try { String line; line = readLine(in); if (DEBUG_ON) debug("header: " + line); if (line.startsWith("GET") && (options & GassServer.READ_ENABLE) != 0) { // copy to client String path = line.substring(4, line.indexOf(' ', 4) ); do { line = readLine(in); if (DEBUG_ON) debug("header (get): " + line); } while ( (line.length() != 0) && (line.charAt(0) != '\r') && (line.charAt(0) != '\n') ); transfer(out, path); } else if (line.startsWith("PUT") && ( ((options & GassServer.WRITE_ENABLE) != 0) || ((options & GassServer.CLIENT_SHUTDOWN_ENABLE) != 0) )) { // copy from client String path = line.substring(4, line.indexOf(' ', 4) ); transfer(in, path, false, out); writeln(out, OKHEADER); } else if (line.startsWith("POST") && ( ((options & GassServer.WRITE_ENABLE) != 0) || ((options & GassServer.STDOUT_ENABLE) != 0) || ((options & GassServer.STDERR_ENABLE) != 0) || ((options & GassServer.CLIENT_SHUTDOWN_ENABLE) != 0) )) { // append from client int index = line.indexOf('?') + 1; String path = line.substring(index, line.indexOf(' ', index) ); transfer(in, path, true, out); writeln(out, OKHEADER); } else { writeln(out, "HTTP/1.1 400 Bad Request" + CRLF); } } catch (FileNotFoundException ex) { logger.debug("FileNotFoundException occured: " + ex.getMessage(), ex); StringBuffer buf = new StringBuffer(HEADER404) .append(CONNECTION_CLOSE) .append(SERVER) .append(CONTENT_HTML) .append(CONTENT_LENGTH).append(" ").append(MSG404.length()) .append(CRLF).append(CRLF) .append(MSG404); out.write(buf.toString().getBytes()); out.flush(); } catch (AuthorizationException ex) { logger.debug("Exception occured: Authorization failed"); writeln(out, "HTTP/1.1 401 Authorization Failed" + CRLF); } catch (Exception ex) { logger.debug("Exception occured: " + ex.getMessage(), ex); writeln(out, "HTTP/1.1 400 " + ex.getMessage() + CRLF); } } catch (IOException e) { logger.error("Error writing response: " + e.getMessage(), e); } finally { try { socket.close(); } catch (IOException e) {} } } private String decodeUrlPath(String path) { if (path.length() == 0) return path; if (path.charAt(0) == '/') path = path.substring(1); try { return URLDecoder.decode(path); } catch(Exception e) { return path; } } /** * Transfer from a file, given its path, to the given OutputStream. * The BufferedWriter points to the same stream but is used to write * HTTP header information. */ private void transfer(OutputStream os, String path) throws IOException { path = decodeUrlPath(path); File f = new File(path); FileInputStream file = new FileInputStream(f); long length = f.length(); StringBuffer buf = new StringBuffer(OKHEADER) .append(CONNECTION_CLOSE) .append(SERVER) .append(CONTENT_BINARY) .append(CONTENT_LENGTH).append(" ").append(length) .append(CRLF).append(CRLF); os.write(buf.toString().getBytes()); os.flush(); byte [] buffer = new byte[BUFFER_SIZE]; int read; while (length != 0) { read = file.read(buffer); if (read == -1) break; os.write(buffer, 0, read); length -= read; } file.close(); os.flush(); os.close(); } private OutputStream pickOutputStream(String path, String str, OutputStream def) { int strl = str.length(); int pos = path.indexOf(str); if (pos != -1) { OutputStream out = server.getJobOutputStream(path.substring(pos + strl - 3)); if (out == null) { return def; } else { return out; } } return null; } /** * Transfer from the given InputStream to a file, given its path. * The Reader points to the same stream but is used to read * the HTTP header information. */ private void transfer(InputStream is, String path, boolean append, OutputStream outs) throws IOException { if (((options & GassServer.CLIENT_SHUTDOWN_ENABLE) != 0) && path.indexOf(GassServer.SHUTDOWN_STR) != -1) { server.shutdown(); return; } OutputStream out = null; String line; long length = 0; boolean chunked = false; boolean javaclient = false; do { line = readLine(is); if (DEBUG_ON) debug("header (put/post): " + line); if (line.startsWith(CONTENT_LENGTH)) { length = Long.parseLong( line.substring( line.indexOf(':') + 1 ).trim() ); } else if (line.startsWith(TRANSFER_ENCODING)) { chunked = true; } else if (line.startsWith(JAVA_CLIENT)) { javaclient = true; } } while ( (line.length() != 0) && (line.charAt(0) != '\r') && (line.charAt(0) != '\n') ); out = pickOutputStream(path, "/dev/stdout", System.out); if (out != null) { // this is stdout if ( (options & GassServer.STDOUT_ENABLE) == 0 ) { throw new IOException("Bad Request"); } } else { out = pickOutputStream(path, "/dev/stderr", System.err); if (out != null) { // this is stderr if ( (options & GassServer.STDERR_ENABLE) == 0 ) { throw new IOException("Bad Request"); } } else { // this is a file if ( (options & GassServer.WRITE_ENABLE) == 0 ) { throw new IOException("Bad Request"); } path = decodeUrlPath(path); out = new FileOutputStream(path, append); } } if (javaclient) { writeln(outs, HTTP_CONTINUE); } byte [] buffer = new byte[BUFFER_SIZE]; int read; if (!chunked) { while (length != 0) { read = is.read(buffer); if (read == -1) break; out.write(buffer, 0, read); length -= read; } } else { /* * Chunks are of the form * * lengthCRLF * dataCRLF * * which can be repeated ad infinitum until we meet * * 0CRLF * CRLF * * NOTE: length is represented in hex! * */ long chunkLength; int bytes; do { line = readLine(is); length = fromHex(line); if (DEBUG_ON) debug("chunk: '" + line + "' size:" + length); chunkLength = length; while (chunkLength != 0) { if (chunkLength > buffer.length) { bytes = buffer.length; } else { bytes = (int)chunkLength; } read = is.read(buffer, 0, bytes); if (read == -1) break; out.write(buffer, 0, read); chunkLength -= read; } is.read(); // skip CR is.read(); // skip LF } while (length > 0); if (DEBUG_ON) debug("finished chunking"); } out.flush(); // do not close System.out or System.err! if (out == System.out || out == System.err) return; out.close(); } /** * Read a line of text from the given Stream and return it * as a String. Assumes lines end in CRLF. */ private String readLine(InputStream in) throws IOException { StringBuffer buf = new StringBuffer(); int c, length = 0; while(true) { c = in.read(); if (c == -1 || c == '\n' || length > 512) { break; } else if (c == '\r') { in.read(); return buf.toString(); } else { buf.append((char)c); length++; } } return buf.toString(); } /** * Convert a String representing a hex number to a long. */ private long fromHex(String s) { long result = 0; int size = s.length(); for (int i = 0; i < size; i++) { char c = s.charAt(i); result *= 16; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': result += (c - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': result += (c - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': result += (c - 'A' + 10); break; default : // TODO: throw a ParseException } } return result; } private void debug(String msg) { System.err.println(msg); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/server/JobOutputListener.java000066400000000000000000000017741241116057200323130ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.gass.server; /** * This class defines a job output listener. */ public interface JobOutputListener { /** * It is called whenever the job's output * has been updated. * * @param output new output */ public void outputChanged(String output); /** * It is called whenever job finished * and no more output will be generated. */ public void outputClosed(); } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/server/JobOutputStream.java000066400000000000000000000045001241116057200317470ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.gass.server; import java.io.OutputStream; import java.io.IOException; /** * This is a small class that allows to redirect * a job's output to a custom job output listener. * That is, a listener that presents/displays the * job output in a specific way. For example, this * class can be used to redirect a job's output * to a window. *

    * This class is specificaly designed for jobs * that generate textual output. Binary data * might not be handled correctly. */ public class JobOutputStream extends OutputStream { protected JobOutputListener listener; /** * Creates a job output stream with a specific * job output listener to which the job output * will be redirected to. * * @param jobListener an instance of the job output * listener. Cannot be null. */ public JobOutputStream(JobOutputListener jobListener) { if (jobListener == null) { throw new IllegalArgumentException("jobListener cannot be null"); } listener = jobListener; } /** * Converts the byte array to a string and forwards * it to the job output listener. *
    Called by the GassServer. */ public void write(byte[] b, int off, int len) throws IOException { String s = new String(b, off, len); listener.outputChanged(s); } /** * Converts the int to a string and forwards * it to the job output listener. *
    Called by the GassServer. */ public void write(int b) throws IOException { listener.outputChanged(String.valueOf(b)); } /** * Notifies the job output listener that * no more output will be produced. *
    Called by the GassServer. */ public void close() throws IOException { listener.outputClosed(); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/server/RemoteGassServer.java000066400000000000000000000261441241116057200321100ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.gass.server; import org.globus.gram.GramJob; import org.globus.gram.GramJobListener; import org.globus.util.GlobusURL; import org.globus.io.gass.client.GassException; import org.globus.util.deactivator.Deactivator; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class allows for starting gass server remotely. The gass * server is started via the globus gatekeeper. * */ public class RemoteGassServer { private static Log logger = LogFactory.getLog(RemoteGassServer.class.getName()); public static final int LINE_BUFFER_ENABLE = 256; public static final int TILDE_EXPAND_ENABLE = 512; public static final int USER_EXPAND_ENABLE = 1024; private int port = 0; private int options = 0; private boolean secure = true; private GSSCredential cred = null; private String url = null; private GramJob job = null; private boolean compatibilityMode = false; private OutputListener stderrListener, stdoutListener; private GassServerListener gassJobListener; /** * Starts Gass Server with default user credentials. * Port of the server will be dynamically assigned. */ public RemoteGassServer() { this(true, 0); } /** * Starts Gass Server on given port and mode. Default * credentials will be used to start the server. * * @param secure * if true starts server in secure mode, otherwise unsecure. * @param port * port of the server, if 0 it will be dynamically assigned. */ public RemoteGassServer(boolean secure, int port) { this(null, secure, port); } /** * Starts Gass Server on given port and mode. The supplied * credentials will be used to start the server. * * @param cred * credentials to use to start the server. * @param secure * if true starts server in secure mode, otherwise unsecure. * @param port * port of the server, if 0 it will be dynamically assigned. */ public RemoteGassServer(GSSCredential cred, boolean secure, int port) { this.cred = cred; this.secure = secure; this.port = port; options = USER_EXPAND_ENABLE | TILDE_EXPAND_ENABLE | LINE_BUFFER_ENABLE | GassServer.READ_ENABLE | GassServer.WRITE_ENABLE; } /** * Returns url of this server. * * @return url of this server */ public String getURL() { return url; } /** * Sets the options of the gass server such * as enabling client shutdown, etc. * * @param options server options */ public void setOptions(int options) { this.options = options; } /** * Returns current options of the server. * * @return options of the server. O if not * none set. */ public int getOptions() { return options; } /** * Sets the compatibility mode to work with the old * globus 1.1.x installations. * * @param compatibility set to true if working with * the old globus 1.1.x installation. * */ public void setCompatibilityMode(boolean compatibility) { this.compatibilityMode = compatibility; } /** * Starts the gass server on the remote machine. * * @param rmc resource manager contact of the remote machine. * @exception GassException if any error occurs during * remote startup. */ public void start(String rmc) throws GassException { if (rmc == null) { throw new IllegalArgumentException("Resource manager contact not specified"); } GassServer gassServer = null; String error = null; try { gassServer = new GassServer(this.cred, 0); String gassURL = gassServer.getURL(); String rsl = getRSL(gassURL); logger.debug("RSL: " + rsl); stderrListener = new OutputListener(); stdoutListener = new OutputListener(); gassServer.registerJobOutputStream("err-rgs", new JobOutputStream(stderrListener)); gassServer.registerJobOutputStream("out-rgs", new JobOutputStream(stdoutListener)); job = new GramJob(this.cred, rsl); gassJobListener = new GassServerListener(); job.addListener(gassJobListener); job.request(rmc); int status = gassJobListener.waitFor(1000*60*2); if (status == GramJob.STATUS_ACTIVE) { while(true) { if (stderrListener.hasData()) { // got some error error = stderrListener.getOutput(); break; } else if (stdoutListener.hasData()) { // this could be the url String fl = stdoutListener.getOutput(); if (fl.startsWith("https://") || fl.startsWith("http://")) { // extract url url = fl.trim(); break; } else { // something is wrong with stdout error = "Unable to extract gass url : " + fl; break; } } else { // wait for stdout/err logger.debug("waiting for stdout/err"); sleep(500); } } } else if (status == GramJob.STATUS_FAILED || status == GramJob.STATUS_DONE) { int errorCode = gassJobListener.getError(); if (stderrListener.hasData()) { error = stderrListener.getOutput(); } else if (errorCode != 0) { error = "Remote gass server stopped with error : " + errorCode; } else { error = "Remote gass server stopped and returned no error"; } } else { error = "Unexpected state or received no notification"; } } catch(Exception e) { throw new GassException( e.getMessage() ); } finally { if (gassServer != null) { gassServer.shutdown(); } } if (error != null) { throw new GassException(error); } } /** * Shutdowns remotely running gass server. * * @return true if server was successfully killed, false * otherwise. */ public boolean shutdown() { if (url != null) { logger.debug("Trying to shutdown gass server directly..."); try { GlobusURL u = new GlobusURL(url); GassServer.shutdown(this.cred, u); } catch(Exception e) { logger.debug("gass server shutdown failed", e); } try { gassJobListener.reset(); int status = gassJobListener.waitFor(1000*60); if (status == GramJob.STATUS_FAILED || status == GramJob.STATUS_DONE) { // shutdown successful reset(); return true; } } catch(InterruptedException e) { logger.debug("", e); } } // otherwise just cancel the job. if (job == null) return true; logger.debug("Canceling gass server job."); try { job.cancel(); reset(); return true; } catch(Exception e) { return false; } } private void reset() { job = null; url = null; } private String getRSL(String gassURL) { StringBuffer buf = new StringBuffer(); if (compatibilityMode) { buf.append("&(executable=$(GLOBUS_TOOLS_PREFIX)/bin/globus-gass-server)"); } else { buf.append("&(executable=$(GLOBUS_LOCATION)/bin/globus-gass-server)"); buf.append("(environment=(LD_LIBRARY_PATH $(GLOBUS_LOCATION)/lib))"); } buf.append("(rsl_substitution=(GLOBUSRUN_GASS_URL " + gassURL + "))"); buf.append("(stderr=$(GLOBUSRUN_GASS_URL)/dev/stderr-rgs)"); buf.append("(stdout=$(GLOBUSRUN_GASS_URL)/dev/stdout-rgs)"); setRSLArguments(buf); return buf.toString(); } private void setRSLArguments(StringBuffer buf) { buf.append("(arguments=\"-c\""); if (port != 0) { buf.append(" \"-p\" \"" + port + "\""); } if (!secure) { buf.append(" \"-i\""); } if ((options & LINE_BUFFER_ENABLE) != 0) { buf.append(" \"-l\""); } if ((options & TILDE_EXPAND_ENABLE) != 0) { buf.append(" \"-t\""); } if ((options & USER_EXPAND_ENABLE) != 0) { buf.append(" \"-u\""); } if ((options & GassServer.READ_ENABLE) != 0) { buf.append(" \"-r\""); } if ((options & GassServer.WRITE_ENABLE) != 0) { buf.append(" \"-w\""); } buf.append(")"); } private void sleep(int msec) { try { Thread.sleep(msec); } catch(Exception e) { } } // ---------- main ---------------- public static void main(String [] args) { RemoteGassServer s = null; int port = 0; boolean secure = true; String host = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("-h")) { host = args[++i]; } else if (args[i].equals("-p")) { port = Integer.parseInt(args[++i]); } else if (args[i].equalsIgnoreCase("-i")) { secure = false; } else { System.err.println("Unknown command: " + args[i]); System.exit(1); } } try { s = new RemoteGassServer(secure, port); s.setOptions( USER_EXPAND_ENABLE | TILDE_EXPAND_ENABLE | LINE_BUFFER_ENABLE | GassServer.READ_ENABLE | GassServer.WRITE_ENABLE ); s.start(host); System.out.println("Remote gass server url: " + s.getURL()); Thread.sleep(10000); System.out.println("Shutting down..."); } catch(Exception e) { e.printStackTrace(); } finally { if (s != null) s.shutdown(); } System.out.println("Done"); Deactivator.deactivateAll(); } } class GassServerListener implements GramJobListener { private static Log logger = LogFactory.getLog(RemoteGassServer.class.getName()); private int status = -1; private int error = 0; public int getError() { return this.error; } public static boolean isStartState(int status) { return (status == GramJob.STATUS_ACTIVE || status == GramJob.STATUS_FAILED || status == GramJob.STATUS_DONE); } public synchronized void reset() { this.error = 0; this.status = -1; } public synchronized int waitFor(int timeout) throws InterruptedException { for(;;) { if (isStartState(status)) { break; } wait(timeout); if (status == -1) { break; } } return status; } public synchronized void statusChanged(GramJob job) { int st = job.getStatus(); logger.debug("Gass job status: " + st); if (status == -1 && isStartState(st)) { status = st; error = job.getError(); notify(); } } } class OutputListener implements JobOutputListener { private StringBuffer outputBuf = null; public void outputChanged(String output) { if (outputBuf == null) { outputBuf = new StringBuffer(); } outputBuf.append(output); } public void outputClosed() { } public String getOutput() { return (outputBuf == null) ? null : outputBuf.toString(); } public boolean hasData() { return (outputBuf != null); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/gass/server/package.html000066400000000000000000000020361241116057200302600ustar00rootroot00000000000000 org.globus.gass.server package Provides a pure Java Globus GASS server for transferring files via HTTPS.

    The server is multi-threaded and accepts HTTPS connection from GASS clients to copy from, copy to, and append to files that are local to the server.

    This version has not been fully tested against the full GASS protocol, but works for all cases tested with globus-url-copy.

    Package Specification

    (none)

    Related Documentation

    The following classes are used by the org.globus.gass.server class: For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/000077500000000000000000000000001241116057200252115ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/FTPInputStream.java000066400000000000000000000065671241116057200307170ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.InputStream; import java.io.IOException; import org.globus.ftp.FTPClient; import org.globus.ftp.Session; import org.globus.ftp.InputStreamDataSink; import org.globus.ftp.vanilla.TransferState; import org.globus.ftp.exception.FTPException; import org.globus.common.ChainedIOException; public class FTPInputStream extends GlobusInputStream { protected InputStream input; protected FTPClient ftp; protected TransferState state; protected FTPInputStream() { } public FTPInputStream(String host, int port, String user, String pwd, String file) throws IOException, FTPException { this(host, port, user, pwd, file, true, Session.TYPE_IMAGE); } public FTPInputStream(String host, int port, String user, String pwd, String file, boolean passive, int type) throws IOException, FTPException { this.ftp = new FTPClient(host, port); this.ftp.authorize(user, pwd); get(passive, type, file); } protected void get(boolean passive, int type, String remoteFile) throws IOException, FTPException { InputStreamDataSink sink = null; try { this.ftp.setType(type); if (passive) { this.ftp.setPassive(); this.ftp.setLocalActive(); } else { this.ftp.setLocalPassive(); this.ftp.setActive(); } sink = new InputStreamDataSink(); this.input = sink.getInputStream(); this.state = this.ftp.asynchGet(remoteFile, sink, null); this.state.waitForStart(); } catch (FTPException e) { if (sink != null) { sink.close(); } close(); throw e; } } public long getSize() { return -1; } public void abort() { if (this.input != null) { try { this.input.close(); } catch(Exception e) {} } try { this.ftp.close(); } catch (IOException e) { } catch (FTPException e) { } } // standard InputStream methods public void close() throws IOException { if (this.input != null) { try { this.input.close(); } catch(Exception e) {} } try { if (this.state != null) { this.state.waitForEnd(); } } catch (FTPException e) { throw new ChainedIOException("close failed.", e); } finally { try { this.ftp.close(); } catch (FTPException ee) { throw new ChainedIOException("close failed.", ee); } } } public int read(byte [] msg) throws IOException { return this.input.read(msg); } public int read(byte [] buf, int off, int len) throws IOException { return this.input.read(buf, off, len); } public int read() throws IOException { return this.input.read(); } public int available() throws IOException { return this.input.available(); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/FTPOutputStream.java000066400000000000000000000065721241116057200311140ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.OutputStream; import java.io.IOException; import org.globus.ftp.FTPClient; import org.globus.ftp.Session; import org.globus.ftp.OutputStreamDataSource; import org.globus.ftp.vanilla.TransferState; import org.globus.ftp.exception.FTPException; import org.globus.common.ChainedIOException; public class FTPOutputStream extends GlobusOutputStream { protected OutputStream output; protected FTPClient ftp; protected TransferState state; protected FTPOutputStream() { } public FTPOutputStream(String host, int port, String user, String pwd, String file, boolean append) throws IOException, FTPException { this(host, port, user, pwd, file, append, true, Session.TYPE_IMAGE); } public FTPOutputStream(String host, int port, String user, String pwd, String file, boolean append, boolean passive, int type) throws IOException, FTPException { this.ftp = new FTPClient(host, port); this.ftp.authorize(user, pwd); put(passive, type, file, append); } public void abort() { if (this.output != null) { try { this.output.close(); } catch(Exception e) {} } try { this.ftp.close(); } catch (IOException e) { } catch (FTPException e) { } } public void close() throws IOException { if (this.output != null) { try { this.output.close(); } catch(Exception e) {} } try { if (this.state != null) { this.state.waitForEnd(); } } catch (FTPException e) { throw new ChainedIOException("close failed.", e); } finally { try { this.ftp.close(); } catch (FTPException ee) { throw new ChainedIOException("close failed.", ee); } } } protected void put(boolean passive, int type, String remoteFile, boolean append) throws IOException, FTPException { OutputStreamDataSource source = null; try { this.ftp.setType(type); if (passive) { this.ftp.setPassive(); this.ftp.setLocalActive(); } else { this.ftp.setLocalPassive(); this.ftp.setActive(); } source = new OutputStreamDataSource(2048); this.state = this.ftp.asynchPut(remoteFile, source, null, append); this.state.waitForStart(); this.output = source.getOutputStream(); } catch (FTPException e) { if (source != null) { source.close(); } close(); throw e; } } public void write(byte [] msg) throws IOException { output.write(msg); } public void write(byte [] msg, int from, int length) throws IOException { output.write(msg, from, length); } public void write(int b) throws IOException { output.write(b); } public void flush() throws IOException { output.flush(); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/GassInputStream.java000066400000000000000000000061461241116057200311540ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.IOException; import java.net.Socket; import org.globus.common.ChainedIOException; import org.globus.io.gass.client.GassException; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSContext; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSContext; public class GassInputStream extends HTTPInputStream { private GSSCredential cred; private Authorization auth; /** * Opens Gass input stream in secure mode with default * user credentials. * * @param host host name of the gass server * @param port port number of the gass server * @param file file to retrieve from the server */ public GassInputStream(String host, int port, String file) throws GassException, GSSException, IOException { this(null, SelfAuthorization.getInstance(), host, port, file); } /** * Opens Gass input stream in secure mode with specified * user credentials. * * @param cred user credentials to use * @param host host name of the gass server * @param port port number of the gass server * @param file file to retrieve from the server */ public GassInputStream(GSSCredential cred, Authorization auth, String host, int port, String file) throws GassException, GSSException, IOException { super(); this.cred = cred; this.auth = auth; get(host, port, file); } protected Socket openSocket(String host, int port) throws IOException { GSSManager manager = ExtendedGSSManager.getInstance(); ExtendedGSSContext context = null; try { context = (ExtendedGSSContext)manager.createContext( null, GSSConstants.MECH_OID, this.cred, GSSContext.DEFAULT_LIFETIME ); context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); } catch (GSSException e) { throw new ChainedIOException("Security error", e); } GssSocketFactory factory = GssSocketFactory.getDefault(); socket = factory.createSocket(host, port, context); ((GssSocket)socket).setAuthorization(this.auth); return socket; } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/GassOutputStream.java000066400000000000000000000110221241116057200313420ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.IOException; import org.globus.io.gass.client.GassException; import org.globus.gsi.GSIConstants; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSContext; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSContext; public class GassOutputStream extends HTTPOutputStream { /** * Opens Gass output stream in secure mode with default * user credentials. * * @param host host name of the gass server. * @param port port number of the gass server. * @param file name of the file on the remote side. * @param length total size of the data to be transfered. * Use -1 if unknown. The data then will be * transfered in chunks. * @param append if true, append data to existing file. * Otherwise, the file will be overwritten. */ public GassOutputStream(String host, int port, String file, long length, boolean append) throws GassException, GSSException, IOException { this(null, SelfAuthorization.getInstance(), host, port, file, length, append); } /** * Opens Gass output stream in secure mode with specified * user credentials. * * @param cred user credentials to use. If null, * default user credentials will be used. * @param host host name of the gass server. * @param port port number of the gass server. * @param file name of the file on the remote side. * @param length total size of the data to be transfered. * Use -1 if unknown. The data then will be * transfered in chunks. * @param append if true, append data to existing file. * Otherwise, the file will be overwritten. */ public GassOutputStream(GSSCredential cred, String host, int port, String file, long length, boolean append) throws GassException, GSSException, IOException { this(cred, SelfAuthorization.getInstance(), host, port, file, length, append); } /** * Opens Gass output stream in secure mode with specified * user credentials. * * @param cred user credentials to use. If null, * default user credentials will be used. * @param host host name of the gass server. * @param port port number of the gass server. * @param file name of the file on the remote side. * @param length total size of the data to be transfered. * Use -1 if unknown. The data then will be * transfered in chunks. * @param append if true, append data to existing file. * Otherwise, the file will be overwritten. */ public GassOutputStream(GSSCredential cred, Authorization auth, String host, int port, String file, long length, boolean append) throws GassException, GSSException, IOException { super(); this.size = length; this.append = append; GSSManager manager = ExtendedGSSManager.getInstance(); ExtendedGSSContext context = (ExtendedGSSContext)manager.createContext(null, GSSConstants.MECH_OID, cred, GSSContext.DEFAULT_LIFETIME); context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_SSL); GssSocketFactory factory = GssSocketFactory.getDefault(); socket = factory.createSocket(host, port, context); ((GssSocket)socket).setAuthorization(auth); put(host, file, length, -1); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/GlobusFileInputStream.java000066400000000000000000000031351241116057200323050ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.IOException; import java.io.FileInputStream; import java.io.File; public class GlobusFileInputStream extends GlobusInputStream { private FileInputStream input; private long size = -1; public GlobusFileInputStream(String file) throws IOException { File f = new File(file); input = new FileInputStream(f); size = f.length(); } public long getSize() { return size; } public void abort() { try { input.close(); } catch(Exception e) {} } // standard InputStream methods public void close() throws IOException { input.close(); } public int read(byte [] msg) throws IOException { return input.read(msg); } public int read(byte [] buf, int off, int len) throws IOException { return input.read(buf, off, len); } public int read() throws IOException { return input.read(); } public int available() throws IOException { return input.available(); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/GlobusFileOutputStream.java000066400000000000000000000027111241116057200325050ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.OutputStream; import java.io.IOException; import java.io.FileOutputStream; public class GlobusFileOutputStream extends GlobusOutputStream { private OutputStream output; public GlobusFileOutputStream(String file, boolean append) throws IOException { output = new FileOutputStream(file, append); } public void abort() { try { output.close(); } catch(Exception e) {} } public void close() throws IOException { output.close(); } public void write(byte [] msg) throws IOException { output.write(msg); } public void write(byte [] msg, int from, int length) throws IOException { output.write(msg, from, length); } public void write(int b) throws IOException { output.write(b); } public void flush() throws IOException { output.flush(); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/GlobusInputStream.java000066400000000000000000000023271241116057200315070ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.InputStream; import java.io.IOException; public abstract class GlobusInputStream extends InputStream { /** * Returns the total size of input data. * * @return -1 if size is unknown. */ public long getSize() { return -1; } public int read() throws IOException { throw new IOException("Not implemented."); } /** * Aborts transfer. Usually makes sure to * release all resources (sockets, file descriptors) *
    Does nothing by default. */ public void abort() { // FIXME: is this still used/needed? } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/GlobusOutputStream.java000066400000000000000000000021211241116057200317000ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.OutputStream; import java.io.IOException; public abstract class GlobusOutputStream extends OutputStream { /** * Aborts transfer. Usually makes sure to * release all resources (sockets, file descriptors) *
    Does nothing by default. */ public void abort() { // FIXME: is this still used/needed? } public void write(int b) throws IOException { throw new IOException("Not implemented."); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/GridFTPInputStream.java000066400000000000000000000042431241116057200315120ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.IOException; import org.globus.ftp.GridFTPClient; import org.globus.ftp.Session; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.exception.FTPException; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.HostAuthorization; import org.ietf.jgss.GSSCredential; public class GridFTPInputStream extends FTPInputStream { public GridFTPInputStream(GSSCredential cred, String host, int port, String file) throws IOException, FTPException { this(cred, HostAuthorization.getInstance(), host, port, file, true, Session.TYPE_IMAGE, true); } public GridFTPInputStream(GSSCredential cred, Authorization auth, String host, int port, String file, boolean reqDCAU) throws IOException, FTPException { this(cred, auth, host, port, file, true, Session.TYPE_IMAGE, reqDCAU); } public GridFTPInputStream(GSSCredential cred, Authorization auth, String host, int port, String file, boolean passive, int type, boolean reqDCAU) throws IOException, FTPException { GridFTPClient gridFtp = new GridFTPClient(host, port); gridFtp.setAuthorization(auth); gridFtp.authenticate(cred); if (gridFtp.isFeatureSupported("DCAU")) { if (!reqDCAU) { gridFtp.setDataChannelAuthentication(DataChannelAuthentication.NONE); } } else { gridFtp.setLocalNoDataChannelAuthentication(); } ftp = gridFtp; get(passive, type, file); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/GridFTPOutputStream.java000066400000000000000000000063121241116057200317120ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.IOException; import org.globus.ftp.GridFTPClient; import org.globus.ftp.Session; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.exception.FTPException; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.HostAuthorization; import org.ietf.jgss.GSSCredential; public class GridFTPOutputStream extends FTPOutputStream { public GridFTPOutputStream(GSSCredential cred, String host, int port, String file, boolean append) throws IOException, FTPException { this(cred, HostAuthorization.getInstance(), host, port, file, append, true, Session.TYPE_IMAGE, true); } public GridFTPOutputStream(GSSCredential cred, Authorization auth, String host, int port, String file, boolean append, boolean reqDCAU) throws IOException, FTPException { this(cred, auth, host, port, file, append, true, Session.TYPE_IMAGE, reqDCAU); } public GridFTPOutputStream(GSSCredential cred, Authorization auth, String host, int port, String file, boolean append, boolean reqDCAU, long size) throws IOException, FTPException { this(cred, auth, host, port, file, append, true, Session.TYPE_IMAGE, reqDCAU, size); } public GridFTPOutputStream(GSSCredential cred, Authorization auth, String host, int port, String file, boolean append, boolean passive, int type, boolean reqDCAU) throws IOException, FTPException { this(cred, auth, host, port, file, append, passive, type, reqDCAU, -1); } public GridFTPOutputStream(GSSCredential cred, Authorization auth, String host, int port, String file, boolean append, boolean passive, int type, boolean reqDCAU, long size) throws IOException, FTPException { GridFTPClient gridFtp = new GridFTPClient(host, port); gridFtp.setAuthorization(auth); gridFtp.authenticate(cred); if (gridFtp.isFeatureSupported("DCAU")) { if (!reqDCAU) { gridFtp.setDataChannelAuthentication(DataChannelAuthentication.NONE); } } else { gridFtp.setLocalNoDataChannelAuthentication(); } ftp = gridFtp; put(passive, type, file, append); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/HTTPInputStream.java000066400000000000000000000100001241116057200310160ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.IOException; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import org.globus.io.gass.client.internal.GASSProtocol; import org.globus.net.SocketFactory; import org.globus.util.http.HttpResponse; import org.globus.util.http.HTTPChunkedInputStream; import org.globus.util.GlobusURL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class HTTPInputStream extends GlobusInputStream { private static Log logger = LogFactory.getLog(HTTPInputStream.class.getName()); protected InputStream input; protected Socket socket; protected long size = -1; /** * Private constructor used by subclasses. */ protected HTTPInputStream() { } /** * Opens HTTP input stream connection (unsecure) * * @param host host name of the HTTP server. * @param port port number of the HTTP server. * @param file file to retrieve from the server. */ public HTTPInputStream(String host, int port, String file) throws IOException { get(host, port, file); } // subclasses should overwrite this function protected Socket openSocket(String host, int port) throws IOException { return SocketFactory.getDefault().createSocket(host, port); } protected void get(String host, int port, String file) throws IOException { HttpResponse hd = null; while(true) { this.socket = openSocket(host, port); this.input = this.socket.getInputStream(); OutputStream out = socket.getOutputStream(); String msg = GASSProtocol.GET(file, host + ":" + port); try { out.write( msg.getBytes() ); out.flush(); if (logger.isTraceEnabled()) { logger.trace("SENT: " + msg); } hd = new HttpResponse(input); } catch(IOException e) { abort(); throw e; } if (hd.httpCode == 200) { break; } else { abort(); switch(hd.httpCode) { case 404: throw new FileNotFoundException( "File " + file + " not found on the server." ); case 301: case 302: logger.debug("Received redirection to: " + hd.location); GlobusURL newLocation = new GlobusURL(hd.location); host = newLocation.getHost(); port = newLocation.getPort(); file = newLocation.getPath(); break; default: throw new IOException( "Failed to retrieve file from server. " + " Server returned error: " + hd.httpMsg + " (" + hd.httpCode + ")" ); } } } if (hd.chunked) { input = new HTTPChunkedInputStream(input); } else if (hd.contentLength > 0) { size = hd.contentLength; } } public void abort() { try { close(); } catch (Exception e) {} } public long getSize() { return size; } public void close() throws IOException { if (this.input != null) { this.input.close(); } if (this.socket != null) { this.socket.close(); } } public int read(byte [] msg) throws IOException { return input.read(msg); } public int read(byte [] buf, int off, int len) throws IOException { return input.read(buf, off, len); } public int read() throws IOException { return input.read(); } public int available() throws IOException { return input.available(); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/HTTPOutputStream.java000066400000000000000000000127071241116057200312370ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.streams; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.net.Socket; import org.globus.io.gass.client.internal.GASSProtocol; import org.globus.io.gass.client.GassException; import org.globus.net.SocketFactory; import org.globus.util.http.HttpResponse; import org.globus.common.ChainedIOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class HTTPOutputStream extends GlobusOutputStream { private static Log logger = LogFactory.getLog(HTTPOutputStream.class.getName()); private static final byte[] CRLF = "\r\n".getBytes(); private static final int DEFAULT_TIME = 3000; protected OutputStream output; protected InputStream in; protected Socket socket; protected long size = -1; protected boolean append = false; /** * Private constructor used by subclasses. */ protected HTTPOutputStream() { } /** * Opens HTTP output stream (unsecure) * * @param host host name of the HTTP server. * @param port port number of the HTTP server. * @param file name of the file on the remote side. * @param length total size of the data to be transfered. * Use -1 if unknown. The data then will be * transfered in chunks. * @param append if true, append data to existing file. * Otherwise, the file will be overwritten. */ public HTTPOutputStream(String host, int port, String file, long length, boolean append) throws GassException, IOException { init(host, port, file, length, append); } private void init(String host, int port, String file, long length, boolean append) throws GassException, IOException { size = length; this.append = append; // default waiting time for response from the server int time = DEFAULT_TIME; long st = System.currentTimeMillis(); socket = SocketFactory.getDefault().createSocket(host, port); long et = System.currentTimeMillis(); time = 2*(int)(et - st); put(host, file, length, time); } private void sleep(int time) { try { Thread.sleep(time); } catch(Exception e) {} } protected void put(String host, String file, long length, int waittime) throws IOException { output = socket.getOutputStream(); in = socket.getInputStream(); String msg = GASSProtocol.PUT(file, host, length, append); if (logger.isTraceEnabled()) { logger.trace("SENT: " + msg); } output.write( msg.getBytes() ); output.flush(); if (waittime < 0) { int maxsleep = DEFAULT_TIME; while(maxsleep != 0) { sleep(1000); maxsleep -= 1000; checkForReply(); } } else { sleep(waittime); } checkForReply(); } private void checkForReply() throws IOException { if (in.available() <= 0) { return; } HttpResponse reply = new HttpResponse(in); if (logger.isTraceEnabled()) { logger.trace("REPLY: " + reply); } if (reply.httpCode != 100) { abort(); throw new IOException("Gass PUT failed: " + reply.httpMsg); } else { logger.debug("Received continuation reply"); } } private void finish() throws IOException { if (size == -1) { String lHex = Integer.toHexString(0); output.write(lHex.getBytes()); output.write(CRLF); output.write(CRLF); } output.flush(); } private void closeSocket() { try { if (socket != null) socket.close(); if (in != null) in.close(); if (output != null) output.close(); } catch(Exception e) {} } public void abort() { try { finish(); } catch(Exception e) {} closeSocket(); } public void close() throws IOException { // is there a way to get rid of that wait for final reply? finish(); HttpResponse hd = new HttpResponse(in); closeSocket(); if (logger.isTraceEnabled()) { logger.trace("REPLY: " + hd); } if (hd.httpCode != 200) { throw new ChainedIOException("Gass close failed.", new GassException("Gass PUT failed: " + hd.httpMsg)); } } public void write(byte [] msg) throws IOException { write(msg, 0, msg.length); } public void write(byte [] msg, int from, int length) throws IOException { checkForReply(); if (size == -1) { String lHex = Integer.toHexString(length); output.write(lHex.getBytes()); output.write(CRLF); output.write(msg, from, length); output.write(CRLF); } else { output.write(msg, from, length); } } public void write(int b) throws IOException { checkForReply(); if (size == -1) { output.write("01".getBytes()); output.write(CRLF); output.write(b); output.write(CRLF); } else { output.write(b); } } public void flush() throws IOException { output.flush(); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/streams/package.html000066400000000000000000000006511241116057200274740ustar00rootroot00000000000000 Implements the standard Java I/O streams interface for a number of different protocols, including FTP, GSIFTP, HTTP, HTTPS, and File.

    Package Specification

    Related Documentation

    JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/urlcopy/000077500000000000000000000000001241116057200252305ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/urlcopy/UrlCopy.java000066400000000000000000000660621241116057200275020ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.urlcopy; import java.io.IOException; import java.util.List; import java.util.Iterator; import java.util.LinkedList; import java.net.URLDecoder; import org.globus.io.streams.GlobusInputStream; import org.globus.io.streams.GlobusOutputStream; import org.globus.io.streams.GlobusFileInputStream; import org.globus.io.streams.GlobusFileOutputStream; import org.globus.io.streams.FTPInputStream; import org.globus.io.streams.FTPOutputStream; import org.globus.io.streams.HTTPInputStream; import org.globus.io.streams.HTTPOutputStream; import org.globus.io.streams.GassInputStream; import org.globus.io.streams.GassOutputStream; import org.globus.io.streams.GridFTPInputStream; import org.globus.io.streams.GridFTPOutputStream; import org.globus.ftp.FTPClient; import org.globus.ftp.GridFTPClient; import org.globus.ftp.GridFTPSession; import org.globus.ftp.Session; import org.globus.ftp.DataChannelAuthentication; import org.globus.ftp.exception.FTPException; import org.globus.util.GlobusURL; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.HostAuthorization; import org.globus.gsi.gssapi.auth.SelfAuthorization; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /* * Limitations: * o third party transfer use binary type * o third party transfer negotiate DCAU - defaults to DCAU on * o no ability to set ascii/binary transfer type * o no ability to set authorization per connection */ public class UrlCopy implements Runnable { private static Log logger = LogFactory.getLog(UrlCopy.class.getName()); /** maximum buffer size to read or write when putting and getting files */ public static final int BUFF_SIZE = 2048; protected int bufferSize = BUFF_SIZE; protected GSSCredential srcCreds = null; protected Authorization srcAuth = null; protected GSSCredential dstCreds = null; protected Authorization dstAuth = null; protected boolean dcau = true; protected boolean appendMode = false; protected GlobusURL srcUrl = null; protected GlobusURL dstUrl = null; protected boolean canceled = false; protected boolean thirdParty = true; protected List listeners = null; protected long sourceOffset = 0; protected long destinationOffset = 0; protected long sourceLength = Long.MAX_VALUE; protected int tcpBufferSize = 0; protected boolean disableAllo = false; public void setDCAU(boolean dcau) { this.dcau = dcau; } public boolean getDCAU() { return this.dcau; } /** * Sets credentials to use for both sides. * * @param credentials user credentials */ public void setCredentials(GSSCredential credentials) { setSourceCredentials(credentials); setDestinationCredentials(credentials); } /** * Sets source url credentials. * * @param srcCredentials source url credentials. */ public void setSourceCredentials(GSSCredential srcCredentials) { this.srcCreds = srcCredentials; } /** * Sets destination url credentials. * * @param dstCredentials destination url credentials. */ public void setDestinationCredentials(GSSCredential dstCredentials) { this.dstCreds = dstCredentials; } /** * Sets source authorization type * * @param auth authorization type to perform for source */ public void setSourceAuthorization(Authorization auth) { this.srcAuth = auth; } /** * Sets destination authorization type * * @param auth authorization type to perform for destination */ public void setDestinationAuthorization(Authorization auth) { this.dstAuth = auth; } /** * Returns credentials used for authenticating * the source side for the url copy. * If no source credentials are set, the default * user credentials will used. * * @return source credentials. */ public GSSCredential getSourceCredentials() { return this.srcCreds; } /** * Returns credentials used for authenticating * the destination side for the url copy. * If no destination credentials are set, the default * user credentials will used. * * @return destination credentials. */ public GSSCredential getDestinationCredentials() { return this.dstCreds; } /** * Returns authorization type for * the source side for the url copy. * If no authorization type is set, the default * authorization will be performed for a given protocol. * * @return source authorization type */ public Authorization getSourceAuthorization() { return this.srcAuth; } /** * Returns authorization type for * the destination side for the url copy. * If no authorization type is set, the default * authorization will be performed for a given protocol. * * @return destination authorization type */ public Authorization getDestinationAuthorization() { return this.dstAuth; } /** * Adds url copy listener. * * @param listener url copy listener */ public void addUrlCopyListener(UrlCopyListener listener) { if (listeners == null) listeners = new LinkedList(); listeners.add(listener); } /** * Remove url copy listener * * @param listener url copy listener */ public void removeUrlCopyListener(UrlCopyListener listener) { if (listeners == null) return; listeners.remove(listener); } /** * Sets buffer size for transfering data. * It does not set the TCP buffers. * * @param size size of the data buffer */ public void setBufferSize(int size) { bufferSize = size; } /** * Returns buffer size used for transfering * data. * * @return data buffer size */ public int getBufferSize() { return bufferSize; } /** * Sets the TCP buffer size for GridFTP transfers. * * @param size size of TCP buffer */ public void setTCPBufferSize(int size) { if (size < 0) { throw new IllegalArgumentException("The TCP buffer size must be a positive"); } this.tcpBufferSize = size; } /** * Returns TCP buffer size used for transfers * data. * * @return TCP buffer size */ public int getTCPBufferSize() { return this.tcpBufferSize; } /** * Enables/disables append mode. * * @param appendMode if true, destination file * will be appended. */ public void setAppendMode(boolean appendMode) { this.appendMode = appendMode; } /** * Checks if append mode is enabled. * * @return true if appending will be performed, * false otherwise. */ public boolean isAppendMode() { return appendMode; } /** * Gets the offset in the destination file from which data starts * to be written * * @return a value indicating the offset in bytes */ public long getDestinationOffset() { return this.destinationOffset; } /** * Sets the offset in the destination file from which data starts * to be written. The default offset is 0 (the beginning of the file) * * @param destinationOffset the offset in bytes */ public void setDestinationOffset(long destinationOffset) { this.destinationOffset = destinationOffset; } /** * Gets the maximum data size that will be transfered. * * @return the size in bytes */ public long getSourceLength() { return this.sourceLength; } /** * Allows a partial transfer by setting the maximum number of bytes * that will be transfered. By default the entire source file is * transfered. * * @param sourceLength the size of the transfer in bytes */ public void setSourceFileLength(long sourceLength) { this.sourceLength = sourceLength; } /** * Gets the offset in the source file from which data starts * to be read * * @return a value indicating the offset in bytes */ public long getSourceOffset() { return this.sourceOffset; } /** * Sets the offset in the source file from which data starts * to be read. The default offset is 0 (the beginning of the file) * * @param sourceOffset the offset in bytes */ public void setSourceFileOffset(long sourceOffset) { this.sourceOffset = sourceOffset; } private void checkUrl(GlobusURL url) throws UrlCopyException { String urlPath = url.getPath(); if (urlPath == null || urlPath.length() == 0) { throw new UrlCopyException("The '" + url.getURL() + "' url does not specify the file location."); } } /** * Sets source url. * * @param source source url. */ public void setSourceUrl(GlobusURL source) throws UrlCopyException { if (source == null) { throw new IllegalArgumentException("Source url cannot be null"); } checkUrl(source); srcUrl = source; } /** * Returns source url. * * @return url */ public GlobusURL getSourceUrl() { return srcUrl; } /** * Sets destination url. * * @param dest destination url */ public void setDestinationUrl(GlobusURL dest) throws UrlCopyException { if (dest == null) { throw new IllegalArgumentException("Desitination url cannot be null"); } checkUrl(dest); dstUrl = dest; } /** * Returns destination url. * * @return url */ public GlobusURL getDestinationUrl() { return dstUrl; } /** * Enables/disables usage of third party transfers. * * @param thirdParty if true enable, false disable */ public void setUseThirdPartyCopy(boolean thirdParty) { this.thirdParty = thirdParty; } /** * Can be used to query whether the use of the ALLO command * with GridFTP uploads is disabled. */ public boolean getDisableAllo() { return disableAllo; } /** * Allows disabling of the use of ALLO with GridFTP * uploads */ public void setDisableAllo(boolean disableAllo) { this.disableAllo = disableAllo; } /** * Cancels the transfer in progress. If no transfer * is in progress it is ignored. */ public void cancel() { canceled = true; } /** * Checks if the transfer was canceled. * * @return true if transfer was canceled */ public boolean isCanceled() { return canceled; } /** * This method is an implementation of the {@link Runnable} interface * and can be used to perform the copy in a separate thread. *

    * This method will perform the transfer and signal completion and * errors through the {@link UrlCopyListener#transferCompleted()} and * {@link UrlCopyListener#transferError(Exception)} of any registered listeners * (see {@link #addUrlCopyListener(UrlCopyListener)}). * */ public void run() { try { copy(); } catch(Exception e) { if (listeners != null) { Iterator iter = listeners.iterator(); while(iter.hasNext()) { ((UrlCopyListener)iter.next()).transferError(e); } } } finally { if (listeners != null) { Iterator iter = listeners.iterator(); while(iter.hasNext()) { ((UrlCopyListener)iter.next()).transferCompleted(); } } } } /** * Performs the copy function. * Source and destination urls must be specified otherwise * a exception is thrown. Also, if source and destination url * are ftp urls and thirdPartyCopy is enabled, third party transfer * will be performed. Urls, of course, must be of supported protocol. * Currently, gsiftp, ftp, https, http, and file are supported. *

    * This method does not cause the {@link UrlCopyListener#transferCompleted()} * and {@link UrlCopyListener#transferError(Exception)} to be called. If you want * completion/failures to be signaled asynchronously, either call the * {@link #run} method or wrap this object in a {@link Thread}. * * @throws UrlCopyException in case of an error. */ public void copy() throws UrlCopyException { if (srcUrl == null) { throw new UrlCopyException("Source url is not specified"); } if (dstUrl == null) { throw new UrlCopyException("Destination url is not specified"); } String fromP = srcUrl.getProtocol(); String toP = dstUrl.getProtocol(); if (thirdParty && fromP.endsWith("ftp") && toP.endsWith("ftp")) { thirdPartyTransfer(); return; } GlobusInputStream in = null; GlobusOutputStream out = null; boolean rs = false; try { in = getInputStream(); long size = in.getSize(); if (size == -1) { logger.debug("Source size: unknown"); } else { logger.debug("Source size: " + size); } out = getOutputStream(size); rs = transfer(size, in, out); in.close(); out.close(); } catch(Exception e) { if (out != null) out.abort(); if (in != null) in.abort(); throw new UrlCopyException("UrlCopy transfer failed.", e); } if (!rs && isCanceled()) { throw new UrlCopyException("Transfer Aborted"); } } /** * Returns input stream based on the source url */ protected GlobusInputStream getInputStream() throws Exception { GlobusInputStream in = null; String fromP = srcUrl.getProtocol(); String fromFile = srcUrl.getPath(); if (fromP.equalsIgnoreCase("file")) { fromFile = URLDecoder.decode(fromFile); in = new GlobusFileInputStream(fromFile); } else if (fromP.equalsIgnoreCase("ftp")) { fromFile = URLDecoder.decode(fromFile); in = new FTPInputStream(srcUrl.getHost(), srcUrl.getPort(), srcUrl.getUser(), srcUrl.getPwd(), fromFile); } else if (fromP.equalsIgnoreCase("gsiftp") || fromP.equalsIgnoreCase("gridftp")) { Authorization auth = getSourceAuthorization(); if (auth == null) { auth = HostAuthorization.getInstance(); } fromFile = URLDecoder.decode(fromFile); in = new GridFTPInputStream(getSourceCredentials(), auth, srcUrl.getHost(), srcUrl.getPort(), fromFile, getDCAU()); } else if (fromP.equalsIgnoreCase("https")) { Authorization auth = getSourceAuthorization(); if (auth == null) { auth = SelfAuthorization.getInstance(); } in = new GassInputStream(getSourceCredentials(), auth, srcUrl.getHost(), srcUrl.getPort(), fromFile); } else if (fromP.equalsIgnoreCase("http")) { in = new HTTPInputStream(srcUrl.getHost(), srcUrl.getPort(), fromFile); } else { throw new Exception("Source protocol: " + fromP + " not supported!"); } return in; } /** * Returns output stream based on the destination url. */ protected GlobusOutputStream getOutputStream(long size) throws Exception { GlobusOutputStream out = null; String toP = dstUrl.getProtocol(); String toFile = dstUrl.getPath(); if (toP.equalsIgnoreCase("file")) { toFile = URLDecoder.decode(toFile); out = new GlobusFileOutputStream(toFile, appendMode); } else if (toP.equalsIgnoreCase("ftp")) { toFile = URLDecoder.decode(toFile); out = new FTPOutputStream(dstUrl.getHost(), dstUrl.getPort(), dstUrl.getUser(), dstUrl.getPwd(), toFile, appendMode); } else if (toP.equalsIgnoreCase("gsiftp") || toP.equalsIgnoreCase("gridftp")) { Authorization auth = getDestinationAuthorization(); if (auth == null) { auth = HostAuthorization.getInstance(); } toFile = URLDecoder.decode(toFile); out = new GridFTPOutputStream(getDestinationCredentials(), auth, dstUrl.getHost(), dstUrl.getPort(), toFile, appendMode, getDCAU(), (disableAllo ? -1 : size)); } else if (toP.equalsIgnoreCase("https")) { Authorization auth = getDestinationAuthorization(); if (auth == null) { auth = SelfAuthorization.getInstance(); } out = new GassOutputStream(getDestinationCredentials(), auth, dstUrl.getHost(), dstUrl.getPort(), toFile, size, appendMode); } else if (toP.equalsIgnoreCase("http")) { out = new HTTPOutputStream(dstUrl.getHost(), dstUrl.getPort(), toFile, size, appendMode); } else { throw new Exception("Destination protocol: " + toP + " not supported!"); } return out; } /** * This function performs the actual transfer. */ private boolean transfer(long total, GlobusInputStream in, GlobusOutputStream out) throws IOException { byte [] buffer = new byte[bufferSize]; int bytes = 0; long totalBytes = total; long transferedBytes = 0; if (total == -1) { while( (bytes = in.read(buffer)) != -1) { out.write(buffer, 0, bytes); out.flush(); if (listeners != null) { transferedBytes += bytes; fireUrlTransferProgressEvent(totalBytes, transferedBytes); } if (isCanceled()) return false; } } else { while ( total != 0 ) { bytes = bufferSize; if (total < bufferSize) bytes = (int)total; bytes = in.read(buffer); out.write(buffer, 0, bytes); out.flush(); total -= bytes; if (listeners != null) { transferedBytes += bytes; fireUrlTransferProgressEvent(totalBytes, transferedBytes); } if (isCanceled()) return false; } } return true; } private void fireUrlTransferProgressEvent(long totalBytes, long transferedBytes) { Iterator iter = listeners.iterator(); while(iter.hasNext()) { ((UrlCopyListener)iter.next()).transfer(transferedBytes, totalBytes); } } /** * This performs thrid party transfer only if source and destination urls * are ftp urls. */ private void thirdPartyTransfer() throws UrlCopyException { logger.debug("Trying third party transfer..."); FTPClient srcFTP = null; FTPClient dstFTP = null; try { srcFTP = createFTPConnection(srcUrl, true); dstFTP = createFTPConnection(dstUrl, false); negotiateDCAU(srcFTP, dstFTP); srcFTP.setType(Session.TYPE_IMAGE); dstFTP.setType(Session.TYPE_IMAGE); if (listeners != null) { fireUrlTransferProgressEvent(-1, -1); } if (this.sourceOffset == 0 && this.destinationOffset == 0 && this.sourceLength == Long.MAX_VALUE) { srcFTP.setMode(Session.MODE_STREAM); dstFTP.setMode(Session.MODE_STREAM); srcFTP.transfer(srcUrl.getPath(), dstFTP, dstUrl.getPath(), false, null); } else if (srcFTP instanceof GridFTPClient && dstFTP instanceof GridFTPClient) { GridFTPClient srcGridFTP = (GridFTPClient) srcFTP; GridFTPClient dstGridFTP = (GridFTPClient) dstFTP; srcGridFTP.setMode(GridFTPSession.MODE_EBLOCK); dstGridFTP.setMode(GridFTPSession.MODE_EBLOCK); srcGridFTP.extendedTransfer(srcUrl.getPath(), this.sourceOffset, this.sourceLength, dstGridFTP, dstUrl.getPath(), this.destinationOffset, null); } else { throw new UrlCopyException("Partial 3rd party transfers not supported " + "by FTP client. Use GridFTP for both source and destination."); } } catch(Exception e) { throw new UrlCopyException("UrlCopy third party transfer failed.", e); } finally { if (srcFTP != null) { try { srcFTP.close(); } catch (Exception ee) {} } if (dstFTP != null) { try { dstFTP.close(); } catch (Exception ee) {} } } } /* * This could replaced later with something more inteligent * where the user would set if dcau is required or not, etc. */ protected void negotiateDCAU(FTPClient src, FTPClient dst) throws IOException, FTPException { if (src instanceof GridFTPClient) { // src: dcau can be on or off if (dst instanceof GridFTPClient) { // dst: dca can be on or off GridFTPClient s = (GridFTPClient)src; GridFTPClient d = (GridFTPClient)dst; if (src.isFeatureSupported("DCAU") && dst.isFeatureSupported("DCAU")) { setDCAU(s, getDCAU()); setDCAU(d, getDCAU()); } else { setDCAU(s, false); setDCAU(d, false); setDCAU(false); } } else { // dst: no dcau supported - disable src setDCAU((GridFTPClient)src, false); setDCAU(false); } } else { // src: no dcau if (dst instanceof GridFTPClient) { // dst: just disable dcau setDCAU((GridFTPClient)dst, false); } else { // dst: no dcau // we are all set then } setDCAU(false); } } private static void setDCAU(GridFTPClient c, boolean dcau) throws IOException, FTPException { if (c.isFeatureSupported("DCAU")) { if (!dcau) { c.setDataChannelAuthentication(DataChannelAuthentication.NONE); } } else if (dcau) { throw new IOException("DCAU not supported but DCAU requested"); } } /** * Creates ftp connection based on the ftp url (secure vs. unsecure) */ private FTPClient createFTPConnection(GlobusURL ftpURL, boolean srcSide) throws Exception { String protocol = ftpURL.getProtocol(); if (protocol.equalsIgnoreCase("ftp")) { FTPClient ftp = new FTPClient(ftpURL.getHost(), ftpURL.getPort()); ftp.authorize(ftpURL.getUser(), ftpURL.getPwd()); return ftp; } else { GridFTPClient ftp = new GridFTPClient(ftpURL.getHost(), ftpURL.getPort()); if (srcSide) { Authorization auth = getSourceAuthorization(); if (auth == null) { auth = HostAuthorization.getInstance(); } ftp.setAuthorization(auth); ftp.authenticate(getSourceCredentials()); } else { Authorization auth = getDestinationAuthorization(); if (auth == null) { auth = HostAuthorization.getInstance(); } ftp.setAuthorization(auth); ftp.authenticate(getDestinationCredentials()); } if (tcpBufferSize != 0) { ftp.setTCPBufferSize(tcpBufferSize); } return ftp; } } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/urlcopy/UrlCopyException.java000066400000000000000000000017201241116057200313470ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.urlcopy; import org.globus.common.ChainedException; /** * Encapsulates the exceptions caused by various errors * in the url-copy library. */ public class UrlCopyException extends ChainedException { public UrlCopyException(String msg) { super(msg); } public UrlCopyException(String msg, Throwable ex) { super(msg, ex); } } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/urlcopy/UrlCopyListener.java000066400000000000000000000030121241116057200311720ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.io.urlcopy; public interface UrlCopyListener { /** * This function is contniuosly called during url transfers. * * @param transferedBytes number of bytes currently trasfered * if -1, then performing thrid party transfer * @param totalBytes number of total bytes to transfer * if -1, the total size in unknown. */ public void transfer(long transferedBytes, long totalBytes); /** * This function is called only when an error occurs. * * @param exception the actual error exception */ public void transferError(Exception exception); /** * This function is called once the transfer is completed * either successfully or because of a failure. If an error occurred * during the transfer the transferError() function is called first. */ public void transferCompleted(); } JGlobus-JGlobus-Release-2.1.0/io/src/main/java/org/globus/io/urlcopy/package.html000066400000000000000000000015021241116057200275070ustar00rootroot00000000000000 org.globus.io.urlcopy package This library provides a simple API for transferring a file from one location to another. The locations are specified as URLs and any combination of the following protocols is supported: HTTP, HTTPS, FTP, GSIFTP, and FILE. Also, third party transfers can be initialized between any ftp servers that support that feature.

    Package Specification

    Related Documentation

    For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/io/src/test/000077500000000000000000000000001241116057200201545ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/test/java/000077500000000000000000000000001241116057200210755ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/000077500000000000000000000000001241116057200216645ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/globus/000077500000000000000000000000001241116057200231575ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/globus/gram/000077500000000000000000000000001241116057200241055ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/globus/gram/Gram15Test.java000066400000000000000000000252161241116057200266520ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram; import org.globus.io.gass.server.GassServer; import org.globus.util.deactivator.Deactivator; import org.ietf.jgss.GSSException; /** * Demonstration of Gram 1.5 protocol features. *
    */ public class Gram15Test { private static GramJobListener getListener(final String label) { GramJobListener l = ( new GramJobListener() { public void statusChanged(GramJob job) { System.out.println(label + " status change \n" + " ID : "+ job.getIDAsString() + "\n" + " Status : "+ job.getStatusAsString()); } }); return l; } public static boolean test1(String contact, boolean cancelCall) { GramJob job = new GramJob("&(executable=/bin/sleep)(arguments=100)(twoPhase=yes)"); job.addListener(getListener("Job Test 1")); System.out.println("Submitting job..."); try { job.request(contact); System.out.println("job submited: " + job.getIDAsString()); } catch(WaitingForCommitException e) { System.out.println("Two phase commit: sending COMMIT_REQUEST signal"); try { job.signal(GramJob.SIGNAL_COMMIT_REQUEST); } catch(Exception ee) { ee.printStackTrace(); return false; } } catch(GramException e) { e.printStackTrace(); return false; } catch(GSSException e) { e.printStackTrace(); return false; } System.out.println("Sleeping..."); try { Thread.sleep(2000); } catch(Exception e) { } try { if (cancelCall) { System.out.println("Canceling job... (cancel call)"); job.cancel(); } else { System.out.println("Canceling job... (cancel signal)"); job.signal(GramJob.SIGNAL_CANCEL, " "); } } catch(GramException e) { e.printStackTrace(); return false; } catch(GSSException e) { e.printStackTrace(); return false; } System.out.println("Two phase commit: sending COMMIT_END signal"); try { job.signal(GramJob.SIGNAL_COMMIT_END); } catch(Exception ee) { ee.printStackTrace(); return false; } return true; } public static boolean test2(String contact) { GramJob job = new GramJob("&(executable=/bin/sleep)(arguments=20)(twoPhase=yes)"); job.addListener(getListener("Job Test 2")); System.out.println("Submitting job..."); try { job.request(contact); System.out.println("job submited: " + job.getIDAsString()); } catch(WaitingForCommitException e) { System.out.println("Two phase commit: sending COMMIT_EXTEND signal"); try { job.signal(GramJob.SIGNAL_COMMIT_EXTEND, "30"); } catch(Exception ee) { ee.printStackTrace(); return false; } } catch(GramException e) { e.printStackTrace(); return false; } catch(GSSException e) { e.printStackTrace(); return false; } System.out.println("Waiting for timeout..."); try { Thread.sleep(75000); } catch(Exception e) { } if (job.getStatus() == job.STATUS_FAILED) { System.out.println("Error: Timeout expired!"); return false; } else if (job.getStatus() == job.STATUS_UNSUBMITTED) { return true; } return true; } /** * Restart example. */ public static boolean test3(String contact) { String rsl = "&(executable=/bin/sleep)(arguments=50)(saveState=yes)(twoPhase=yes)"; GramJob job = new GramJob(rsl); job.addListener(getListener("Job Test 3")); System.out.println("Submitting job..."); try { job.request(contact); System.out.println("job submited: " + job.getIDAsString()); } catch(WaitingForCommitException e) { System.out.println("Two phase commit: sending COMMIT_REQUEST signal"); try { job.signal(GramJob.SIGNAL_COMMIT_REQUEST); } catch(Exception ee) { ee.printStackTrace(); return false; } } catch(GramException e) { e.printStackTrace(); return false; } catch(GSSException e) { e.printStackTrace(); return false; } System.out.println("Stopping job manager..."); try { job.signal(GramJob.SIGNAL_STOP_MANAGER); } catch(Exception e) { e.printStackTrace(); return false; } System.out.println("Restarting the job..."); job = new GramJob(rsl + "(restart=" + job.getIDAsString() + ")"); job.addListener(getListener("Job Test 3")); try { job.request(contact); System.out.println("New job id: " + job.getIDAsString() ); } catch(WaitingForCommitException e) { System.out.println("Two phase commit: sending COMMIT_REQUEST signal"); try { job.signal(GramJob.SIGNAL_COMMIT_REQUEST); } catch(Exception ee) { ee.printStackTrace(); return false; } } catch(GramException e) { e.printStackTrace(); return false; } catch(GSSException e) { e.printStackTrace(); return false; } try { Thread.sleep(5000); System.out.println("Cancelling job..."); job.cancel(); } catch(Exception e) { e.printStackTrace(); return false; } System.out.println("Two phase commit: sending COMMIT_END signal"); try { job.signal(GramJob.SIGNAL_COMMIT_END); } catch(Exception ee) { ee.printStackTrace(); return false; } return true; } public static boolean test4(String contact) { boolean sendCommit = false; String url = null; GassServer s = null; try { s = new GassServer(); s.registerDefaultDeactivator(); url = s.getURL(); } catch(Exception e) { e.printStackTrace(); return false; } System.out.println("Gass server running at: " + url); String exe = url + "/" + System.getProperty("user.dir") + "/tests/test.sh"; System.out.println(exe); GramJob job = new GramJob("&(saveState=yes)(twoPhase=yes)(executable=" + exe + ")(stdout=" + url + "/dev/stdout)(stderr=" + url + "/dev/stderr)"); job.addListener(getListener("Job Test 4")); try { job.request(contact); System.out.println("job submitted : " + job.getIDAsString() ); } catch(WaitingForCommitException e) { System.out.println("Two phase commit: sending COMMIT_REQUEST signal"); try { job.signal(GramJob.SIGNAL_COMMIT_REQUEST); sendCommit = true; } catch(Exception ee) { ee.printStackTrace(); return false; } } catch(GramException e) { e.printStackTrace(); return false; } catch(GSSException e) { e.printStackTrace(); return false; } try { Thread.sleep(5000); } catch(Exception e) {} // what this should do? System.out.println("Checking stdio positions/sizes..."); try { job.signal(GramJob.SIGNAL_STDIO_SIZE, "1000 1000"); System.out.println("STDIO_SIZE signal should throw an error."); return false; } catch(Exception e) { e.printStackTrace(); } try { Thread.sleep(2000); } catch(Exception e) {} System.out.println("Cancelling job..."); try { job.cancel(); if (sendCommit) { System.out.println("Two phase commit: sending COMMIT_END signal"); job.signal(GramJob.SIGNAL_COMMIT_END); } } catch(Exception ee) { ee.printStackTrace(); return false; } return true; } public static boolean test5(String contact) { String url = null; GassServer s = null; try { s = new GassServer(); s.registerDefaultDeactivator(); url = s.getURL(); } catch(Exception e) { e.printStackTrace(); return false; } System.out.println("Gass server running at: " + url); String exe = url + "/" + System.getProperty("user.dir") + "/tests/test.sh"; System.out.println(exe); GramJob job = new GramJob("&(twoPhase=yes)(executable=" + exe + ")(stdout=" + url + "/dev/stdout)(stderr=" + url + "/dev/stderr)"); job.addListener(getListener("Job Test 4")); System.out.println("Submitting job..."); try { job.request(contact); System.out.println("job submitted : " + job.getIDAsString() ); } catch(WaitingForCommitException e) { System.out.println("Two phase commit: sending COMMIT_REQUEST signal"); try { job.signal(GramJob.SIGNAL_COMMIT_REQUEST); } catch(Exception ee) { ee.printStackTrace(); return false; } } catch(GramException e) { e.printStackTrace(); return false; } catch(GSSException e) { e.printStackTrace(); return false; } try { Thread.sleep(5000); } catch(Exception e) {} try { s.shutdown(); s = new GassServer(); s.registerDefaultDeactivator(); url = s.getURL(); System.out.println("new gass server: " + url); job.signal(GramJob.SIGNAL_STDIO_UPDATE, "&(stdout=" + url + "/dev/stdout)(stdoutPosition=4)(stderrPosition=0)"); } catch(Exception e) { e.printStackTrace(); return false; } return true; } public static void main(String [] args) { String contact = null; if (args.length == 0) { System.err.println("Usage: java GramTest [resource manager]"); System.exit(1); } contact = args[0]; System.out.println("TEST 1 : " + test1(contact, true)); System.out.println(); System.out.println("TEST 2 : " + test1(contact, false)); System.out.println(); System.out.println("TEST 3 : " + test3(contact)); System.out.println(); System.out.println("TEST 4 : " + test2(contact)); System.out.println(); System.out.println("TEST 5 : " + test4(contact)); System.out.println(); System.out.println("TEST 6 : " + test5(contact)); System.out.println(); try { while ( Gram.getActiveJobs() != 0 ) { Thread.sleep(2000); } } catch(Exception e) {} Deactivator.deactivateAll(); } } JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/globus/gram/tests/000077500000000000000000000000001241116057200252475ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/globus/gram/tests/GramTest.java000066400000000000000000000245241241116057200276470ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.gram.tests; import java.io.File; import java.io.ByteArrayOutputStream; import org.globus.gram.GramJob; import org.globus.gram.Gram; import org.globus.gram.GramException; import org.globus.gram.GramJobListener; import org.globus.gram.WaitingForCommitException; import org.globus.gram.util.TestUtil; import org.globus.io.gass.server.GassServer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; public class GramTest extends TestCase { private static final int TIMEOUT = 1000*60*2; private static Log logger = LogFactory.getLog(GramTest.class.getName()); private static final String CONFIG = "test.properties"; private static TestUtil util; static { try { System.out.println("Current directory = "+ System.getProperty("user.dir")); util = new TestUtil(CONFIG); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public GramTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); Gram.deactivateAllCallbackHandlers(); } public static Test suite() { return new TestSuite(GramTest.class); } public void testPing() throws Exception { System.out.println("CONTACT = "+ util.get("job.long.contact")); if ((util.get("job.long.contact"))==null) System.out.println("NULL VALUE FROM UTIL"); Gram.ping(util.get("job.long.contact")); } public void testActiveJobs() throws Exception { GramJob job1 = new GramJob(util.get("job.long")); job1.request(util.get("job.long.contact")); GramJob job2 = new GramJob(util.get("job.long")); job2.request(util.get("job.long.contact")); assertEquals(2, Gram.getActiveJobs()); int i = 0; while ( Gram.getActiveJobs() != 0 ) { Thread.sleep(2000); i++; if (i == 40) { fail("getActiveJob() did not reported 0 jobs"); } } } public void testJobStatusPoll() throws Exception { GramJob job = new GramJob(util.get("job.long")); logger.debug("submitting job in batch mode..."); job.request(util.get("job.long.contact"), true); logger.debug("job submitted: " + job.getIDAsString()); String status = null; do { try { Thread.sleep(5000); } catch(Exception e) {} logger.debug("querying status on job..."); try { Gram.jobStatus(job); } catch(GramException e) { if (e.getErrorCode() == GramException.ERROR_CONTACTING_JOB_MANAGER) { if (status == null) { fail("Error contacting job manager - could not get job status"); } else { logger.debug("error contacting job manager - assuming job is finished."); break; } } else { fail("Failed to get job status: " + e.getMessage()); } } status = job.getStatusAsString(); logger.debug("status: " + status); } while (!status.equals("DONE")); } public void testBind() throws Exception { GramJob job = new GramJob(util.get("job.long")); logger.debug("submitting job in batch mode..."); job.request(util.get("job.long.contact"), true); logger.debug("job submitted: " + job.getIDAsString()); DoneStatusListener listener = new DoneStatusListener(); job.addListener(listener); job.bind(); if (!listener.waitFor(TIMEOUT)) { fail("Did not get DONE notification"); } } public void testCancel() throws Exception { GramJob job = new GramJob(util.get("job.long")); FailedStatusListener listener = new FailedStatusListener(); job.addListener(listener); logger.debug("submitting job in interactive mode..."); job.request(util.get("job.long.contact")); logger.debug("job submitted: " + job.getIDAsString()); Thread.sleep(5000); job.cancel(); if (!listener.waitFor(TIMEOUT)) { fail("Did not get FAILED notification"); } } public void testUnbind() throws Exception { GramJob job = new GramJob(util.get("job.long")); ActiveStatusListener listener = new ActiveStatusListener(); job.addListener(listener); logger.debug("submitting job in interactive mode..."); job.request(util.get("job.long.contact")); logger.debug("job submitted: " + job.getIDAsString()); if (!listener.waitFor(TIMEOUT)) { fail("Did not get ACTIVE notification"); } job.unbind(); listener.reset(); Thread.sleep(2000); job.cancel(); if (listener.getNotified()) { fail("Unconnected listener received unexpected notification."); } } public void testBadParameter() throws Exception { GramJob job = new GramJob("&(argument=12)"); try { job.request(util.get("job.long.contact")); } catch (GramException e) { if (e.getErrorCode() != GramException.PARAMETER_NOT_SUPPORTED) { e.printStackTrace(); fail("Unexpected error returned: " + e.getMessage()); } } } public void testBadExecutable() throws Exception { GramJob job = new GramJob("&(executable=/bin/thisexecdoesnotexist)"); FailedStatusListener listener = new FailedStatusListener(); job.addListener(listener); try { job.request(util.get("job.long.contact")); } catch (GramException e) { if (e.getErrorCode() != GramException.EXECUTABLE_NOT_FOUND) { e.printStackTrace(); fail("Unexpected error returned: " + e.getMessage()); } logger.debug("Error returned on request()"); return; } if (!listener.waitFor(TIMEOUT)) { fail("Did not get FAILED notification"); } if (job.getError() != GramException.EXECUTABLE_NOT_FOUND) { fail("Unexpected error returned: " + job.getError()); } } public void testRedirect() throws Exception { DoneStatusListener listener = new DoneStatusListener(); GassServer server = null; try { server = new GassServer(); String url = server.getURL(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); StringBuffer rsl = new StringBuffer(); rsl.append("&(executable=") .append(util.get("stdin.exe")) .append(")"); rsl.append("(rsl_substitution=(GLOBUSRUN_GASS_URL ") .append(url) .append("))"); rsl.append("(stdin=$(GLOBUSRUN_GASS_URL)/") .append(util.get("stdin.file")) .append(")"); rsl.append("(stdout=$(GLOBUSRUN_GASS_URL)/dev/stdout-rgs)"); server.registerJobOutputStream("out-rgs", stdout); System.out.println(rsl); GramJob job = new GramJob(rsl.toString()); job.addListener(listener); job.request(util.get("job.long.contact")); if (!listener.waitFor(TIMEOUT)) { fail("Did not get DONE notification"); } File f = new File(util.get("stdin.file")); byte[] stdoutData = stdout.toByteArray(); assertEquals("stdout size", f.length(), stdoutData.length); } finally { if (server != null) { server.shutdown(); } } } class DoneStatusListener implements GramJobListener { boolean notified = false; public synchronized void statusChanged(GramJob job) { if (job.getStatus() == GramJob.STATUS_DONE) { notified = true; notify(); } } public synchronized boolean waitFor(int timeout) throws Exception { wait(timeout); return notified; } } class FailedStatusListener implements GramJobListener { boolean notified = false; public synchronized void statusChanged(GramJob job) { if (job.getStatus() == GramJob.STATUS_FAILED) { notified = true; notify(); } } public synchronized boolean waitFor(int timeout) throws Exception { wait(timeout); return notified; } } class ActiveStatusListener implements GramJobListener { boolean notified = false; public synchronized void statusChanged(GramJob job) { if (job.getStatus() == GramJob.STATUS_ACTIVE) { notified = true; notify(); } } public synchronized boolean waitFor(int timeout) throws Exception { wait(timeout); return notified; } public void reset() { notified = false; } public boolean getNotified() { return notified; } } // These are 1.5 gram tests public void testTwoPhaseSignalCancel() throws Exception { twoPhaseSubmit(false); } public void testTwoPhaseCancel() throws Exception { twoPhaseSubmit(true); } private void twoPhaseSubmit(boolean cancelCall) throws Exception { GramJob job = new GramJob(util.get("job.long") + "(twoPhase=yes)"); try { job.request(util.get("job.long.contact")); fail("Did not throw expected exception"); } catch(WaitingForCommitException e) { logger.debug("Two phase commit: sending COMMIT_REQUEST signal"); job.signal(GramJob.SIGNAL_COMMIT_REQUEST); } logger.debug("job submited: " + job.getIDAsString()); Thread.sleep(5000); // this is little weird... cancel() and signal_cancel() should // behave in the same exact way but they do not if (cancelCall) { logger.debug("Canceling job... (cancel call)"); job.cancel(); // XXX: this should be common to both ways logger.debug("Two phase commit: sending COMMIT_END signal"); job.signal(GramJob.SIGNAL_COMMIT_END); } else { logger.debug("Canceling job... (cancel signal)"); job.signal(GramJob.SIGNAL_CANCEL, " "); } } public void testTwoPhaseExtend() throws Exception { GramJob job = new GramJob(util.get("job.long") + "(twoPhase=yes)"); try { job.request(util.get("job.long.contact")); } catch(WaitingForCommitException e) { logger.debug("Two phase commit: sending COMMIT_EXTEND signal"); job.signal(GramJob.SIGNAL_COMMIT_EXTEND, "30"); } logger.debug("job submited: " + job.getIDAsString()); Thread.sleep(75000); if (job.getStatus() == job.STATUS_FAILED) { fail("Timeout expired!"); } } } JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/globus/gram/tests/test.sh000066400000000000000000000001421241116057200265570ustar00rootroot00000000000000#! /bin/sh echo test 1 2 3 echo test 4 5 6 sleep 10 echo test 7 8 9 echo "test 10 11 12" 1>&2 JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/globus/gram/util/000077500000000000000000000000001241116057200250625ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/test/java/org/globus/gram/util/TestUtil.java000066400000000000000000000026071241116057200275070ustar00rootroot00000000000000package org.globus.gram.util; /* * Copyright 1999-2006 University of Chicago * * 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. */ import java.util.Properties; import java.io.InputStream; import java.io.IOException; public class TestUtil { private Properties props; public TestUtil(String config) throws Exception { Thread t = Thread.currentThread(); InputStream in = null; try { in = t.getContextClassLoader().getResourceAsStream(config); if (in == null) { throw new IOException("Test configuration file not found: " + config); } props = new Properties(); props.load(in); } finally { if (in != null) { in.close(); } } } public String get(String propName) { return props.getProperty(propName); } public int getAsInt(String propName) { String value = props.getProperty(propName); return Integer.parseInt(value); } } JGlobus-JGlobus-Release-2.1.0/io/src/test/resources/000077500000000000000000000000001241116057200221665ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/io/src/test/resources/test.properties000066400000000000000000000003041241116057200252600ustar00rootroot00000000000000job.long=&(executable=/bin/sleep)(arguments=35) job.long.contact=ubuntu:50000:/O=Grid/OU=GlobusTest/OU=simpleCA-ubuntu/CN=Vijay Anand stdin.exe=/bin/cat stdin.file=/home/vijay/archive/CHANGES.TXT JGlobus-JGlobus-Release-2.1.0/jsse/000077500000000000000000000000001241116057200167435ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/README.textile000066400000000000000000000000001241116057200212660ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/pom.xml000066400000000000000000000014451241116057200202640ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 jsse SSL support junit junit test ${project.groupId} ssl-proxies ${project.version} JGlobus-JGlobus-Release-2.1.0/jsse/src/000077500000000000000000000000001241116057200175325ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/main/000077500000000000000000000000001241116057200204565ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/000077500000000000000000000000001241116057200213775ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/org/000077500000000000000000000000001241116057200221665ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/org/globus/000077500000000000000000000000001241116057200234615ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/org/globus/gsi/000077500000000000000000000000001241116057200242435ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/org/globus/gsi/jsse/000077500000000000000000000000001241116057200252075ustar00rootroot00000000000000GlobusSSLConfigurationException.java000066400000000000000000000022371241116057200342230ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/org/globus/gsi/jsse/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.jsse; /** * Signals an error in configuring the Globus SSL support. * * @version ${version} * @since 1.0 */ public class GlobusSSLConfigurationException extends Exception { /** * */ private static final long serialVersionUID = 1L; public GlobusSSLConfigurationException() { } public GlobusSSLConfigurationException(String message) { super(message); } public GlobusSSLConfigurationException(String message, Throwable cause) { super(message, cause); } public GlobusSSLConfigurationException(Throwable cause) { super(cause); } } JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/org/globus/gsi/jsse/GlobusSSLHelper.java000066400000000000000000000166221241116057200310360ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.jsse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.gsi.stores.Stores; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.cert.CertStore; import java.security.cert.CertificateException; /** * This is a utility class designed to simplify common tasks required for * configuring the globus ssl support. * * @version 1.0 * @since 1.0 */ // TODO: support custom classloader public final class GlobusSSLHelper { private GlobusSSLHelper() { // Should not be instantiated. } /** * Create a trust store using the supplied details. Java SSL requires the * trust store to be supplied as a java.security.KeyStore, so this will * create a KeyStore containing all of the Trust Anchors. * * @param provider * The Java security provider to use. * @param trustAnchorStoreType * The type of key store to be constructed. * @param trustAnchorStoreLocation * The location of the trust store file * @param trustAnchorStorePassword * The password for the trust store. * @return A configured Keystore which holds TrustAnchors. Note that this * holds trusted certificates, not keys/credentials * @throws GlobusSSLConfigurationException * If unable to construct the TrustStore. */ public static KeyStore buildTrustStore(String provider, String trustAnchorStoreType, String trustAnchorStoreLocation, String trustAnchorStorePassword) throws GlobusSSLConfigurationException { try { KeyStore trustAnchorStore; if (provider == null) { trustAnchorStore = KeyStore.getInstance(trustAnchorStoreType); } else { trustAnchorStore = KeyStore.getInstance(trustAnchorStoreType, provider); } InputStream keyStoreInput = getStream(trustAnchorStoreLocation); try { trustAnchorStore.load(new BufferedInputStream(keyStoreInput), trustAnchorStorePassword == null ? null : trustAnchorStorePassword.toCharArray()); } finally { keyStoreInput.close(); } return trustAnchorStore; } catch (KeyStoreException e) { throw new GlobusSSLConfigurationException(e); } catch (IOException e) { throw new GlobusSSLConfigurationException(e); } catch (NoSuchAlgorithmException e) { throw new GlobusSSLConfigurationException(e); } catch (CertificateException e) { throw new GlobusSSLConfigurationException(e); } catch (NoSuchProviderException e) { throw new GlobusSSLConfigurationException(e); } } /** * Create a configured CredentialStore using the supplied parameters. The * credential store is a java.security.KeyStore. * * @param provider * The Java security provider to use. * @param credentialStoreType * The type of key store to be constructed. * @param credentialStoreLocation * The location of the credential store file * @param credentialStorePassword * The password for the credential store. * @return A configured Keystore which holds credentials defined by these * parameters. * @throws GlobusSSLConfigurationException * If unable to construct the Credential Store. */ public static KeyStore findCredentialStore(String provider, String credentialStoreType, String credentialStoreLocation, String credentialStorePassword) throws GlobusSSLConfigurationException { try { KeyStore credentialStore; if (provider == null) { credentialStore = KeyStore.getInstance(credentialStoreType); } else { credentialStore = KeyStore.getInstance(credentialStoreType, provider); } InputStream keyStoreInput = getStream(credentialStoreLocation); try { credentialStore.load(new BufferedInputStream(keyStoreInput), credentialStorePassword == null ? null : credentialStorePassword.toCharArray()); } finally { keyStoreInput.close(); } return credentialStore; } catch (KeyStoreException e) { throw new GlobusSSLConfigurationException(e); } catch (IOException e) { throw new GlobusSSLConfigurationException(e); } catch (NoSuchAlgorithmException e) { throw new GlobusSSLConfigurationException(e); } catch (CertificateException e) { throw new GlobusSSLConfigurationException(e); } catch (NoSuchProviderException e) { throw new GlobusSSLConfigurationException(e); } } private static InputStream getStream(String url) throws MalformedURLException, IOException { if (url.startsWith("classpath:")) { String resource = url.substring(10); URL u = ClassLoader.class.getResource(resource); if (u == null) { throw new MalformedURLException(); } return u.openStream(); } else if (url.startsWith("file:")) { URL u = new URL(url); File f; try { f = new File(u.toURI()); } catch (URISyntaxException e) { f = new File(u.getPath()); } return new FileInputStream(f); } else { return new URL(url).openStream(); } } /** * Create a store of Certificate Revocation Lists. Java requires that this * be a java.security.certificates.CertStore. As such, the store can hold * both CRL's and non-trusted certs. For the purposes of this method, we * assume that only crl's will be loaded. This can only be used with the * Globus provided Certificate Store. * * @param crlPattern * The pattern which defines the locations of the CRL's * @return A configured Java CertStore containing the specified CRL's * @throws GlobusSSLConfigurationException * if the store cannot be loaded. */ public static CertStore findCRLStore(String crlPattern) throws GlobusSSLConfigurationException { try { return Stores.getCRLStore(crlPattern); } catch (InvalidAlgorithmParameterException e) { throw new GlobusSSLConfigurationException(e); } catch (NoSuchAlgorithmException e) { Log logger = LogFactory.getLog(GlobusSSLHelper.class.getCanonicalName()); logger.warn("Error Loading CRL store", e); throw new GlobusSSLConfigurationException(e); } catch (GeneralSecurityException e) { Log logger = LogFactory.getLog(GlobusSSLHelper.class.getCanonicalName()); logger.warn("Error Loading CRL store", e); throw new GlobusSSLConfigurationException(e); } } } JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/org/globus/gsi/jsse/GlobusTLSContext.java000066400000000000000000000103631241116057200312400ustar00rootroot00000000000000package org.globus.gsi.jsse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.ByteArrayInputStream; import java.security.Principal; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Date; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.security.auth.Subject; import org.apache.commons.codec.binary.Hex; public class GlobusTLSContext { private static ThreadLocal containerSubjectHolder = new ThreadLocal(); private Subject containerSubject; private Subject peerSubject; private X509Certificate[] localCertChain; private X509Certificate[] peerCertChain; private Principal localPrincipal; private Principal peerPrincipal; private Date creationTime; private String sessionId; private String cipherSuite; private String protocol; private String peerHost; private int peerPort; private Log logger = LogFactory.getLog(getClass().getCanonicalName()); public GlobusTLSContext(SSLSession sslSession) { containerSubject = new Subject(); containerSubject.getPrincipals().add(sslSession.getLocalPrincipal()); containerSubject.getPublicCredentials().add( getLocalCertChain(sslSession)); GlobusTLSContext.containerSubjectHolder.set(containerSubject); peerSubject = new Subject(); try { peerSubject.getPrincipals().add(sslSession.getPeerPrincipal()); } catch (SSLPeerUnverifiedException e) { // We should already be verified, but if by some crazy chance we // aren't logger.warn(e.getLocalizedMessage(), e); } peerSubject.getPublicCredentials().add(getPeerCertChain(sslSession)); creationTime = new Date(sslSession.getCreationTime()); try { sessionId = new String(Hex.encodeHex(sslSession.getId())); } catch (Exception e) { logger.warn(e.getLocalizedMessage(), e); } cipherSuite = sslSession.getCipherSuite(); protocol = sslSession.getProtocol(); peerHost = sslSession.getPeerHost(); peerPort = sslSession.getPeerPort(); } public static Subject getCurrentContainerSubject() { return GlobusTLSContext.containerSubjectHolder.get(); } public X509Certificate[] getLocalCertChain() { return localCertChain; } public X509Certificate[] getPeerCertChain() { return peerCertChain; } public Principal getLocalPrincipal() { return localPrincipal; } public Principal getPeerPrincipal() { return peerPrincipal; } public Date getCreationTime() { return creationTime; } public String getSessionId() { return sessionId; } public String getCipherSuite() { return cipherSuite; } public String getProtocol() { return protocol; } public String getPeerHost() { return peerHost; } public int getPeerPort() { return peerPort; } private X509Certificate[] getLocalCertChain(SSLSession sslSession) { try { Certificate[] javaxCerts = sslSession.getLocalCertificates(); return processCerts(javaxCerts); } catch (Exception e) { logger.warn(e.getLocalizedMessage(), e); return null; } } private X509Certificate[] getPeerCertChain(SSLSession sslSession) { Certificate[] javaxCerts; try { javaxCerts = sslSession.getPeerCertificates(); return processCerts(javaxCerts); } catch (SSLPeerUnverifiedException e) { logger.warn(e.getLocalizedMessage(), e); return null; } catch (CertificateEncodingException e) { logger.warn(e.getLocalizedMessage(), e); return null; } catch (CertificateException e) { logger.warn(e.getLocalizedMessage(), e); return null; } } private X509Certificate[] processCerts( java.security.cert.Certificate[] javaxCerts) throws CertificateException, CertificateEncodingException { if (javaxCerts == null || javaxCerts.length == 0) return null; int length = javaxCerts.length; X509Certificate[] javaCerts = new X509Certificate[length]; java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory .getInstance("X.509"); for (int i = 0; i < length; i++) { byte bytes[] = javaxCerts[i].getEncoded(); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); javaCerts[i] = (X509Certificate) cf.generateCertificate(stream); } return javaCerts; } } JGlobus-JGlobus-Release-2.1.0/jsse/src/main/java/org/globus/gsi/jsse/SSLConfigurator.java000066400000000000000000000247561241116057200311140ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.jsse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.security.InvalidAlgorithmParameterException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.Security; import java.security.UnrecoverableKeyException; import java.security.cert.CertStore; import java.util.Map; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.globus.gsi.provider.GlobusTrustManagerFactoryParameters; import org.globus.gsi.provider.SigningPolicyStore; import org.globus.gsi.proxy.ProxyPolicyHandler; /** * This class is used to configure and create SSL socket factories. The * factories can either be built by setting the credentialStore, crlStore, * trustAnchorStore and policyStore directly, or it can use the java security * SPI mechanism. This is the simplest way to configure the globus ssl support. * * @version ${version} * @since 1.0 */ public class SSLConfigurator { private String provider; private String protocol = "TLS"; private String secureRandomAlgorithm; private KeyStore credentialStore; private KeyStore trustAnchorStore; private CertStore crlStore; private SigningPolicyStore policyStore; private boolean rejectLimitProxy; private Map handlers; private String trustAnchorStoreType; private String trustAnchorStoreLocation; private String trustAnchorStorePassword; private String credentialStoreType; private String credentialStoreLocation; private String credentialStorePassword; private String crlStoreType; private String crlLocationPattern; private SSLContext sslContext; private Log logger = LogFactory.getLog(getClass()); private String sslKeyManagerFactoryAlgorithm = Security .getProperty("ssl.KeyManagerFactory.algorithm") == null ? "SunX509" : Security.getProperty("ssl.KeyManagerFactory.algorithm"); /** * Create an SSLSocketFactory based on the configured stores. * * @return A configured SSLSocketFactory * @throws GlobusSSLConfigurationException * If we fail to create the socketFactory. */ public SSLSocketFactory createFactory() throws GlobusSSLConfigurationException { return getSSLContext().getSocketFactory(); } /** * Create an SSLContext based on the configured stores. * * @return A configured SSLContext. * @throws GlobusSSLConfigurationException * If we fail to create the context. */ public SSLContext getSSLContext() throws GlobusSSLConfigurationException { if (sslContext == null) { configureContext(); } return this.sslContext; } /** * Create an SSLServerSocketFactory based on the configured stores. * * @return A configured SSLServerSocketFactory * @throws GlobusSSLConfigurationException * If we fail to create the server socket factory. */ public SSLServerSocketFactory createServerFactory() throws GlobusSSLConfigurationException { SSLContext context = getSSLContext(); return context.getServerSocketFactory(); } private void configureContext() throws GlobusSSLConfigurationException { ManagerFactoryParameters parameters = getCertPathParameters(); TrustManager[] trustManagers; try { TrustManagerFactory fact = TrustManagerFactory.getInstance("GSI"); fact.init(parameters); trustManagers = fact.getTrustManagers(); } catch (NoSuchAlgorithmException e1) { throw new GlobusSSLConfigurationException(e1); } catch (InvalidAlgorithmParameterException e) { throw new GlobusSSLConfigurationException(e); } KeyManager[] keyManagers = loadKeyManagers(); SecureRandom secureRandom = loadSecureRandom(); sslContext = loadSSLContext(); try { sslContext.init(keyManagers, trustManagers, secureRandom); } catch (KeyManagementException e) { throw new GlobusSSLConfigurationException(e); } } private ManagerFactoryParameters getCertPathParameters() throws GlobusSSLConfigurationException { GlobusTrustManagerFactoryParameters parameters; KeyStore inputTrustStore; if (this.trustAnchorStore == null) { logger.trace("No trustAnchorStore available"); inputTrustStore = GlobusSSLHelper.buildTrustStore(this.provider, this.trustAnchorStoreType, this.trustAnchorStoreLocation, this.trustAnchorStorePassword); } else { inputTrustStore = this.trustAnchorStore; } CertStore inputCertStore = this.crlStore != null? this.crlStore: GlobusSSLHelper.findCRLStore(this.crlLocationPattern); if (handlers == null) { parameters = new GlobusTrustManagerFactoryParameters( inputTrustStore, inputCertStore, this.policyStore, this.rejectLimitProxy); } else { parameters = new GlobusTrustManagerFactoryParameters( inputTrustStore, inputCertStore, this.policyStore, this.rejectLimitProxy, handlers); } return parameters; } private SSLContext loadSSLContext() throws GlobusSSLConfigurationException { try { return provider == null ? SSLContext.getInstance(protocol) : SSLContext.getInstance(protocol, provider); } catch (NoSuchAlgorithmException e) { throw new GlobusSSLConfigurationException(e); } catch (NoSuchProviderException e) { throw new GlobusSSLConfigurationException(e); } } private SecureRandom loadSecureRandom() throws GlobusSSLConfigurationException { try { return secureRandomAlgorithm == null ? null : SecureRandom .getInstance(secureRandomAlgorithm); } catch (NoSuchAlgorithmException e) { throw new GlobusSSLConfigurationException(e); } } private KeyManager[] loadKeyManagers() throws GlobusSSLConfigurationException { try { KeyStore inputKeyStore; if (this.credentialStore == null) { if (this.credentialStoreLocation == null) return null; inputKeyStore = GlobusSSLHelper.findCredentialStore( this.provider, this.credentialStoreType, this.credentialStoreLocation, this.credentialStorePassword); } else { inputKeyStore = this.credentialStore; } KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(sslKeyManagerFactoryAlgorithm); keyManagerFactory.init(inputKeyStore, credentialStorePassword == null ? null : credentialStorePassword.toCharArray()); return keyManagerFactory.getKeyManagers(); } catch (KeyStoreException e) { throw new GlobusSSLConfigurationException(e); } catch (NoSuchAlgorithmException e) { throw new GlobusSSLConfigurationException(e); } catch (UnrecoverableKeyException e) { throw new GlobusSSLConfigurationException(e); } } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getSecureRandomAlgorithm() { return secureRandomAlgorithm; } public void setSecureRandomAlgorithm(String secureRandomAlgorithm) { this.secureRandomAlgorithm = secureRandomAlgorithm; } public String getCredentialStorePassword() { return credentialStorePassword; } public void setCredentialStorePassword(String credentialStorePassword) { this.credentialStorePassword = credentialStorePassword; } public KeyStore getTrustAnchorStore() { return trustAnchorStore; } public void setTrustAnchorStore(KeyStore trustAnchorStore) { this.trustAnchorStore = trustAnchorStore; } public CertStore getCrlStore() { return crlStore; } public void setCrlStore(CertStore crlStore) { this.crlStore = crlStore; } public SigningPolicyStore getPolicyStore() { return policyStore; } public void setPolicyStore(SigningPolicyStore policyStore) { this.policyStore = policyStore; } public boolean isRejectLimitProxy() { return rejectLimitProxy; } public void setRejectLimitProxy(boolean rejectLimitProxy) { this.rejectLimitProxy = rejectLimitProxy; } public Map getHandlers() { return handlers; } public void setHandlers(Map handlers) { this.handlers = handlers; } public String getCredentialStoreLocation() { return credentialStoreLocation; } public void setCredentialStoreLocation(String credentialStoreLocation) { this.credentialStoreLocation = credentialStoreLocation; } public String getCredentialStoreType() { return credentialStoreType; } public void setCredentialStoreType(String credentialStoreType) { this.credentialStoreType = credentialStoreType; } public String getTrustAnchorStoreType() { return trustAnchorStoreType; } public void setTrustAnchorStoreType(String trustAnchorStoreType) { this.trustAnchorStoreType = trustAnchorStoreType; } public String getTrustAnchorStoreLocation() { return trustAnchorStoreLocation; } public void setTrustAnchorStoreLocation(String trustAnchorStoreLocation) { this.trustAnchorStoreLocation = trustAnchorStoreLocation; } public String getTrustAnchorStorePassword() { return trustAnchorStorePassword; } public void setTrustAnchorStorePassword(String trustAnchorStorePassword) { this.trustAnchorStorePassword = trustAnchorStorePassword; } public String getCrlStoreType() { return crlStoreType; } public void setCrlStoreType(String crlStoreType) { this.crlStoreType = crlStoreType; } public String getCrlLocationPattern() { return crlLocationPattern; } public void setCrlLocationPattern(String crlLocationPattern) { this.crlLocationPattern = crlLocationPattern; } public KeyStore getCredentialStore() { return credentialStore; } public void setCredentialStore(KeyStore credentialStore) { this.credentialStore = credentialStore; } } JGlobus-JGlobus-Release-2.1.0/jsse/src/main/resources/000077500000000000000000000000001241116057200224705ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/main/resources/log4j.properties000066400000000000000000000004221241116057200256230ustar00rootroot00000000000000log4j.rootCategory=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c{2} %x - %m%n log4j.category.COM.claymoresystems.ptls.SSLDebug=OFF JGlobus-JGlobus-Release-2.1.0/jsse/src/test/000077500000000000000000000000001241116057200205115ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/test/java/000077500000000000000000000000001241116057200214325ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/test/java/org/000077500000000000000000000000001241116057200222215ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/test/java/org/globus/000077500000000000000000000000001241116057200235145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/test/java/org/globus/gsi/000077500000000000000000000000001241116057200242765ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/test/java/org/globus/gsi/jsse/000077500000000000000000000000001241116057200252425ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/test/java/org/globus/gsi/jsse/SSLConfiguratorTest.java000066400000000000000000000115161241116057200317750ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.jsse; import static org.junit.Assert.assertEquals; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.gsi.jsse.GlobusSSLConfigurationException; import org.globus.gsi.jsse.SSLConfigurator; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.security.Security; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.stores.ResourceSigningPolicyStore; import org.globus.gsi.stores.Stores; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class SSLConfiguratorTest { private static SSLSocket sslsocket; private static SSLServerSocket serverSocket; private CountDownLatch latch = new CountDownLatch(1); private StringBuilder builder = new StringBuilder(); @BeforeClass public static void setup() throws Exception { Security.addProvider(new GlobusProvider()); } @Test public void testConfig() throws Exception { SSLConfigurator config = new SSLConfigurator(); config.setCrlLocationPattern(null); config.setCrlStoreType(GlobusProvider.CERTSTORE_TYPE); config.setCredentialStoreLocation("classpath:/configuratorTest/mykeystore.properties"); config.setCredentialStorePassword("password"); config.setCredentialStoreType(GlobusProvider.KEYSTORE_TYPE); config.setTrustAnchorStoreLocation("classpath:/configuratorTest/mytruststore.properties"); config.setTrustAnchorStorePassword("password"); config.setTrustAnchorStoreType(GlobusProvider.KEYSTORE_TYPE); ResourceSigningPolicyStore policyStore = Stores.getSigningPolicyStore("classpath:/configuratorTest/TestCA1.signing_policy"); config.setPolicyStore(policyStore); serverSocket = startServer(config); latch.await(); sslsocket = runClient(config); OutputStream outputstream = sslsocket.getOutputStream(); OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream); BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter); bufferedwriter.write("hello"); bufferedwriter.flush(); } private SSLSocket runClient(SSLConfigurator config) throws IOException, GlobusSSLConfigurationException { SSLSocketFactory sslsocketfactory = config.createFactory(); return (SSLSocket) sslsocketfactory.createSocket("localhost", 9991); } @AfterClass public static void stop() throws Exception { serverSocket.close(); sslsocket.close(); } Log logger = LogFactory.getLog(SSLConfiguratorTest.class); private SSLServerSocket startServer(SSLConfigurator config) throws GlobusSSLConfigurationException, IOException { SSLServerSocketFactory sslserversocketfactory = config .createServerFactory(); final SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory .createServerSocket(9991); ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(new Runnable() { /** * When an object implementing interface Runnable is * used to create a thread, starting the thread causes the object's * run method to be called in that separately executing * thread. *

    * The general contract of the method run is that it * may take any action whatsoever. * * @see Thread#run() */ public void run() { latch.countDown(); try { SSLSocket sslsocket = (SSLSocket) sslserversocket.accept(); InputStream inputstream = sslsocket.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader( inputstream); BufferedReader bufferedreader = new BufferedReader( inputstreamreader); String line; while ((line = bufferedreader.readLine()) != null) { builder.append(line); } assertEquals(builder.toString().trim(), "hello"); } catch (IOException e) { e.printStackTrace(); } } }); return sslserversocket; } } JGlobus-JGlobus-Release-2.1.0/jsse/src/test/resources/000077500000000000000000000000001241116057200225235ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/test/resources/configuratorTest/000077500000000000000000000000001241116057200260655ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/jsse/src/test/resources/configuratorTest/TestCA1.signing_policy000066400000000000000000000002421241116057200322260ustar00rootroot00000000000000#TestCA1.signing_policy access_id_CA X509 '/O=Auto/OU=JGlobusTestCA/CN=CA' pos_rights globus CA:sign cond_subjects globus '"/*"' JGlobus-JGlobus-Release-2.1.0/jsse/src/test/resources/configuratorTest/cacert.pem000066400000000000000000000016301241116057200300310ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICeTCCAeKgAwIBAgIBADANBgkqhkiG9w0BAQUFADA0MQ0wCwYDVQQKEwRBdXRv MRYwFAYDVQQLEw1KR2xvYnVzVGVzdENBMQswCQYDVQQDEwJDQTAeFw0xMTAzMTUw MTE4NTdaFw0xNjAzMTUwMTE5MDdaMDQxDTALBgNVBAoTBEF1dG8xFjAUBgNVBAsT DUpHbG9idXNUZXN0Q0ExCzAJBgNVBAMTAkNBMIGfMA0GCSqGSIb3DQEBAQUAA4GN ADCBiQKBgQCkfnJsLXlvbNFQB7k1i8A86R7e/9BSwYif/OG0bNhsnewgLekyrRa+ HmReo0cBc8+wvUexHEyBKhOCmpyCW4mzTvH6lVSQHb4Gef54tc4wZS/R6luGweRU zW8CWOOTCj0nJIviefkKHhB5v/beHmhP+i4T0Y08Rz4FBraq/uL9AQIDAQABo4Ga MIGXMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHGg7KW9MikplKFKhlCEtrs+ pnw0MFgGA1UdIwRRME+AFHGg7KW9MikplKFKhlCEtrs+pnw0oTQxDTALBgNVBAoT BEF1dG8xFjAUBgNVBAsTDUpHbG9idXNUZXN0Q0ExCzAJBgNVBAMTAkNBggEAMAsG A1UdDwQEAwIBBjANBgkqhkiG9w0BAQUFAAOBgQBFwAHr43BToa1G3zcSX7jykigw SBCOJgncdO7H4cYhP5xNrslzwo9J3iPFqT9Lgdfdw7b4i+ey9CektgiUHUK78EkS 4bM3L29V2bcEjLIXhWBzI18j2oIw+aybc5U/A0VgdPh9M1JpKT99FxzliWz541FR MQvlvnnX4vUr0Th0HQ== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/jsse/src/test/resources/configuratorTest/mykeystore.properties000066400000000000000000000016671241116057200324300ustar00rootroot00000000000000# # Copyright 1999-2010 University of Chicago # # 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. # # Properties file as input to the keystore (PEMFilebasedKeystore) # Name of proxy file #proxyFilename=/Users/ranantha/work/sos/gitRepository/Globus-Security/integratioon-example/target/classes/proxy.pem # Name of certificate file certificateFilename=classpath:/configuratorTest/usercert.pem # Name of key file keyFilename=classpath:/configuratorTest/userkey.pem JGlobus-JGlobus-Release-2.1.0/jsse/src/test/resources/configuratorTest/mytruststore.properties000066400000000000000000000012021241116057200330020ustar00rootroot00000000000000# # Copyright 1999-2010 University of Chicago # # 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. # directory_list=classpath:/configuratorTest/cacert.pemJGlobus-JGlobus-Release-2.1.0/jsse/src/test/resources/configuratorTest/usercert.pem000066400000000000000000000013711241116057200304260ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICBjCCAW+gAwIBAgIBADANBgkqhkiG9w0BAQUFADA0MQ0wCwYDVQQKEwRBdXRv MRYwFAYDVQQLEw1KR2xvYnVzVGVzdENBMQswCQYDVQQDEwJDQTAeFw0xMTAzMTUw MTIzMzdaFw0xNjAzMTUwMTIzNDdaMDwxDTALBgNVBAoTBEF1dG8xFjAUBgNVBAsT DUpHbG9idXNUZXN0Q0ExEzARBgNVBAMTCmdsb2J1cy5vcmcwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAI7a/QhZuFGUCvvznueSxdFaKlTxcAWG790jm56417qK 1tktcNmoX3mzuY0yu5vVQ/6Mk7NWHTnijGfjdONLF5ImTY9SsXzEFgPCcXZUgJ4R xkfl+PGLj/OBN4NCXYsF09W21DGa6d5ZCFS3hOjjGge+gQUHdP2gDh9hw0m2I/4t AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgSwMA0GCSqGSIb3 DQEBBQUAA4GBACRaJHra+dtyb1h2k4tUa019+sPkFV1y5IPWIxRs+fKV7JQrd42W jrHPimRU8TJ/2b4aNCLXRTK2qHhbQ72+WKrH78aI2gYQK6AuDuy2WNNwPOnHg4uG vJaczITE2FsUqXr4AVOxFyJsnljXfx05zD0zHbNqg+qqtpLxFuO3McQy -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/jsse/src/test/resources/configuratorTest/userkey.pem000066400000000000000000000015671241116057200302700ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQCO2v0IWbhRlAr7857nksXRWipU8XAFhu/dI5ueuNe6itbZLXDZ qF95s7mNMrub1UP+jJOzVh054oxn43TjSxeSJk2PUrF8xBYDwnF2VICeEcZH5fjx i4/zgTeDQl2LBdPVttQxmuneWQhUt4To4xoHvoEFB3T9oA4fYcNJtiP+LQIDAQAB AoGAdOw3/gWxHtQUyXL0tIUk89zgmPWjwmJXIKBsVtTjfQL2JntSylNNEcdQL4k+ lKVRKZ7VpQrukNokIUPB/+cOOogWFKGqGW3Tmi/3UvbnKWQZB9kanupC9HqxfS2O 5vhuWT3W20/B6/0P4Nkv4V6OHr4+hsn4LYbaBO4fCuRw8eECQQDuG//QZ8IGw+oE jQ4yKzPk082EUMra2JqHO3dArkWh+bFdvTMJWKDSOP1Al4MZDmQkFgfWMYVOUaUC qSolGoMHAkEAmZbK60CNJwS1bLadSi8UhXAccoVUmRybsGHf82yCju62mO1Vgxwz CCWZ7oFL6Qzpc95icdTm2znrxEyrXeUkKwJAdyeT0Jrbwb7wsO5VmE1+XpiPVBOK MBIM4nejqb6MIg5t79bqX1b2w7y5H0Wy2SsWeeh8a3fEmfjJdpdo+8BUqQJAQT3z 3rDiBOQUKST9dajAH9q6ys7mW8/yNp+s4RuD7jFq8VVH0NTmvJw0YkMcOtgYRvb9 fHtCwXc+NnmXBeCzVwJADEv5Y58PeUBZFSlGNNsWoFIdTN7J3yVpAtFFwgnG2xiA DZfEG6OzgkQ87eikamg4SspAvorUgKf3IgV9C4dgPg== -----END RSA PRIVATE KEY----- JGlobus-JGlobus-Release-2.1.0/myproxy/000077500000000000000000000000001241116057200175265ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/pom.xml000066400000000000000000000013461241116057200210470ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 myproxy myproxy ${project.groupId} gss ${project.version} junit junit test JGlobus-JGlobus-Release-2.1.0/myproxy/src/000077500000000000000000000000001241116057200203155ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/000077500000000000000000000000001241116057200212415ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/000077500000000000000000000000001241116057200221625ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/000077500000000000000000000000001241116057200227515ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/000077500000000000000000000000001241116057200242445ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/000077500000000000000000000000001241116057200257735ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/ChangePasswordParams.java000066400000000000000000000035031241116057200327130ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; /** * Holds the parameters for the changePassword operation. */ public class ChangePasswordParams extends Params { private String newPassphrase; private String credentialName; public ChangePasswordParams() { super(MyProxy.CHANGE_PASSWORD); } public void setNewPassphrase(String newPassphrase) { checkPassphrase(newPassphrase); this.newPassphrase = newPassphrase; } public String getNewPassphrase() { return this.newPassphrase; } public void setCredentialName(String credentialName) { this.credentialName = credentialName; } public String getCredentialName() { return this.credentialName; } protected String makeRequest(boolean includePassword) { StringBuffer buf = new StringBuffer(); buf.append(super.makeRequest(includePassword)); buf.append(NEW_PHRASE); if (includePassword) { buf.append(newPassphrase); } else { for (int i=0;iinfo operation. */ public class CredentialInfo { private String owner; private long startTime; private long endTime; private String name; private String description; // optional private String renewers; // optional private String retrievers; // optional public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getRetrievers() { return this.retrievers; } public void setRetrievers(String retrievers) { this.retrievers = retrievers; } public String getRenewers() { return this.renewers; } public void setRenewers(String renewers) { this.renewers = renewers; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getOwner() { return this.owner; } public void setOwner(String owner) { this.owner = owner; } public long getStartTime() { return this.startTime; } public void setStartTime(long time) { this.startTime = time; } public long getEndTime() { return this.endTime; } public void setEndTime(long time) { this.endTime = time; } public Date getEndTimeAsDate() { return new Date(this.endTime); } public Date getStartTimeAsDate() { return new Date(this.startTime); } public String toString() { StringBuffer buf = new StringBuffer(); if (this.name != null) { buf.append(this.name).append(" "); } buf.append(owner).append(" "); buf.append(String.valueOf(startTime)).append(" "); buf.append(String.valueOf(endTime)); if (this.description != null) { buf.append(' '); buf.append(this.description); } if (this.renewers != null) { buf.append(' '); buf.append(this.renewers); } if (this.retrievers != null) { buf.append(' '); buf.append(this.retrievers); } return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/DestroyParams.java000066400000000000000000000026371241116057200314430ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; /** * Holds the parameters for the destroy operation. */ public class DestroyParams extends Params { private String credentialName; public DestroyParams() { super(MyProxy.DESTROY_PROXY); } public DestroyParams(String username, String passphrase) { super(MyProxy.DESTROY_PROXY, username, passphrase); } public void setCredentialName(String credentialName) { this.credentialName = credentialName; } public String getCredentialName() { return this.credentialName; } protected String makeRequest(boolean includePassword) { StringBuffer buf = new StringBuffer(); buf.append(super.makeRequest(includePassword)); add(buf, CRED_NAME, credentialName); return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/GetParams.java000066400000000000000000000054151241116057200305260ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; import org.ietf.jgss.GSSCredential; import java.util.List; import java.util.Iterator; /** * Holds the parameters for the get operation. */ public class GetParams extends Params { private boolean wantTrustroots = false; private String credentialName; private GSSCredential authzcreds; private List voname; private List vomses; public GetParams() { super(MyProxy.GET_PROXY); } public GetParams(String username, String passphrase) { super(MyProxy.GET_PROXY, username, passphrase); } public void setCredentialName(String credentialName) { this.credentialName = credentialName; } public String getCredentialName() { return this.credentialName; } public void setWantTrustroots(boolean wantTrustroots) { this.wantTrustroots = wantTrustroots; } public boolean getWantTrustroots() { return this.wantTrustroots; } public void setVoname(List voname) { this.voname = voname; } public List getVoname() { return this.voname; } public void setVomses(List vomses) { this.vomses = vomses; } public List getVomses() { return this.vomses; } /** * Set credentials for renewal authorization. * @param creds * The credentials to renew. */ public void setAuthzCreds(GSSCredential creds) { this.authzcreds = creds; } public GSSCredential getAuthzCreds() { return this.authzcreds; } protected String makeRequest(boolean includePassword) { StringBuffer buf = new StringBuffer(); buf.append(super.makeRequest(includePassword)); add(buf, CRED_NAME, credentialName); add(buf, VONAME, this.voname); add(buf, VOMSES, this.vomses); if (this.wantTrustroots == true) { add(buf, TRUSTROOTS, "1"); } return buf.toString(); } private void add(StringBuffer buf, String prefix, List values) { if (values == null) { return; } for (Iterator itr = values.iterator(); itr.hasNext(); ) { String value = (String)itr.next(); add(buf, prefix, value); } } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/GetTrustrootsParams.java000066400000000000000000000020431241116057200326510ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; /** * Holds the parameters for the get-trustroots operation. */ public class GetTrustrootsParams extends Params { public GetTrustrootsParams() { super(MyProxy.GET_TRUSTROOTS); } protected String makeRequest(boolean includePassword) { StringBuffer buf = new StringBuffer(); buf.append(super.makeRequest(includePassword)); add(buf, TRUSTROOTS, "1"); return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/InfoParams.java000066400000000000000000000014641241116057200307020ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; /** * Holds the parameters for the info operation. */ public class InfoParams extends Params { public InfoParams() { super(MyProxy.INFO_PROXY); } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/InitParams.java000066400000000000000000000050251241116057200307070ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; /** * Holds the parameters for the put operation. */ public class InitParams extends Params { private String retriever; private String renewer; private String credentialName; private String credentialDescription; private String trusted_retriever; public InitParams() { super(MyProxy.PUT_PROXY); } public void setCredentialName(String credentialName) { this.credentialName = credentialName; } public String getCredentialName() { return this.credentialName; } public void setCredentialDescription(String description) { this.credentialDescription = description; } public String getCredentialDescription() { return this.credentialDescription; } public void setRetriever(String retriever) { this.retriever = retriever; } public String getRetriever() { return this.retriever; } public void setRenewer(String renewer) { this.renewer = renewer; } public String getRenewer() { return this.renewer; } public void setTrustedRetriever(String trusted_retriever) { this.trusted_retriever = trusted_retriever; } public String getTrustedRetriever() { return this.trusted_retriever; } /** * If the passpharse is not set returns * an empty string. */ public String getPassphrase() { String pwd = super.getPassphrase(); return (pwd == null) ? "" : pwd; } protected String makeRequest(boolean includePassword) { StringBuffer buf = new StringBuffer(); buf.append(super.makeRequest(includePassword)); add(buf, RETRIEVER, retriever); add(buf, CRED_RETRIEVER_TRUSTED, trusted_retriever); add(buf, RENEWER, renewer); add(buf, CRED_NAME, credentialName); add(buf, CRED_DESC, credentialDescription); return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/MyProxy.java000066400000000000000000001570671241116057200303050ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; import java.nio.charset.Charset; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.Writer; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.IOException; import java.io.EOFException; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.DataOutputStream; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.net.Socket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.security.KeyPair; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.cert.X509Certificate; import java.security.MessageDigest; import java.security.GeneralSecurityException; import java.security.Signature; import javax.security.auth.x500.X500Principal; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.bouncycastle.asn1.x509.X509Name; import org.globus.common.CoGProperties; import org.bouncycastle.util.encoders.Base64; import org.globus.gsi.X509Credential; import org.globus.gsi.GSIConstants; import org.globus.gsi.util.CertificateIOUtil; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.OpenSSLKey; import org.globus.gsi.gssapi.net.GssSocket; import org.globus.gsi.gssapi.net.GssSocketFactory; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.auth.IdentityAuthorization; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.globus.gsi.gssapi.GSSConstants; import org.globus.gsi.bc.BouncyCastleCertProcessingFactory; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class provides an API for communicating with MyProxy servers. * It provides main functions for retrieving, removing and * storing credentials on MyProxy server. It also provides functions * for getting credential information and changing passwords. *

    * More information about MyProxy is available on the * MyProxy Home Page. *

    * * @version 2.0 */ public class MyProxy { static Log logger = LogFactory.getLog(MyProxy.class.getName()); public final static String version = "2.0"; public static final int MIN_PASSWORD_LENGTH = MyProxyConstants.MIN_PASSWORD_LENGTH; public static final String MYPROXY_PROTOCOL_VERSION = MyProxyConstants.MYPROXY_PROTOCOL_VERSION; private static final String RESPONSE = "RESPONSE="; private static final String ERROR = "ERROR="; private static final String AUTHZ_DATA = "AUTHORIZATION_DATA="; private static final String CRED = "CRED_"; private static final String OWNER = "OWNER="; private static final String START_TIME = "START_TIME="; private static final String END_TIME = "END_TIME="; private static final String DESC = "DESC="; private static final String RETRIEVER = "RETRIEVER="; private static final String RENEWER = "RENEWER="; private static final String TRUSTROOTS = "TRUSTED_CERTS="; private static final String CRED_START_TIME = CRED + START_TIME; private static final String CRED_END_TIME = CRED + END_TIME; private static final String CRED_OWNER = CRED + OWNER; private static final String CRED_DESC = CRED + DESC; private static final String CRED_RETRIEVER = CRED + RETRIEVER; private static final String CRED_RENEWER = CRED + RENEWER; private static final String CRED_NAME = CRED + "NAME="; /** The default MyProxy server port (7512). */ public static final int DEFAULT_PORT = 7512; /** The default key size (2048 bits). */ public static final int DEFAULT_KEYBITS = 2048; /** The integer command number for the MyProxy 'Get' command (0). */ public static final int GET_PROXY = 0; /** The integer command number for the MyProxy 'Put' command (1). */ public static final int PUT_PROXY = 1; /** The integer command number for the MyProxy 'Info' command (2). */ public static final int INFO_PROXY = 2; /** The integer command number for the MyProxy 'Destroy' command (3). */ public static final int DESTROY_PROXY = 3; /** The integer command number for the MyProxy Password Change * command (4). */ public static final int CHANGE_PASSWORD = 4; /** The integer command number for the MyProxy 'Store' command (5). */ public static final int STORE_CREDENTIAL = 5; /** The integer command number for the MyProxy 'Retrieve' command (6). */ public static final int RETRIEVE_CREDENTIAL = 6; /** The integer command number for the MyProxy 'Get Trustroots' command (7). */ public static final int GET_TRUSTROOTS = 7; /** The hostname(s) of the target MyProxy server(s). Multiple host names can be specified comma delimited with each hostname optionally followed by a ':' and port number. The client will communicate with the first server it has a successful network connection with. */ protected String host; /** The port of the target MyProxy server (default 7512). */ protected int port = DEFAULT_PORT; /** The authorization policy in effect for the target MyProxy server. */ protected Authorization authorization; /** The GSSContext for communication with the MyProxy server. */ protected GSSContext context; /** Trustroot information and path constant. */ protected String[] trustrootFilenames; protected String[] trustrootData; private final static String TRUSTED_CERT_PATH = "/.globus/certificates"; /** * Initialize the MyProxy client object with the default * authorization policy. */ public MyProxy() { setAuthorization(new MyProxyServerAuthorization()); } /** * Prepare to connect to the MyProxy server at the specified * host and port using the default authorization policy. * * @param host * The hostname(s) of the MyProxy server(s) with optional port * info. Multiple hostnames can be specified in a comma separated * list with each hostname optionally followed by a ':' and port * number. The client will communicate with the first server it has * a successful network connection with. * @param port * The port number of the MyProxy server to use if one is not * specified as part of the host string. */ public MyProxy(String host, int port) { setHost(host); setPort(port); setAuthorization(new MyProxyServerAuthorization()); } /** * Set MyProxy server hostname. * @param host * The hostname(s) of the MyProxy server(s). Multiple host names * are comma delimited with each hostname optionally followed by a * ':' and port number. The client will communicate with the first * server it has a successful network connection with. */ public void setHost(String host) { this.host = host; } /** * Get MyProxy server hostname. * @return The hostname of the MyProxy server. */ public String getHost() { return host; } /** * Set MyProxy server port. * @param port * The port number of the MyProxy server to use if one is not * specified as part of the host string. Defaults to * MyProxy.DEFAULT_PORT. */ public void setPort(int port) { this.port = port; } /** * Get MyProxy server port. * @return The port number of the MyProxy server. */ public int getPort() { return port; } /** * Set MyProxy server authorization mechanism. * @param authorization * The authorization mechanism for the MyProxy server. */ public void setAuthorization(Authorization authorization) { this.authorization = authorization; } /** * Get MyProxy server authorization mechanism. * @return The authorization mechanism for the MyProxy server. */ public Authorization getAuthorization() { return this.authorization; } private GssSocket getSocket(GSSCredential credential) throws IOException, GSSException { GSSManager manager = ExtendedGSSManager.getInstance(); this.context = manager.createContext(null, GSSConstants.MECH_OID, credential, GSSContext.DEFAULT_LIFETIME); // no delegation this.context.requestCredDeleg(false); // Request confidentiality this.context.requestConf(true); IOException exception = null; Socket socket = null; String goodAddr = ""; int hostIdx = 0; String hosts[] = host.split(","); int socketTimeout = CoGProperties.getDefault().getSocketTimeout(); int currentPort = port; search: while (hostIdx < hosts.length) { String hostPort[] = hosts[hostIdx].split(":"); hosts[hostIdx] = hostPort[0]; if (hostPort.length > 1 && hostPort[1] != null) // port number specified port = Integer.parseInt(hostPort[1].trim()); else port = currentPort; InetAddress addrs[] = null; try { addrs = InetAddress.getAllByName(hosts[hostIdx]); } catch (UnknownHostException e) { if (logger.isDebugEnabled()) { logger.debug("getSocket(): Skipping unknown host " + hosts[hostIdx]); } exception = e; } for (int addrIdx = 0; addrs != null && addrIdx < addrs.length; addrIdx++) { exception = null; try { if (logger.isDebugEnabled()) { logger.debug("getSocket(): Trying " + addrs[addrIdx].toString()); } socket = new Socket(); socket.connect( new InetSocketAddress(addrs[addrIdx],port), socketTimeout); goodAddr = addrs[addrIdx].toString(); if (logger.isDebugEnabled()) { logger.debug(" Succeeded."); } break search; } catch (IOException e) { exception = e; if (logger.isDebugEnabled()) { logger.debug(" Failed."); } } } hostIdx += 1; } if (exception != null) { if (logger.isDebugEnabled()) { logger.debug("getSocket(): " + "Unable to connect to a MyProxy host"); } throw exception; } setHost(hosts[hostIdx]); // host we have successfully connected to GssSocketFactory gssFactory = GssSocketFactory.getDefault(); GssSocket gssSocket = (GssSocket)gssFactory.createSocket(socket, hosts[hostIdx], port, this.context); if (logger.isDebugEnabled()) { logger.debug("getSocket(): Connected to " + goodAddr); } gssSocket.setAuthorization(this.authorization); return gssSocket; } /** * Delegate credentials to a MyProxy server. * * @param credential * The GSI credentials to use. * @param username * The username to store the credentials under. * @param passphrase * The passphrase to use to encrypt the stored * credentials. * @param lifetime * The maximum lifetime of credentials delegated by the server * (in seconds). * @exception MyProxyException * If an error occurred during the operation. */ public void put(GSSCredential credential, String username, String passphrase, int lifetime) throws MyProxyException { InitParams request = new InitParams(); request.setUserName(username); request.setPassphrase(passphrase); request.setLifetime(lifetime); put(credential, request); } /** * Delegate credentials to a MyProxy server. * * @param credential * The GSI credentials to use. * @param params * The parameters for the put operation. * @exception MyProxyException * If an error occurred during the operation. */ public void put(GSSCredential credential, InitParams params) throws MyProxyException { if (credential == null) { throw new IllegalArgumentException("credential == null"); } if (params == null) { throw new IllegalArgumentException("params == null"); } if (!(credential instanceof GlobusGSSCredentialImpl)) { throw new IllegalArgumentException("wrong type of credentials"); } String msg = params.makeRequest(); Socket gsiSocket = null; OutputStream out = null; InputStream in = null; try { gsiSocket = getSocket(credential); out = gsiSocket.getOutputStream(); in = gsiSocket.getInputStream(); if (!((GssSocket)gsiSocket).getContext().getConfState()) throw new Exception("Confidentiality requested but not available"); // send message out.write(msg.getBytes()); out.flush(); if (logger.isDebugEnabled()) { logger.debug("Req sent:" + params); } handleReply(in); BouncyCastleCertProcessingFactory certFactory = BouncyCastleCertProcessingFactory.getDefault(); GlobusGSSCredentialImpl pkiCred = (GlobusGSSCredentialImpl)credential; X509Certificate [] certs = pkiCred.getCertificateChain(); // read in the cert request from socket and // generate a certificate to be sent back to the server X509Certificate cert = certFactory.createCertificate(in, certs[0], pkiCred.getPrivateKey(), -1, BouncyCastleCertProcessingFactory.decideProxyType(certs[0], GSIConstants.DelegationType.FULL)); // write the new cert we've generated to the socket to send it back // to the server // must put everything into one message ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048); buffer.write( (byte)(certs.length+1) ); // write signed ceritifcate buffer.write(cert.getEncoded()); for (int i=0;i 0) { int i = 1; Iterator iter = credMap.entrySet().iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); creds[i++] = (CredentialInfo)entry.getValue(); } } return creds; } catch(Exception e) { throw new MyProxyException("MyProxy info failed.", e); } finally { // close socket close(out, in, gsiSocket); } } private boolean matches(String line, int pos, String arg) { return line.regionMatches(true, pos - arg.length(), arg, 0, arg.length()); } private String getCredName(String line, int pos, String arg) { return line.substring(CRED.length(), pos-arg.length()); } private CredentialInfo getCredentialInfo(Map map, String name) { CredentialInfo info = (CredentialInfo)map.get(name); if (info == null) { info = new CredentialInfo(); info.setName(name); map.put(name, info); } return info; } /** * Retrieves delegated credentials from MyProxy server Anonymously * (without local credentials) * * Notes: Performs simple verification of private/public keys of * the delegated credential. Should be improved later. * And only checks for RSA keys. * * @param username * The username of the credentials to retrieve. * @param passphrase * The passphrase of the credentials to retrieve. * @param lifetime * The requested lifetime of the retrieved credential (in seconds). * @return GSSCredential * The retrieved delegated credentials. * @exception MyProxyException * If an error occurred during the operation. */ public GSSCredential get(String username, String passphrase, int lifetime) throws MyProxyException { return get(null, username, passphrase, lifetime); } /** * Retrieves delegated credentials from the MyProxy server. * * Notes: Performs simple verification of private/public keys of * the delegated credential. Should be improved later. * And only checks for RSA keys. * * @param credential * The local GSI credentials to use for authentication. * Can be set to null if no local credentials. * @param username * The username of the credentials to retrieve. * @param passphrase * The passphrase of the credentials to retrieve. * @param lifetime * The requested lifetime of the retrieved credential (in seconds). * @return GSSCredential * The retrieved delegated credentials. * @exception MyProxyException * If an error occurred during the operation. */ public GSSCredential get(GSSCredential credential, String username, String passphrase, int lifetime) throws MyProxyException { GetParams request = new GetParams(); request.setUserName(username); request.setPassphrase(passphrase); request.setLifetime(lifetime); return get(credential, request); } /** * Retrieves delegated credentials from the MyProxy server. * * @param credential * The local GSI credentials to use for authentication. * Can be set to null if no local credentials. * @param params * The parameters for the get operation. * @return GSSCredential * The retrieved delegated credentials. * @exception MyProxyException * If an error occurred during the operation. */ public GSSCredential get(GSSCredential credential, GetParams params) throws MyProxyException { if (params == null) { throw new IllegalArgumentException("params == null"); } if (credential == null) { try { credential = getAnonymousCredential(); } catch (GSSException e) { throw new MyProxyException("Failed to create anonymous credentials", e); } } String msg = params.makeRequest(); Socket gsiSocket = null; OutputStream out = null; InputStream in = null; try { gsiSocket = getSocket(credential); if (credential.getName().isAnonymous()) { this.context.requestAnonymity(true); } out = gsiSocket.getOutputStream(); in = gsiSocket.getInputStream(); if (!((GssSocket)gsiSocket).getContext().getConfState()) throw new Exception("Confidentiality requested but not available"); // send message out.write(msg.getBytes()); out.flush(); if (logger.isDebugEnabled()) { logger.debug("Req sent:" + params); } // may require authz handshake handleReply(in, out, params.getAuthzCreds(), params.getWantTrustroots()); // start delegation - generate key pair KeyPair keyPair = CertificateUtil.generateKeyPair("RSA", DEFAULT_KEYBITS); // According to the MyProxy protocol, the MyProxy server // will ignore the subject in the client's certificate // signing request (CSR). However, in some cases it is // helpful to control the CSR subject (for example, when // the MyProxy server is using a CA back-end that can only // issue certificates with subjects matching the request). // So we construct the CSR subject using the given MyProxy // username (if possible). String CSRsubjectString = params.getUserName(); CSRsubjectString = CSRsubjectString.trim(); if (CSRsubjectString.contains("CN=") || CSRsubjectString.contains("cn=")) { // If the MyProxy username is a DN, use it. if (CSRsubjectString.charAt(0) == '/') { // "good enough" conversion of OpenSSL DN strings CSRsubjectString = CSRsubjectString.substring(1); CSRsubjectString = CSRsubjectString.replace('/', ','); } } else { CSRsubjectString = "CN="+CSRsubjectString; } X509Name CSRsubjectName; try { CSRsubjectName = new X509Name(CSRsubjectString); } catch (Exception e) { // If our X509Name construction fails for any reason, // just use a default value (as in the past). CSRsubjectName = new X509Name("CN=ignore"); } if (logger.isDebugEnabled()) { logger.debug("CSR subject: " + CSRsubjectName.toString()); } BouncyCastleCertProcessingFactory certFactory = BouncyCastleCertProcessingFactory.getDefault(); byte [] req = null; req = certFactory.createCertificateRequest(CSRsubjectName, "SHA1WithRSAEncryption", keyPair); // send the request to server out.write(req); out.flush(); // read the number of certificates int size = in.read(); if (logger.isDebugEnabled()) { logger.debug("Reading " + size + " certs"); } X509Certificate [] chain = new X509Certificate[size]; for (int i=0;i -1; i--) { newSubject.append("/"); newSubject.append(subjArr[i]); } String subject = newSubject.toString(); File tmpDir = new File(getTrustRootPath() + "-" + System.currentTimeMillis()); if (tmpDir.mkdir() == true) { String hash = opensslHash(acceptedIssuers[idx]); String filename = tmpDir.getPath() + tmpDir.separator + hash + ".0"; FileOutputStream os = new FileOutputStream(new File(filename)); CertificateIOUtil.writeCertificate(os, acceptedIssuers[idx]); os.close(); if (logger.isDebugEnabled()) { logger.debug("wrote trusted certificate to " + filename); } filename = tmpDir.getPath() + tmpDir.separator + hash + ".signing_policy"; os = new FileOutputStream(new File(filename)); Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8")); wr.write("access_id_CA X509 '"); wr.write(subject); wr.write("'\npos_rights globus CA:sign\ncond_subjects globus \"*\"\n"); wr.flush(); wr.close(); os.close(); if (logger.isDebugEnabled()) { logger.debug("wrote trusted certificate policy to " + filename); } // success. commit the bootstrapped directory. if (tmpDir.renameTo(x509Dir) == true) { if (logger.isDebugEnabled()) { logger.debug("renamed " + tmpDir.getPath() + " to " + x509Dir.getPath()); } } else { throw new MyProxyException("Unable to rename " + tmpDir.getPath() + " to " + x509Dir.getPath()); } } else { throw new MyProxyException("Cannot create temporary directory: " + tmpDir.getName()); } } } } catch(Exception e) { throw new MyProxyException("MyProxy bootstrapTrust failed.", e); } } private static String readLine(InputStream is) throws IOException { StringBuffer sb = new StringBuffer(); for (int c = is.read(); c > 0 && c != '\n'; c = is.read()) { sb.append((char) c); } if (sb.length() > 0) { if (logger.isDebugEnabled()) { logger.debug("Received line: " + sb); } return new String(sb); } return null; } private InputStream handleReply(InputStream in) throws IOException, MyProxyException { return handleReply(in, null, null, false); } private InputStream handleReply(InputStream in, OutputStream out, GSSCredential authzcreds, boolean wantTrustroots) throws IOException, MyProxyException { String tmp = null; /* there was something weird here with the received protocol version sometimes. it contains an extra <32 byte. fixed it by using endsWith. now i read extra byte at the end of each message. */ // protocol version tmp = readLine(in); if (tmp == null) { throw new EOFException(); } if (!tmp.endsWith(MyProxyConstants.VERSION)) { throw new MyProxyException("Protocol version mismatch: " + tmp); } // response tmp = readLine(in); if (tmp == null) { throw new EOFException(); } if (!tmp.startsWith(RESPONSE)) { throw new MyProxyException("Invalid reply: no response message"); } boolean error = tmp.charAt(RESPONSE.length()) == '1'; boolean authzchallenge = tmp.charAt(RESPONSE.length()) == '2'; if (error) { StringBuffer errorStr = new StringBuffer(); while( (tmp = readLine(in)) != null ) { if (tmp.startsWith(ERROR)) { if (errorStr.length() > 0) errorStr.append(' '); errorStr.append(tmp.substring(ERROR.length())); } } if (errorStr.length() == 0) { errorStr.append("unspecified server error"); } throw new MyProxyException(errorStr.toString()); } if (authzchallenge) { if (authzcreds == null) { throw new MyProxyException("Unable to respond to server's authentication challenge. No credentials for renewal."); } if (out == null) { throw new MyProxyException("Internal error. Authz challenge but no OutputStream."); } String[] authzdata = null; while( (tmp = readLine(in)) != null ) { if (tmp.startsWith(AUTHZ_DATA)) { int pos = tmp.indexOf(':', AUTHZ_DATA.length()+1); if (pos != -1) { authzdata = new String[2]; authzdata[0] = tmp.substring(AUTHZ_DATA.length(), pos).trim(); authzdata[1] = tmp.substring(pos+1).trim(); } if (authzdata == null) { throw new MyProxyException("Unable to parse authorization challenge from server."); } if (authzdata[0].equals("X509_certificate")) { GlobusGSSCredentialImpl pkiCred = (GlobusGSSCredentialImpl)authzcreds; try { Signature sig = Signature.getInstance("SHA1withRSA"); sig.initSign(pkiCred.getPrivateKey()); sig.update(authzdata[1].getBytes()); byte[] sigbytes = sig.sign(); X509Certificate [] certs = pkiCred.getCertificateChain(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048); buffer.write(2); // AUTHORIZETYPE_CERT buffer.write(0); buffer.write(0); buffer.write(0); // pad DataOutputStream dos = new DataOutputStream(buffer); dos.writeInt(sigbytes.length); dos.flush(); buffer.write(sigbytes); buffer.write((byte)certs.length); for (int i=0; i 0) in.read(b); ByteArrayInputStream inn = new ByteArrayInputStream(b); return inn; } private static void close(OutputStream out, InputStream in, Socket sock) { try { if (out != null) out.close(); if (in != null) in.close(); if (sock != null) sock.close(); } catch(IOException ee) {} } private static Authorization getAuthorization(String subjectDN) { if (subjectDN == null) { return new MyProxyServerAuthorization(); } else { return new IdentityAuthorization(subjectDN); } } private GSSCredential getAnonymousCredential() throws GSSException { GSSManager manager = ExtendedGSSManager.getInstance(); GSSName anonName = manager.createName((String)null, null); return manager.createCredential(anonName, GSSCredential.INDEFINITE_LIFETIME, (Oid)null, GSSCredential.INITIATE_AND_ACCEPT); } /** * Returns the trusted certificates directory location where * writeTrustRoots() will store certificates. * It first checks the X509_CERT_DIR system property. * If that property is not set, it uses * ${user.home}/.globus/certificates. * Note that, unlike CoGProperties.getCaCertLocations(), * it does not return /etc/grid-security/certificates or * ${GLOBUS_LOCATION}/share/certificates. */ public static String getTrustRootPath() { String path = System.getProperty("X509_CERT_DIR"); if (path == null) { path = System.getProperty("user.home") + TRUSTED_CERT_PATH; } return path; } /** * Writes the retrieved trust roots to the Globus trusted certificates * directory. * @return true if trust roots are written successfully, false if no * trust roots are available to be written */ public boolean writeTrustRoots() throws IOException { return writeTrustRoots(getTrustRootPath()); } /** * Writes the retrieved trust roots to a trusted certificates directory. * @param directory * path where the trust roots should be written * @return true if trust roots are written successfully, false if no * trust roots are available to be written */ public boolean writeTrustRoots(String directory) throws IOException { if (this.trustrootFilenames == null || this.trustrootData == null) { return false; } File rootDir = new File(directory); if (!rootDir.exists()) { rootDir.mkdirs(); } for (int i = 0; i < trustrootFilenames.length; i++) { FileOutputStream out = new FileOutputStream( directory + File.separator + this.trustrootFilenames[i]); out.write(this.trustrootData[i].getBytes()); out.close(); } return true; } /* the following methods are based off code to compute the subject name hash from: http://blog.piefox.com/2008/10/javaopenssl-ca-generation.html */ private static String opensslHash(X509Certificate cert) { try { return openssl_X509_NAME_hash(cert.getSubjectX500Principal()); } catch (Exception e) { throw new Error("MD5 isn't available!", e); } } /** * Generates a hex X509_NAME hash (like openssl x509 -hash -in cert.pem) * Based on openssl's crypto/x509/x509_cmp.c line 321 */ private static String openssl_X509_NAME_hash(X500Principal p) throws Exception { // This code replicates OpenSSL's hashing function // DER-encode the Principal, MD5 hash it, then extract the first 4 bytes and reverse their positions byte[] derEncodedSubject = p.getEncoded(); byte[] md5 = MessageDigest.getInstance("MD5").digest(derEncodedSubject); // Reduce the MD5 hash to a single unsigned long byte[] result = new byte[] { md5[3], md5[2], md5[1], md5[0] }; return toHex(result); } // encode binary to hex private static String toHex(final byte[] bin) { if (bin == null || bin.length == 0) return ""; char[] buffer = new char[bin.length * 2]; final char[] hex = "0123456789abcdef".toCharArray(); // i tracks input position, j tracks output position for (int i = 0, j = 0; i < bin.length; i++) { final byte b = bin[i]; buffer[j++] = hex[(b >> 4) & 0x0F]; buffer[j++] = hex[b & 0x0F]; } return new String(buffer); } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/MyProxyCLI.java000066400000000000000000001261671241116057200306320ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.IOException; import java.security.PrivateKey; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import java.util.ArrayList; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.GSIConstants; import org.globus.gsi.X509Credential; import org.globus.gsi.OpenSSLKey; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import org.globus.gsi.bc.BouncyCastleCertProcessingFactory; import org.globus.gsi.gssapi.auth.IdentityAuthorization; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.globus.util.Util; import org.globus.common.CoGProperties; import org.globus.common.Version; import org.globus.myproxy.CredentialInfo; import org.globus.myproxy.ChangePasswordParams; import org.globus.myproxy.DestroyParams; import org.globus.myproxy.InitParams; import org.globus.myproxy.GetParams; import org.globus.myproxy.GetTrustrootsParams; import org.globus.myproxy.InfoParams; import org.globus.myproxy.StoreParams; import org.gridforum.jgss.ExtendedGSSManager; import org.gridforum.jgss.ExtendedGSSCredential; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSException; /** MyProxy Command Line Client */ public class MyProxyCLI { public static final int MYPROXY_SERVER_PORT = 7512; public static final int PORTAL_LIFETIME_HOURS = 12; public static final int CRED_LIFETIME_HOURS = 168; public static final int MATCH_CN_ONLY = 0; public static final int REGULAR_EXP = 1; private static final String commonOptions = "\tCommon Options:\n" + "\t-help\n" + "\t\tDisplays usage\n" + "\t-v | -version\n" + "\t\tDisplays version\n" + "\n" + "\t-h | -host \n" + "\t\tHostname of the myproxy-server\n" + "\t-p | -port \n" + "\t\tPort of the myproxy-server\n" + "\t\t(default " + MYPROXY_SERVER_PORT + ")\n" + "\t-s | -subject \n" + "\t\tPerforms subject authorization\n" + "\t-l | -username \n" + "\t\tUsername for the delegated proxy\n" + "\t-d | -dn_as_username\n" + "\t\tUse the proxy certificate subject (DN) as the default\n" + "\t\tusername instead of the \"user.name\" system property.\n" + "\t-S | -stdin_pass\n" + "\t\tAllows passphrase from stdin.\n"; private static final String message = "\n" + "Syntax: java MyProxyCLI [common options] command [command options]\n" + " java MyProxyCLI -version\n" + " java MyProxyCLI -help\n\n" + commonOptions + "\n" + "\tCommands:\n" + "\t put - put proxy\n" + "\t store - store credentials\n" + "\t get - get proxy\n" + "\t anonget - get proxy without local credentials\n" + "\t get-trustroots - get trustroots information\n" + "\t destroy - remove proxy\n" + "\t info - credential information\n" + "\t pwd - change credential password\n\n" + "\tSpecify -help after a command name for command-specific help.\n"; private static final String destroyMessage = "\n" + "Syntax: java MyProxyCLI [common options] destroy [command options]\n\n" + commonOptions + "\n" + "\tCommand Options:\n" + "\t-help\n" + "\t\tDisplays usage\n" + "\t-k | -credname \n" + "\t\tSpecifies credential name\n"; private static final String pwdMessage = "\n" + "Syntax: java MyProxyCLI [common options] pwd [command options]\n\n" + commonOptions + "\n" + "\tCommand Options:\n" + "\t-help\n" + "\t\tDisplays usage\n" + "\t-k | -credname \n" + "\t\tSpecifies credential name\n"; private static final String infoMessage = "\n" + "Syntax: java MyProxyCLI [common options] info [command options]\n\n" + commonOptions + "\n" + "\tCommand Options:\n" + "\t-help\n" + "\t\tDisplays usage\n"; private static final String getMessage = "\n" + "Syntax: java MyProxyCLI [common options] [get|anonget] [command options]\n\n" + commonOptions + "\n" + "\tCommand Options:\n" + "\t-help\n" + "\t\tDisplays usage\n" + "\t-t | -portal_lifetime \n" + "\t\tLifetime of delegated proxy on\n" + "\t\tthe portal (default " + PORTAL_LIFETIME_HOURS + " hours)\n" + "\t-o | -out \n" + "\t\tLocation of delegated proxy\n" + "\t-T | -trustroots\n" + "\t\tManage trust roots\n" + "\t-k | -credname \n" + "\t\tSpecifies credential name\n" + "\t-a | -authorization \n" + "\t\tSpecifies path to credentials to renew\n" + "\t-m | -voms \n" + "\t\tInclude VOMS attributes\n"; private static final String putMessage = "\n" + "Syntax: java MyProxyCLI [common options] put [command options]\n\n" + commonOptions + "\n" + "\tCommand Options:\n" + "\t-help\n" + "\t\tDisplays usage\n" + "\t-cert \n" + "\t\tNon-standard location of user certificate\n" + "\t-key \n" + "\t\tNon-standard location of user key\n" + "\t-t | -portal_lifetime \n" + "\t\tLifetime of delegated proxy on\n" + "\t\tthe portal (default " + PORTAL_LIFETIME_HOURS + " hours)\n" + "\t-c | -cred_lifetime \n" + "\t\tLifetime of delegated proxy\n" + "\t\t(default 1 week - 168 hours)\n" + "\t-a | -allow_anonymous_retrievers\n" + "\t\tAllow credentials to be retrieved with just username/passphrase\n" + "\t-A | -allow_anonymous_renewers\n" + "\t\tAllow credentials to be renewed by any client (not recommended)\n" + "\t-r | -retrievable_by \n" + "\t\tAllow specified entity to retrieve credential\n" + "\t-R | -renewable_by \n" + "\t\tAllow specified entity to renew credential\n" + "\t-x | -regex_dn_match\n" + "\t\tSpecifies that the DN used by options -r and -R\n" + "\t\twill be matched as a regular expression\n " + "\t-X | -match_cn_only\n" + "\t\tSpecifies that the DN used by options -r and -R\n" + "\t\twill be matched against the Common Name (CN) of the\n" + "\t\tsubject\n" + "\t-n | -no_passphrase\n" + "\t\tDisable passphrase authentication\n" + "\t-k | -credname \n" + "\t\tSpecifies credential name\n" + "\t-K | -creddesc \n" + "\t\tSpecifies credential description\n"; private static final String storeMessage = "\n" + "Syntax: java MyProxyCLI [common options] store [command options]\n\n" + commonOptions + "\n" + "\tCommand Options:\n" + "\t-help\n" + "\t\tDisplays usage\n" + "\t-cert \n" + "\t\tNon-standard location of user certificate\n" + "\t-key \n" + "\t\tNon-standard location of user key\n" + "\t-t | -portal_lifetime \n" + "\t\tLifetime of delegated proxy on\n" + "\t\tthe portal (default " + PORTAL_LIFETIME_HOURS + " hours)\n" + "\t-a | -allow_anonymous_retrievers\n" + "\t\tAllow credentials to be retrieved with just username/passphrase\n" + "\t-A | -allow_anonymous_renewers\n" + "\t\tAllow credentials to be renewed by any client (not recommended)\n" + "\t-r | -retrievable_by \n" + "\t\tAllow specified entity to retrieve credential\n" + "\t-R | -renewable_by \n" + "\t\tAllow specified entity to renew credential\n" + "\t-x | -regex_dn_match\n" + "\t\tSpecifies that the DN used by options -r and -R\n" + "\t\twill be matched as a regular expression\n " + "\t-X | -match_cn_only\n" + "\t\tSpecifies that the DN used by options -r and -R\n" + "\t\twill be matched against the Common Name (CN) of the\n" + "\t\tsubject\n" + "\t-k | -credname \n" + "\t\tSpecifies credential name\n" + "\t-K | -creddesc \n" + "\t\tSpecifies credential description\n"; private static final String getTrustrootsMessage = "\n" + "Syntax: java MyProxyCLI [common options] get-trustroots [command options]\n\n" + commonOptions + "\n" + "\tCommand Options:\n" + "\t-help\n" + "\t\tDisplays usage\n"; private int port = MYPROXY_SERVER_PORT; private String hostname; private String username; private String subjectDN; private boolean debug = false; private boolean dnAsUsername = false; private boolean stdin = false; private boolean wantTrustroots = false; protected void parseCmdLine(String [] args) { for (int i = 0; i < args.length; i++) { if (args[i].charAt(0) != '-') { CertificateLoadUtil.init(); if (args[i].equalsIgnoreCase("get")) { doGet(args, i+1, false); } else if (args[i].equalsIgnoreCase("anonget")) { doGet(args, i+1, true); } else if (args[i].equalsIgnoreCase("get-trustroots")) { doGetTrustroots(args, i+1, true); } else if (args[i].equalsIgnoreCase("put")) { doPut(args, i+1); } else if (args[i].equalsIgnoreCase("store")) { doStore(args, i+1); } else if (args[i].equalsIgnoreCase("destroy")) { doDestroy(args, i+1); } else if (args[i].equalsIgnoreCase("info")) { doInfo(args, i+1); } else if (args[i].equalsIgnoreCase("pwd")) { doChangePassword(args, i+1); } else { error("Error: unknown command (" + args[i] +")"); } } else if (args[i].equals("-h") || args[i].equalsIgnoreCase("-host")) { ++i; if (i == args.length) { error("Error: -h requires hostname"); } else { this.hostname = args[i]; } } else if (args[i].equals("-p") || args[i].equalsIgnoreCase("-port")) { ++i; if (i == args.length) { error("Error: -p requires port number"); } else { this.port = Integer.parseInt(args[i]); } } else if (args[i].equals("-l") || args[i].equalsIgnoreCase("-username")) { ++i; if (i == args.length) { error("Error: -l requires username"); } else { this.username = args[i]; } } else if (args[i].equals("-d") || args[i].equalsIgnoreCase("-dn_as_username")) { this.dnAsUsername = true; } else if (args[i].equalsIgnoreCase("-debug")) { this.debug = true; } else if (args[i].equals("-S") || args[i].equalsIgnoreCase("-stdin_pass")) { this.stdin = true; } else if (args[i].equals("-s") || args[i].equalsIgnoreCase("-subject")) { ++i; if (i == args.length) { error("Error: -subject requires an argument"); } else { this.subjectDN = args[i]; } } else if (args[i].equals("-v") || args[i].equalsIgnoreCase("-version")) { // display version info System.out.println(Version.getVersion()); System.exit(1); } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-usage")) { System.err.println(message); System.exit(1); } else { error("Error: argument #" + i + " (" + args[i] +") : unknown"); } } error("Error: No command specified"); } private String getUsername() { if (dnAsUsername) { GSSCredential cred = getDefaultCredential(); try { return cred.getName().toString(); } catch (Exception e) { exit("Failed to get credential name: " + e.getMessage(), e); } } if (this.username == null) { return System.getProperty("user.name"); } else { return this.username; } } private void verifyCommonCmdLine() { if (this.hostname == null) { error("Error: myproxy-server hostname not specified"); } } private org.globus.myproxy.MyProxy getMyProxy() { org.globus.myproxy.MyProxy myProxy = new org.globus.myproxy.MyProxy(this.hostname, this.port); if (this.subjectDN != null) { myProxy.setAuthorization(new IdentityAuthorization(this.subjectDN)); } return myProxy; } protected void doInfo(String args[], int start) { for (int i=start;i now) { System.out.println ("\tTime left : " + Util.formatTimeSec((info[i].getEndTime() - now)/1000)); } else { System.out.println ("\tTime left : expired"); } tmp = info[i].getRetrievers(); if (tmp != null) { System.out.println ("\tRetrievers : "+tmp); } tmp = info[i].getRenewers(); if (tmp != null) { System.out.println ("\tRenewers : "+tmp); } tmp = info[i].getDescription(); if (tmp != null) { System.out.println ("\tDescription : "+tmp); } } } catch(Exception e) { exit("Error: " + e.getMessage(), e); } exit(); } protected void doDestroy(String args[], int start) { String credName = null; for (int i=start;iAuthorizationException if the authorization fails. * Otherwise, the function completes normally. * * @param context the security context. * @param host host address of the peer. * @exception AuthorizationException if the peer is * not authorized to access/use the resource. */ public void authorize(GSSContext context, String host) throws AuthorizationException { try { this.authzMyProxyService.authorize(context, host); } catch (AuthorizationException e) { this.authzHostService.authorize(context, host); } } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/MyTrustManager.java000066400000000000000000000015201241116057200315560ustar00rootroot00000000000000package org.globus.myproxy; import java.security.cert.X509Certificate; import java.security.cert.CertificateException; import javax.net.ssl.X509TrustManager; public class MyTrustManager implements X509TrustManager { private X509Certificate[] certs = null; public X509Certificate[] getAcceptedIssuers() { return this.certs; } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { throw new CertificateException( "checkClientTrusted not implemented by org.globus.myproxy.MyTrustManager"); } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { this.certs = new X509Certificate[certs.length-1]; System.arraycopy(certs, 1, this.certs, 0, certs.length-1); } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/Params.java000066400000000000000000000070021241116057200300600ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy; /** * A generic class for representing basic parameters * needed for all MyProxy operations. */ public abstract class Params implements MyProxyConstants { private int command; protected String username; protected String passphrase; /** Defaults to DEFAULT_LIFETIME (12 hours). */ protected int lifetime = DEFAULT_LIFETIME; public Params(int command) { setCommand(command); } public Params(int command, String username, String passphrase) { setCommand(command); setUserName(username); setPassphrase(passphrase); } protected void setCommand(int command) { this.command = command; } public void setUserName(String username) { this.username = username; } public String getUserName() { return this.username; } public void setPassphrase(String passphrase) { checkPassphrase(passphrase); this.passphrase = passphrase; } public String getPassphrase() { return this.passphrase; } public void setLifetime(int seconds) { this.lifetime = seconds; } public int getLifetime() { return this.lifetime; } protected void checkPassphrase(String passphrase) { if (passphrase == null) { throw new IllegalArgumentException("Password is not specified"); } if (passphrase.length() < MIN_PASSWORD_LENGTH) { throw new IllegalArgumentException("Password must be at least " + MIN_PASSWORD_LENGTH + " characters long"); } } public String makeRequest() { return makeRequest(true); } /** * Serializes the parameters into a MyProxy request. * Subclasses should overwrite this function and * append the custom parameters to the output of * this function. */ protected String makeRequest(boolean includePassword) { StringBuffer buf = new StringBuffer(); buf.append(VERSION).append(CRLF); buf.append(COMMAND).append(String.valueOf(command)).append(CRLF); buf.append(USERNAME).append(this.username).append(CRLF); String pwd = getPassphrase(); buf.append(PASSPHRASE); if (includePassword) { if (pwd != null) { buf.append(pwd); } } else { for (int i=0;pwd != null && istore operation. */ public class StoreParams extends InitParams { public StoreParams() { setCommand(MyProxy.STORE_CREDENTIAL); } } JGlobus-JGlobus-Release-2.1.0/myproxy/src/main/java/org/globus/myproxy/package.html000066400000000000000000000014101241116057200302500ustar00rootroot00000000000000 org.globus.myproxy package This package provides a MyProxy client API. It is fully compatible with the C implementation of MyProxy. It allows for uploading X.509 credentials to a MyProxy server, retrieving the stored credentials from the server, and removing the stored credentials.

    Package Specification

    Related Documentation

    For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/myproxy/src/test/000077500000000000000000000000001241116057200212745ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/test/java/000077500000000000000000000000001241116057200222155ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/test/java/org/000077500000000000000000000000001241116057200230045ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/test/java/org/globus/000077500000000000000000000000001241116057200242775ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/test/java/org/globus/myproxy/000077500000000000000000000000001241116057200260265ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/test/java/org/globus/myproxy/test/000077500000000000000000000000001241116057200270055ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/myproxy/src/test/java/org/globus/myproxy/test/MyProxyTest.java000066400000000000000000000205011241116057200321350ustar00rootroot00000000000000/* * Copyright 1999-2006 University of Chicago * * 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 org.globus.myproxy.test; import org.globus.myproxy.MyProxy; import org.globus.myproxy.MyProxyException; import org.globus.myproxy.CredentialInfo; import org.globus.myproxy.GetParams; import org.globus.myproxy.ChangePasswordParams; import org.globus.myproxy.InfoParams; import org.globus.myproxy.InitParams; import org.globus.myproxy.StoreParams; import org.globus.gsi.gssapi.auth.IdentityAuthorization; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import org.globus.gsi.GlobusCredential; import org.globus.util.TestUtil; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSManager; public class MyProxyTest extends TestCase { private static final String CONFIG = "org/globus/myproxy/test/test.properties"; private static final String username = "testusername"; private static final String password = "123456"; private static final int lifetime = 2 * 3600; private MyProxy myProxy; private GSSCredential cred; private static TestUtil util; static { try { util = new TestUtil(CONFIG); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public MyProxyTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(MyProxyTest.class); } public void setUp() throws Exception { myProxy = new MyProxy(util.get("myproxy.host"), util.getAsInt("myproxy.port")); GSSManager manager = ExtendedGSSManager.getInstance(); cred = manager.createCredential(GSSCredential.INITIATE_ONLY); String subjectDN = util.get("myproxy.subject"); if (subjectDN != null) { myProxy.setAuthorization(new IdentityAuthorization(subjectDN)); } } public void testPutGet1() throws Exception { myProxy.put(cred, username, password, lifetime); try { myProxy.get(cred, username, "ascbdef", lifetime); fail("Did not throw exception as expected"); } catch (MyProxyException e) { } } // public void testPutGet2() throws Exception { // myProxy.put(cred, // username, // password, // lifetime); // // GSSCredential mCred = myProxy.get(cred, // username, // password, // lifetime); // assertTrue(mCred != null); // GlobusCredential gCred = // ((GlobusGSSCredentialImpl)mCred).getGlobusCredential(); // assertTrue(gCred != null); // gCred.verify(); // } public void testDestroy() throws Exception { myProxy.put(cred, username, password, lifetime); myProxy.destroy(cred, username, password); try { myProxy.get(cred, username, password, lifetime); fail("Did not fail as expected"); } catch (MyProxyException e) { } } public void testInfo() throws Exception { myProxy.put(cred, username, password, lifetime); CredentialInfo info = myProxy.info(cred, username, password); assertTrue(info != null); assertEquals(cred.getName().toString(), info.getOwner()); long diff = ((info.getEndTime() - info.getStartTime())/1000) - cred.getRemainingLifetime(); // 360 - 5 min diff in delegation plus 1 min for padding assertTrue(diff > 0 && diff < 360); } public void testInfo2() throws Exception { String credName1 = "foo"; String credDesc1 = "foo credential"; String credRetriever = "foo retriever"; String credName2 = "bar"; String credDesc2 = "bar credential"; String credRenewer = "bar renewer"; InitParams params1 = new InitParams(); params1.setUserName(username); params1.setPassphrase(password); params1.setLifetime(lifetime); params1.setCredentialName(credName1); params1.setCredentialDescription(credDesc1); params1.setRetriever(credRetriever); InitParams params2 = new InitParams(); params2.setUserName(username); params2.setPassphrase(password); params2.setLifetime(lifetime); params2.setCredentialName(credName2); params2.setCredentialDescription(credDesc2); params2.setRenewer(credRenewer); myProxy.put(cred, params1); myProxy.put(cred, params2); InfoParams infoParams = new InfoParams(); infoParams.setUserName(username); infoParams.setPassphrase(password); CredentialInfo info[] = myProxy.info(cred, infoParams); assertTrue(info != null); assertTrue(info.length > 0); boolean f1 = false; boolean f2 = false; for (int i=0;i 4.0.0 org.jglobus parent 2.1.0 test-utils ssl-proxies container-test-utils jsse gss gram gridftp ssl-proxies-tomcat io myproxy axis JGlobus pom Java implementation of the Grid Security Infrastructure (GSI), developed by the Globus project. https://github.com/jglobus/JGlobus Apache 2 http://www.apache.org/licenses/LICENSE-2.0.txt repo bbockelm Brian Bockelman bockelman+maven@gmail.com UTF-8 Github https://github.com/jglobus/JGlobus/issues scm:git:git@github.com:jglobus/JGlobus.git scm:git:git@github.com:jglobus/JGlobus.git scm:git:git@github.com:jglobus/JGlobus.git JGlobus-Release-2.1.0 org.sonatype.oss oss-parent 7 org.apache.maven.plugins maven-compiler-plugin 1.5 1.5 org.apache.maven.plugins maven-source-plugin 2.3 jar org.apache.maven.plugins maven-surefire-plugin 2.17 false true org.apache.maven.plugins maven-release-plugin 2.5 axis axis 1.4 axis axis-jaxrpc 1.4 ${project.groupId} gss ${project.version} commons-httpclient commons-httpclient 3.1 org.apache.httpcomponents httpclient 4.0.1 javax.servlet servlet-api 2.5 commons-logging commons-logging 1.1.1 compile log4j log4j 1.2.14 compile org.bouncycastle bcprov-jdk15on 1.50 commons-io commons-io 1.4 commons-codec commons-codec 1.4 junit junit 4.8.1 JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/000077500000000000000000000000001241116057200215545ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/features/000077500000000000000000000000001241116057200233725ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/features/tomcat.feature000066400000000000000000000014151241116057200262370ustar00rootroot00000000000000Feature: Run Tomcat with proxy certificate support When Tomcat is running with ssl proxy certificate support, a valid proxy certificate should be able to connect successfully, while an invalid cert should be rejected. Scenario: Valid Client Certificate Given Tomcat is configured with ssl proxy support enabled And Tomcat is running with a valid certificate When A client presents a valid certificate Then The client can successfully connect to the server And The server shuts down Scenario: Invalid Client Certificate Given Tomcat is configured with ssl proxy support enabled And Tomcat is running with an valid certificate When A client presents a invalid certificate Then The client can successfully connect to the server And The server shuts downJGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/pom.xml000066400000000000000000000066211241116057200230760ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 ssl-proxies-tomcat SSL and proxy certificate support for Tomcat tomcat7 true org.apache.tomcat tomcat-catalina 7.0.32 org.apache.tomcat tomcat-coyote 7.0.32 tomcat6 org.apache.maven.plugins maven-patch-plugin 1.1.1 jglobus-tomcat6.patch 5 patch process-sources apply org.apache.tomcat catalina 6.0.24 org.apache.tomcat coyote 6.0.24 tomcat5 org.apache.maven.plugins maven-patch-plugin 1.1.1 jglobus-tomcat5.patch 5 patch process-sources apply tomcat catalina 5.5.23 tomcat tomcat-coyote 5.5.23 ${project.groupId} jsse ${project.version} ${project.groupId} container-test-utils ${project.version} test ${project.groupId} test-utils ${project.version} test junit junit test JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/000077500000000000000000000000001241116057200223435ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/000077500000000000000000000000001241116057200232675ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/000077500000000000000000000000001241116057200242105ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/000077500000000000000000000000001241116057200247775ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/globus/000077500000000000000000000000001241116057200262725ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/globus/gsi/000077500000000000000000000000001241116057200270545ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/000077500000000000000000000000001241116057200303435ustar00rootroot00000000000000GlobusSSLImplementation.java000066400000000000000000000010501241116057200356460ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcatpackage org.globus.gsi.tomcat; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.ServerSocketFactory; import org.apache.tomcat.util.net.jsse.JSSEImplementation; public class GlobusSSLImplementation extends JSSEImplementation { public GlobusSSLImplementation() throws ClassNotFoundException { } public String getImplementationName() { return "GlobusSSLImplementation"; } public ServerSocketFactory getServerSocketFactory(AbstractEndpoint endpoint) { return new GlobusSSLSocketFactory(endpoint); } } GlobusSSLInputStream.java000066400000000000000000000024461241116057200351460ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcatpackage org.globus.gsi.tomcat; import java.io.IOException; import java.io.InputStream; import javax.net.ssl.SSLSocket; public class GlobusSSLInputStream extends InputStream{ private InputStream delegate; private SSLSocket sslSocket; public GlobusSSLInputStream(InputStream delegate, SSLSocket sslSocket) { this.delegate = delegate; this.sslSocket = sslSocket; } public SSLSocket getSSLSocket(){ return sslSocket; } public int available() throws IOException { return delegate.available(); } public void close() throws IOException { delegate.close(); } public boolean equals(Object obj) { return delegate.equals(obj); } public int hashCode() { return delegate.hashCode(); } public void mark(int readlimit) { delegate.mark(readlimit); } public boolean markSupported() { return delegate.markSupported(); } public int read() throws IOException { return delegate.read(); } public int read(byte[] b, int off, int len) throws IOException { return delegate.read(b, off, len); } public int read(byte[] b) throws IOException { return delegate.read(b); } public void reset() throws IOException { delegate.reset(); } public long skip(long n) throws IOException { return delegate.skip(n); } public String toString() { return delegate.toString(); } } GlobusSSLSocket.java000066400000000000000000000140371241116057200341220ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcatpackage org.globus.gsi.tomcat; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.SocketChannel; import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; public class GlobusSSLSocket extends SSLSocket { private SSLSocket socket; public GlobusSSLSocket(SSLSocket socket){ this.socket = socket; } public void addHandshakeCompletedListener(HandshakeCompletedListener listener) { socket.addHandshakeCompletedListener(listener); } public void bind(SocketAddress bindpoint) throws IOException { socket.bind(bindpoint); } public void close() throws IOException { socket.close(); } public void connect(SocketAddress endpoint, int timeout) throws IOException { socket.connect(endpoint, timeout); } public void connect(SocketAddress endpoint) throws IOException { socket.connect(endpoint); } public boolean equals(Object obj) { return socket.equals(obj); } public SocketChannel getChannel() { return socket.getChannel(); } public String[] getEnabledCipherSuites() { return socket.getEnabledCipherSuites(); } public String[] getEnabledProtocols() { return socket.getEnabledProtocols(); } public boolean getEnableSessionCreation() { return socket.getEnableSessionCreation(); } public InetAddress getInetAddress() { return socket.getInetAddress(); } public InputStream getInputStream() throws IOException { return new GlobusSSLInputStream(socket.getInputStream(), socket); } public boolean getKeepAlive() throws SocketException { return socket.getKeepAlive(); } public InetAddress getLocalAddress() { return socket.getLocalAddress(); } public int getLocalPort() { return socket.getLocalPort(); } public SocketAddress getLocalSocketAddress() { return socket.getLocalSocketAddress(); } public boolean getNeedClientAuth() { return socket.getNeedClientAuth(); } public boolean getOOBInline() throws SocketException { return socket.getOOBInline(); } public OutputStream getOutputStream() throws IOException { return socket.getOutputStream(); } public int getPort() { return socket.getPort(); } public int getReceiveBufferSize() throws SocketException { return socket.getReceiveBufferSize(); } public SocketAddress getRemoteSocketAddress() { return socket.getRemoteSocketAddress(); } public boolean getReuseAddress() throws SocketException { return socket.getReuseAddress(); } public int getSendBufferSize() throws SocketException { return socket.getSendBufferSize(); } public SSLSession getSession() { return socket.getSession(); } public int getSoLinger() throws SocketException { return socket.getSoLinger(); } public int getSoTimeout() throws SocketException { return socket.getSoTimeout(); } public SSLParameters getSSLParameters() { return socket.getSSLParameters(); } public String[] getSupportedCipherSuites() { return socket.getSupportedCipherSuites(); } public String[] getSupportedProtocols() { return socket.getSupportedProtocols(); } public boolean getTcpNoDelay() throws SocketException { return socket.getTcpNoDelay(); } public int getTrafficClass() throws SocketException { return socket.getTrafficClass(); } public boolean getUseClientMode() { return socket.getUseClientMode(); } public boolean getWantClientAuth() { return socket.getWantClientAuth(); } public int hashCode() { return socket.hashCode(); } public boolean isBound() { return socket.isBound(); } public boolean isClosed() { return socket.isClosed(); } public boolean isConnected() { return socket.isConnected(); } public boolean isInputShutdown() { return socket.isInputShutdown(); } public boolean isOutputShutdown() { return socket.isOutputShutdown(); } public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) { socket.removeHandshakeCompletedListener(listener); } public void sendUrgentData(int data) throws IOException { socket.sendUrgentData(data); } public void setEnabledCipherSuites(String[] suites) { socket.setEnabledCipherSuites(suites); } public void setEnabledProtocols(String[] protocols) { socket.setEnabledProtocols(protocols); } public void setEnableSessionCreation(boolean flag) { socket.setEnableSessionCreation(flag); } public void setKeepAlive(boolean on) throws SocketException { socket.setKeepAlive(on); } public void setNeedClientAuth(boolean need) { socket.setNeedClientAuth(need); } public void setOOBInline(boolean on) throws SocketException { socket.setOOBInline(on); } public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { socket.setPerformancePreferences(connectionTime, latency, bandwidth); } public void setReceiveBufferSize(int size) throws SocketException { socket.setReceiveBufferSize(size); } public void setReuseAddress(boolean on) throws SocketException { socket.setReuseAddress(on); } public void setSendBufferSize(int size) throws SocketException { socket.setSendBufferSize(size); } public void setSoLinger(boolean on, int linger) throws SocketException { socket.setSoLinger(on, linger); } public void setSoTimeout(int timeout) throws SocketException { socket.setSoTimeout(timeout); } public void setSSLParameters(SSLParameters params) { socket.setSSLParameters(params); } public void setTcpNoDelay(boolean on) throws SocketException { socket.setTcpNoDelay(on); } public void setTrafficClass(int tc) throws SocketException { socket.setTrafficClass(tc); } public void setUseClientMode(boolean mode) { socket.setUseClientMode(mode); } public void setWantClientAuth(boolean want) { socket.setWantClientAuth(want); } public void shutdownInput() throws IOException { socket.shutdownInput(); } public void shutdownOutput() throws IOException { socket.shutdownOutput(); } public void startHandshake() throws IOException { socket.startHandshake(); } } GlobusSSLSocketFactory.java000066400000000000000000000102331241116057200354440ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.tomcat; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.jsse.JSSESocketFactory; import org.globus.gsi.X509ProxyCertPathParameters; import org.globus.gsi.jsse.GlobusSSLHelper; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.trustmanager.PKITrustManager; import org.globus.gsi.trustmanager.X509ProxyCertPathValidator; import org.globus.gsi.stores.ResourceSigningPolicyStore; import org.globus.gsi.stores.Stores; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.TrustManager; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.security.KeyStore; import java.security.Security; import java.security.cert.CertStore; /** * This extends the standard JSSE to support the globus trust manager and all of the associated properties: * CRLs, SigningPolicies, proxy certificates. * * @version 1.0 * @since 1.0 */ public class GlobusSSLSocketFactory extends JSSESocketFactory { static { Security.addProvider(new GlobusProvider()); } protected Object crlLocation; protected Object signingPolicyLocation; protected Object rejectLimitedProxyEntry; public GlobusSSLSocketFactory(AbstractEndpoint endpoint) { super(endpoint); crlLocation = endpoint.getAttribute("crlLocation"); signingPolicyLocation = endpoint.getAttribute("signingPolicyLocation"); rejectLimitedProxyEntry = endpoint.getAttribute("rejectLimitedProxy"); } /** * Create a Globus trust manager which supports proxy certificates. This requires that the CRL store, and * signing policy store be configured. * * @param keystoreType The type of keystore to create. * @param keystoreProvider The keystore provider to use. * @param algorithm The keystore algorithm. * @return A set of configured TrustManagers. * @throws Exception If we cannot create the trust managers. */ @Override protected TrustManager[] getTrustManagers(String keystoreType, String keystoreProvider, String algorithm) throws Exception { KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); CertStore crlStore = null; if (crlLocation != null) { crlStore = GlobusSSLHelper.findCRLStore((String) crlLocation); } ResourceSigningPolicyStore policyStore = null; if (signingPolicyLocation != null) { policyStore = Stores.getSigningPolicyStore((String) signingPolicyLocation); } boolean rejectLimitedProxy = rejectLimitedProxyEntry != null && Boolean.parseBoolean((String) rejectLimitedProxyEntry); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(trustStore, crlStore, policyStore, rejectLimitedProxy); TrustManager trustManager = new PKITrustManager(new X509ProxyCertPathValidator(), parameters); return new TrustManager[]{trustManager}; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } @Override public ServerSocket createSocket(int port, int backlog, InetAddress ifAddress) throws IOException { return new GlobusSSLSocketWrapper((SSLServerSocket) super.createSocket(port, backlog, ifAddress)); } @Override public ServerSocket createSocket(int port, int backlog) throws IOException { return createSocket(port, backlog, null); } @Override public ServerSocket createSocket(int port) throws IOException { return createSocket(port, 50); } } GlobusSSLSocketWrapper.java000066400000000000000000000067721241116057200354720ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcatpackage org.globus.gsi.tomcat; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.ServerSocketChannel; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLSocket; public class GlobusSSLSocketWrapper extends SSLServerSocket { private SSLServerSocket delegate; public GlobusSSLSocketWrapper(SSLServerSocket delegate) throws IOException { super(); this.delegate = delegate; } public Socket accept() throws IOException { return new GlobusSSLSocket((SSLSocket) delegate.accept()); } public void bind(SocketAddress endpoint, int backlog) throws IOException { delegate.bind(endpoint, backlog); } public void bind(SocketAddress endpoint) throws IOException { delegate.bind(endpoint); } public void close() throws IOException { delegate.close(); } public boolean equals(Object obj) { return delegate.equals(obj); } public ServerSocketChannel getChannel() { return delegate.getChannel(); } public String[] getEnabledCipherSuites() { return delegate.getEnabledCipherSuites(); } public String[] getEnabledProtocols() { return delegate.getEnabledProtocols(); } public boolean getEnableSessionCreation() { return delegate.getEnableSessionCreation(); } public InetAddress getInetAddress() { return delegate.getInetAddress(); } public int getLocalPort() { return delegate.getLocalPort(); } public SocketAddress getLocalSocketAddress() { return delegate.getLocalSocketAddress(); } public boolean getNeedClientAuth() { return delegate.getNeedClientAuth(); } public int getReceiveBufferSize() throws SocketException { return delegate.getReceiveBufferSize(); } public boolean getReuseAddress() throws SocketException { return delegate.getReuseAddress(); } public int getSoTimeout() throws IOException { return delegate.getSoTimeout(); } public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } public String[] getSupportedProtocols() { return delegate.getSupportedProtocols(); } public boolean getUseClientMode() { return delegate.getUseClientMode(); } public boolean getWantClientAuth() { return delegate.getWantClientAuth(); } public int hashCode() { return delegate.hashCode(); } public boolean isBound() { return delegate.isBound(); } public boolean isClosed() { return delegate.isClosed(); } public void setEnabledCipherSuites(String[] suites) { delegate.setEnabledCipherSuites(suites); } public void setEnabledProtocols(String[] protocols) { delegate.setEnabledProtocols(protocols); } public void setEnableSessionCreation(boolean flag) { delegate.setEnableSessionCreation(flag); } public void setNeedClientAuth(boolean need) { delegate.setNeedClientAuth(need); } public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { delegate.setPerformancePreferences(connectionTime, latency, bandwidth); } public void setReceiveBufferSize(int size) throws SocketException { delegate.setReceiveBufferSize(size); } public void setReuseAddress(boolean on) throws SocketException { delegate.setReuseAddress(on); } public void setSoTimeout(int timeout) throws SocketException { delegate.setSoTimeout(timeout); } public void setUseClientMode(boolean mode) { delegate.setUseClientMode(mode); } public void setWantClientAuth(boolean want) { delegate.setWantClientAuth(want); } public String toString() { return delegate.toString(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/patches/000077500000000000000000000000001241116057200247165ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/patches/jglobus-tomcat5.patch000066400000000000000000000100721241116057200307560ustar00rootroot00000000000000diff --git a/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLImplementation.java b/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLImplementation.java index 96fed75..1741218 100644 --- a/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLImplementation.java +++ b/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLImplementation.java @@ -1,7 +1,6 @@ package org.globus.gsi.tomcat; -import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.ServerSocketFactory; import org.apache.tomcat.util.net.jsse.JSSEImplementation; @@ -15,8 +14,8 @@ public class GlobusSSLImplementation extends JSSEImplementation { return "GlobusSSLImplementation"; } - public ServerSocketFactory getServerSocketFactory(AbstractEndpoint endpoint) { - return new GlobusSSLSocketFactory(endpoint); + public ServerSocketFactory getServerSocketFactory() { + return new GlobusSSLSocketFactory(); } } diff --git a/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLSocketFactory.java b/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLSocketFactory.java index 3718fa3..74ef715 100644 --- a/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLSocketFactory.java +++ b/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLSocketFactory.java @@ -15,8 +15,7 @@ package org.globus.gsi.tomcat; -import org.apache.tomcat.util.net.AbstractEndpoint; -import org.apache.tomcat.util.net.jsse.JSSESocketFactory; +import org.apache.tomcat.util.net.jsse.JSSE14SocketFactory; import org.globus.gsi.X509ProxyCertPathParameters; import org.globus.gsi.jsse.GlobusSSLHelper; import org.globus.gsi.provider.GlobusProvider; @@ -41,58 +40,12 @@ import java.security.cert.CertStore; * @version 1.0 * @since 1.0 */ -public class GlobusSSLSocketFactory extends JSSESocketFactory { +public class GlobusSSLSocketFactory extends JSSE14SocketFactory { static { Security.addProvider(new GlobusProvider()); } - protected Object crlLocation; - protected Object signingPolicyLocation; - protected Object rejectLimitedProxyEntry; - - public GlobusSSLSocketFactory(AbstractEndpoint endpoint) { - super(endpoint); - crlLocation = endpoint.getAttribute("crlLocation"); - signingPolicyLocation = endpoint.getAttribute("signingPolicyLocation"); - rejectLimitedProxyEntry = endpoint.getAttribute("rejectLimitedProxy"); - } - - /** - * Create a Globus trust manager which supports proxy certificates. This requires that the CRL store, and - * signing policy store be configured. - * - * @param keystoreType The type of keystore to create. - * @param keystoreProvider The keystore provider to use. - * @param algorithm The keystore algorithm. - * @return A set of configured TrustManagers. - * @throws Exception If we cannot create the trust managers. - */ - @Override - protected TrustManager[] getTrustManagers(String keystoreType, String keystoreProvider, String algorithm) - throws Exception { - KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); - - CertStore crlStore = null; - if (crlLocation != null) { - crlStore = GlobusSSLHelper.findCRLStore((String) crlLocation); - } - - ResourceSigningPolicyStore policyStore = null; - if (signingPolicyLocation != null) { - policyStore = Stores.getSigningPolicyStore((String) signingPolicyLocation); - } - - boolean rejectLimitedProxy = rejectLimitedProxyEntry != null && - Boolean.parseBoolean((String) rejectLimitedProxyEntry); - - X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(trustStore, crlStore, policyStore, - rejectLimitedProxy); - TrustManager trustManager = new PKITrustManager(new X509ProxyCertPathValidator(), parameters); - return new TrustManager[]{trustManager}; - } - - @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/src/main/patches/jglobus-tomcat6.patch000066400000000000000000000063241241116057200307640ustar00rootroot00000000000000diff --git a/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLImplementation.java b/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLImplementation.java index 96fed75..1741218 100644 --- a/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLImplementation.java +++ b/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLImplementation.java @@ -1,7 +1,6 @@ package org.globus.gsi.tomcat; -import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.ServerSocketFactory; import org.apache.tomcat.util.net.jsse.JSSEImplementation; @@ -15,8 +14,8 @@ public class GlobusSSLImplementation extends JSSEImplementation { return "GlobusSSLImplementation"; } - public ServerSocketFactory getServerSocketFactory(AbstractEndpoint endpoint) { - return new GlobusSSLSocketFactory(endpoint); + public ServerSocketFactory getServerSocketFactory() { + return new GlobusSSLSocketFactory(); } } diff --git a/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLSocketFactory.java b/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLSocketFactory.java index 3718fa3..49cd674 100644 --- a/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLSocketFactory.java +++ b/ssl-proxies-tomcat/src/main/java/org/globus/gsi/tomcat/GlobusSSLSocketFactory.java @@ -15,7 +15,6 @@ package org.globus.gsi.tomcat; -import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.jsse.JSSESocketFactory; import org.globus.gsi.X509ProxyCertPathParameters; import org.globus.gsi.jsse.GlobusSSLHelper; @@ -47,17 +46,6 @@ public class GlobusSSLSocketFactory extends JSSESocketFactory { Security.addProvider(new GlobusProvider()); } - protected Object crlLocation; - protected Object signingPolicyLocation; - protected Object rejectLimitedProxyEntry; - - public GlobusSSLSocketFactory(AbstractEndpoint endpoint) { - super(endpoint); - crlLocation = endpoint.getAttribute("crlLocation"); - signingPolicyLocation = endpoint.getAttribute("signingPolicyLocation"); - rejectLimitedProxyEntry = endpoint.getAttribute("rejectLimitedProxy"); - } - /** * Create a Globus trust manager which supports proxy certificates. This requires that the CRL store, and * signing policy store be configured. @@ -74,15 +62,18 @@ public class GlobusSSLSocketFactory extends JSSESocketFactory { KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); CertStore crlStore = null; + Object crlLocation = attributes.get("crlLocation"); if (crlLocation != null) { crlStore = GlobusSSLHelper.findCRLStore((String) crlLocation); } + Object signingPolicyLocation = attributes.get("signingPolicyLocation"); ResourceSigningPolicyStore policyStore = null; if (signingPolicyLocation != null) { policyStore = Stores.getSigningPolicyStore((String) signingPolicyLocation); } + Object rejectLimitedProxyEntry = attributes.get("rejectLimitedProxy"); boolean rejectLimitedProxy = rejectLimitedProxyEntry != null && Boolean.parseBoolean((String) rejectLimitedProxyEntry); JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/work/000077500000000000000000000000001241116057200225365ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/work/Catalina/000077500000000000000000000000001241116057200242525ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/work/Catalina/localhost/000077500000000000000000000000001241116057200262425ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/work/Catalina/localhost/_/000077500000000000000000000000001241116057200264605ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies-tomcat/work/Catalina/localhost/_/SESSIONS.ser000066400000000000000000000001211241116057200304330ustar00rootroot00000000000000¬ísrjava.lang.Integerâ ¤÷‡8Ivaluexrjava.lang.Number†¬• ”à‹xpJGlobus-JGlobus-Release-2.1.0/ssl-proxies/000077500000000000000000000000001241116057200202675ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/README.textile000066400000000000000000000000001241116057200226120ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/pom.xml000066400000000000000000000043061241116057200216070ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 ssl-proxies SSL and proxy certificate support org.apache.maven.plugins maven-surefire-plugin ${surefire.version} false ${skipTests} ${project.build.testOutputDirectory} ${basedir} commons-logging commons-logging compile log4j log4j compile org.bouncycastle bcprov-jdk15on commons-io commons-io commons-codec commons-codec junit junit test ${project.groupId} test-utils ${project.version} test 2.12 false JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/000077500000000000000000000000001241116057200210565ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/000077500000000000000000000000001241116057200220025ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/000077500000000000000000000000001241116057200227235ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/000077500000000000000000000000001241116057200235125ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/000077500000000000000000000000001241116057200250055ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/common/000077500000000000000000000000001241116057200262755ustar00rootroot00000000000000ChainedCertificateException.java000066400000000000000000000106231241116057200344400ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/common/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.common; /** * @deprecated */ public class ChainedCertificateException extends java.security.cert.CertificateException { /** * The possibly null root cause exception. * @serial */ private Throwable exception; /** * Constructs a new instance of ChainedIOException. * The root exception and the detailed message are null. */ public ChainedCertificateException () { super(); } /** * Constructs a new instance of ChainedIOException with a * detailed message. The root exception is null. * * @param detail A possibly null string containing details of the * exception. * * @see java.lang.Throwable#getMessage */ public ChainedCertificateException (String detail) { super(detail); } /** * Constructs a new instance of ChainedIOException with a * detailed message and a root exception. * * @param detail A possibly null string containing details of the * exception. * @param ex A possibly null root exception that caused this exception. * * @see java.lang.Throwable#getMessage * @see #getException */ public ChainedCertificateException (String detail, Throwable ex) { super(detail); exception = ex; } /** * Returns the root exception that caused this exception. * @return The possibly null root exception that caused this exception. */ public Throwable getException() { return exception; } /** * Prints this exception's stack trace to System.err. * If this exception has a root exception; the stack trace of the * root exception is printed to System.err instead. */ public void printStackTrace() { printStackTrace( System.err ); } /** * Prints this exception's stack trace to a print stream. * If this exception has a root exception; the stack trace of the * root exception is printed to the print stream instead. * @param ps The non-null print stream to which to print. */ public void printStackTrace(java.io.PrintStream ps) { if ( exception != null ) { String superString = getLocalMessage(); synchronized ( ps ) { ps.print(superString); ps.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); exception.printStackTrace( ps ); } } else { super.printStackTrace( ps ); } } /** * Prints this exception's stack trace to a print writer. * If this exception has a root exception; the stack trace of the * root exception is printed to the print writer instead. * @param pw The non-null print writer to which to print. */ public void printStackTrace(java.io.PrintWriter pw) { if ( exception != null ) { String superString = getLocalMessage(); synchronized (pw) { pw.print(superString); pw.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); exception.printStackTrace( pw ); } } else { super.printStackTrace( pw ); } } public String getMessage() { String answer = super.getMessage(); if (exception != null && exception != this) { String msg = exception.getMessage(); if (msg == null) { msg = exception.getClass().getName(); } answer += " [Caused by: " + msg + "]"; } return answer; } private String getLocalMessage() { String message = super.getMessage(); return (message == null) ? getClass().getName() : message; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/common/ChainedException.java000066400000000000000000000104771241116057200323630ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.common; /** * @deprecated */ public class ChainedException extends Exception { /** * The possibly null root cause exception. * @serial */ private Throwable exception; /** * Constructs a new instance of ChainedException. * The root exception and the detailed message are null. */ public ChainedException () { super(); } /** * Constructs a new instance of ChainedException with a * detailed message. The root exception is null. * * @param detail A possibly null string containing details of the * exception. * * @see java.lang.Throwable#getMessage */ public ChainedException (String detail) { super(detail); } /** * Constructs a new instance of ChainedException with a * detailed message and a root exception. * * @param detail A possibly null string containing details of the * exception. * @param ex A possibly null root exception that caused this exception. * * @see java.lang.Throwable#getMessage * @see #getException */ public ChainedException (String detail, Throwable ex) { super(detail); exception = ex; } /** * Returns the root exception that caused this exception. * @return The possibly null root exception that caused this exception. */ public Throwable getException() { return exception; } /** * Prints this exception's stack trace to System.err. * If this exception has a root exception; the stack trace of the * root exception is printed to System.err instead. */ public void printStackTrace() { printStackTrace( System.err ); } /** * Prints this exception's stack trace to a print stream. * If this exception has a root exception; the stack trace of the * root exception is printed to the print stream instead. * @param ps The non-null print stream to which to print. */ public void printStackTrace(java.io.PrintStream ps) { if ( exception != null ) { String superString = getLocalMessage(); synchronized ( ps ) { ps.print(superString); ps.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); exception.printStackTrace( ps ); } } else { super.printStackTrace( ps ); } } /** * Prints this exception's stack trace to a print writer. * If this exception has a root exception; the stack trace of the * root exception is printed to the print writer instead. * @param pw The non-null print writer to which to print. */ public void printStackTrace(java.io.PrintWriter pw) { if ( exception != null ) { String superString = getLocalMessage(); synchronized (pw) { pw.print(superString); pw.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); exception.printStackTrace( pw ); } } else { super.printStackTrace( pw ); } } public String getMessage() { String answer = super.getMessage(); if (exception != null && exception != this) { String msg = exception.getMessage(); if (msg == null) { msg = exception.getClass().getName(); } answer += " [Caused by: " + msg + "]"; } return answer; } private String getLocalMessage() { String message = super.getMessage(); return (message == null) ? getClass().getName() : message; } } ChainedGeneralSecurityException.java000066400000000000000000000106421241116057200353240ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/common/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.common; /** * @deprecated */ public class ChainedGeneralSecurityException extends java.security.GeneralSecurityException { /** * The possibly null root cause exception. * @serial */ private Throwable exception; /** * Constructs a new instance of ChainedIOException. * The root exception and the detailed message are null. */ public ChainedGeneralSecurityException () { super(); } /** * Constructs a new instance of ChainedIOException with a * detailed message. The root exception is null. * * @param detail A possibly null string containing details of the * exception. * * @see java.lang.Throwable#getMessage */ public ChainedGeneralSecurityException (String detail) { super(detail); } /** * Constructs a new instance of ChainedIOException with a * detailed message and a root exception. * * @param detail A possibly null string containing details of the * exception. * @param ex A possibly null root exception that caused this exception. * * @see java.lang.Throwable#getMessage * @see #getException */ public ChainedGeneralSecurityException (String detail, Throwable ex) { super(detail); exception = ex; } /** * Returns the root exception that caused this exception. * @return The possibly null root exception that caused this exception. */ public Throwable getException() { return exception; } /** * Prints this exception's stack trace to System.err. * If this exception has a root exception; the stack trace of the * root exception is printed to System.err instead. */ public void printStackTrace() { printStackTrace( System.err ); } /** * Prints this exception's stack trace to a print stream. * If this exception has a root exception; the stack trace of the * root exception is printed to the print stream instead. * @param ps The non-null print stream to which to print. */ public void printStackTrace(java.io.PrintStream ps) { if ( exception != null ) { String superString = getLocalMessage(); synchronized ( ps ) { ps.print(superString); ps.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); exception.printStackTrace( ps ); } } else { super.printStackTrace( ps ); } } /** * Prints this exception's stack trace to a print writer. * If this exception has a root exception; the stack trace of the * root exception is printed to the print writer instead. * @param pw The non-null print writer to which to print. */ public void printStackTrace(java.io.PrintWriter pw) { if ( exception != null ) { String superString = getLocalMessage(); synchronized (pw) { pw.print(superString); pw.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); exception.printStackTrace( pw ); } } else { super.printStackTrace( pw ); } } public String getMessage() { String answer = super.getMessage(); if (exception != null && exception != this) { String msg = exception.getMessage(); if (msg == null) { msg = exception.getClass().getName(); } answer += " [Caused by: " + msg + "]"; } return answer; } private String getLocalMessage() { String message = super.getMessage(); return (message == null) ? getClass().getName() : message; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/common/ChainedIOException.java000066400000000000000000000105171241116057200326060ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.common; /** * */ public class ChainedIOException extends java.io.IOException { /** * The possibly null root cause exception. * @serial */ private Throwable exception; /** * Constructs a new instance of ChainedIOException. * The root exception and the detailed message are null. */ public ChainedIOException () { super(); } /** * Constructs a new instance of ChainedIOException with a * detailed message. The root exception is null. * * @param detail A possibly null string containing details of the * exception. * * @see java.lang.Throwable#getMessage */ public ChainedIOException (String detail) { super(detail); } /** * Constructs a new instance of ChainedIOException with a * detailed message and a root exception. * * @param detail A possibly null string containing details of the * exception. * @param ex A possibly null root exception that caused this exception. * * @see java.lang.Throwable#getMessage * @see #getException */ public ChainedIOException (String detail, Throwable ex) { super(detail, ex); exception = ex; } /** * Returns the root exception that caused this exception. * @return The possibly null root exception that caused this exception. */ public Throwable getException() { return exception; } /** * Prints this exception's stack trace to System.err. * If this exception has a root exception; the stack trace of the * root exception is printed to System.err instead. */ public void printStackTrace() { printStackTrace( System.err ); } /** * Prints this exception's stack trace to a print stream. * If this exception has a root exception; the stack trace of the * root exception is printed to the print stream instead. * @param ps The non-null print stream to which to print. */ public void printStackTrace(java.io.PrintStream ps) { if ( exception != null ) { String superString = getLocalMessage(); synchronized ( ps ) { ps.print(superString); ps.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); exception.printStackTrace( ps ); } } else { super.printStackTrace( ps ); } } /** * Prints this exception's stack trace to a print writer. * If this exception has a root exception; the stack trace of the * root exception is printed to the print writer instead. * @param pw The non-null print writer to which to print. */ public void printStackTrace(java.io.PrintWriter pw) { if ( exception != null ) { String superString = getLocalMessage(); synchronized (pw) { pw.print(superString); pw.print((superString.endsWith(".") ? " Caused by " : ". Caused by ")); exception.printStackTrace( pw ); } } else { super.printStackTrace( pw ); } } public String getMessage() { String answer = super.getMessage(); if (exception != null && exception != this) { String msg = exception.getMessage(); if (msg == null) { msg = exception.getClass().getName(); } answer += " [Caused by: " + msg + "]"; } return answer; } private String getLocalMessage() { String message = super.getMessage(); return (message == null) ? getClass().getName() : message; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/common/CoGProperties.java000066400000000000000000000556051241116057200317000ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.common; import java.util.Properties; import java.util.Enumeration; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import org.globus.util.ConfigUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** Responsible for managing the properties file * "~/.globus/cog.properties", which holds information about various properties * needed by the security classes. These properties include: *
      *
    • the location of the user certificate file
    • *
    • the location of the user key file
    • *
    • the location of the CA certificates
    • *
    • the location of the proxy file
    • *
    • the tcp port range
    • *
    • the local ip address for DHCP systems
    • *
    • the socket timeout when connecting to a myproxy host
    • *
    */ public class CoGProperties extends Properties { private static Log logger = LogFactory.getLog(CoGProperties.class.getName()); private static final String DEFAULT_RANDOM_PROVIDER = "org.bouncycastle.jce.provider.BouncyCastleProvider"; private static final String DEFAULT_RANDOM_ALGORITHM = "DevRandom"; public static final String ENFORCE_SIGNING_POLICY = "java.security.gsi.signing.policy"; public static final String DELEGATION_KEY_CACHE_LIFETIME = "org.globus.jglobus.delegation.cache.lifetime"; @Deprecated public static final String CRL_CACHE_LIFETIME = "org.globus.jglobus.crl.cache.lifetime"; public static final String CERT_CACHE_LIFETIME = "org.globus.jglobus.cert.cache.lifetime"; public static final String MDSHOST = "localhost"; public static final String MDSPORT = "2135"; public static final String BASEDN = "Mds-Vo-name=local, o=Grid"; final static String SOCKET_TIMEOUT = "org.globus.socket.timeout"; private static final String REVERSE_DNS_CACHETYPE = "org.globus.gsi.gssapi.cache.type"; private static final String REVERSE_DNS_CACHE_LIFETIME = "org.globus.gsi.gssapi.cache.lifetime"; final static public String NO_CACHE = "NoCache"; final static public String THREADED_CACHE = "ThreadedCache"; /** the configuration file properties are read from -- * located in ~/.globus" */ public static final String CONFIG_FILE = "cog.properties"; /** the default properties file **/ private static CoGProperties defaultProps = null; /** the config file location **/ public static String configFile = null; public CoGProperties() { } public CoGProperties(String file) throws IOException { load(file); } public synchronized static CoGProperties getDefault() { if (defaultProps != null) { return defaultProps; } defaultProps = new CoGProperties(); String file = System.getProperty("org.globus.config.file"); if (file == null) { file = ConfigUtil.globus_dir + CONFIG_FILE; } else if (file.equalsIgnoreCase("none")) { return defaultProps; } configFile = file; try { defaultProps.load(configFile); } catch(IOException e) { logger.debug("Failed to load " + CONFIG_FILE + ". Using defaults.", e); } return defaultProps; } /** * Sets default configuration. It can be used * to set a different configuration dynamically. */ public static void setDefault(CoGProperties properties) { defaultProps = properties; } public void save() throws IOException { save(configFile); } public void save(String file) throws IOException { OutputStream out = null; try { out = new FileOutputStream(file); store(out, "Java CoG Kit Configuration File"); } finally { if (out != null) { try { out.close(); } catch (Exception e) {} } } } public void load(String file) throws IOException { FileInputStream in = null; try { in = new FileInputStream(file); load(in); } finally { if (in != null) { try { in.close(); } catch(Exception e) {} } } } public void load(InputStream in) throws IOException { super.load(in); fixSpace(this); } public static void fixSpace(Properties p) { // this will get rid off the trailing spaces String key, value; Enumeration e = p.keys(); while(e.hasMoreElements()) { key = e.nextElement().toString(); value = p.getProperty(key); p.put(key, value.trim()); } } /** * Retrieves the location of the user cert file. * It first checks the X509_USER_CERT system property. If the property * is not set, it checks next the 'usercert' property in the current * configuration. If that property is not set, it returns a default * location of the user cert file. The default value * is the 'usercert.pem' file in the user's globus directory. For example: * ${user.home}/.globus/usercert.pem. * * @return String the location of the user cert file */ public String getUserCertFile() { String location; location = System.getProperty("X509_USER_CERT"); if (location != null) { return location; } location = getProperty("usercert"); if (location != null) { return location; } return ConfigUtil.discoverUserCertLocation(); } public void setUserCertFile(String userCertFile) { put("usercert", userCertFile); } public String getPKCS11LibraryName() { String lib; lib = System.getProperty("PKCS11_LIB"); if (lib != null) { return lib; } lib = getProperty("pkcs11lib"); if (lib != null) { return lib; } return ConfigUtil.discoverPKCS11LibName(); } public String getDefaultPKCS11Handle() { return getProperty("pkcs11.handle", "Globus User Credentials"); } /** * Retrieves the location of the user key file. * It first checks the X509_USER_KEY system property. If the property * is not set, it checks next the 'userkey' property in the current * configuration. If that property is not set, it returns a default * location of the user key file. The default value * is the 'userkey.pem' file in the user's globus directory. For example: * ${user.home}/.globus/userkey.pem. * * @return String the location of the user key file */ public String getUserKeyFile() { String location; location = System.getProperty("X509_USER_KEY"); if (location != null) { return location; } location = getProperty("userkey"); if (location != null) { return location; } return ConfigUtil.discoverUserKeyLocation(); } /** * Sets user key file location * @param userKeyFile user key file location */ public void setUserKeyFile(String userKeyFile) { put("userkey", userKeyFile); } /** * Returns the user specified hostname. This is used * for DHCP machines where java is unable to determine the * right hostname/IP address. * It first checks the 'GLOBUS_HOSTNAME' system property. If the property * is not set, it checks the 'host' system property next. If the 'host' * property is not set in the current configuration, null is returned * (and default 'localhost' hostname will be used) * * @return String the hostname of the machine. */ public String getHostName() { String value = System.getProperty("GLOBUS_HOSTNAME"); if (value != null) { return value; } return getProperty("hostname", null); } /** * Sets hostname * @param host hostname */ public void setHostName(String host) { put("hostname", host); } /** * Returns the user specified ip address. This is used * for DHCP machines where java is unable to determine the * right IP address. * It first checks the 'org.globus.ip' system property. * If that property is not set, it checks next the 'ip' property * in the current configuration. If the 'ip' property is not set in the * current configuration, the hostname of the machine is looked up * using the {@link #getHostName() getHostName()} function. If * getHostName() returns a hostname that hostname is converted * into an IP address and it is returned. Otherwise, null is returned * (and default ip address will be used) * * @return String the ip address of the machine. */ public String getIPAddress() { String value = System.getProperty("org.globus.ip"); if (value != null) { return value; } value = getProperty("ip", null); if (value != null) { return value; } value = getHostName(); if (value != null) { try { return InetAddress.getByName(value).getHostAddress(); } catch (UnknownHostException e) { return null; } } return value; } /** * Sets ip address * @param ipAddress ip address */ public void setIPAddress(String ipAddress) { put("ip", ipAddress); } /** * Retrieves the location of the CA certificate files. * It first checks the X509_CERT_DIR system property. If the property * is not set, it checks next the 'cacert' property in the current * configuration. If that property is not set, it tries to find * the certificates using the following rules:
    * First the ${user.home}/.globus/certificates directory is checked. * If the directory does not exist, and on a Unix machine, the * /etc/grid-security/certificates directory is checked next. * If that directory does not exist and GLOBUS_LOCATION * system property is set then the ${GLOBUS_LOCATION}/share/certificates * directory is checked. Otherwise, null is returned. * This indicates that the certificates directory could * not be found. *
    * Moreover, this function can return multiple file and directory * locations. The locations must be comma separated. * * @return String the locations of the CA certificates */ public String getCaCertLocations() { String location; location = System.getProperty("X509_CERT_DIR"); if (location != null) { return location; } location = getProperty("cacert"); if (location != null) { return location; } return ConfigUtil.discoverCertDirLocation(); } public void setCaCertLocations(String list) { put("cacert", list); } /** * Retrieves the location of the proxy file. * It first checks the X509_USER_PROXY system property. If the property * is not set, it checks next the 'proxy' property in the current * configuration. If that property is not set, then it defaults to a * value based on the following rules:
    * If a UID system property is set, and running on a Unix machine it * returns /tmp/x509up_u${UID}. If any other machine then Unix, it returns * ${tempdir}/x509up_u${UID}, where tempdir is a platform-specific * temporary directory as indicated by the java.io.tmpdir system property. * If a UID system property is not set, the username will be used instead * of the UID. That is, it returns ${tempdir}/x509up_u_${username} *
    * This is done this way because Java is not able to obtain the current * uid. * * @return String the location of the proxy file */ public String getProxyFile() { String location; location = System.getProperty("X509_USER_PROXY"); if (location != null) { return location; } location = getProperty("proxy"); if (location != null) { return location; } return ConfigUtil.discoverProxyLocation(); } public void setProxyFile(String proxyFile) { put("proxy", proxyFile); } /** * Returns the tcp port range. * It first checks the 'GLOBUS_TCP_PORT_RANGE' system property. If that * system property is not set then 'org.globus.tcp.port.range' system * property is checked. If that system property is not set then it returns * the value specified in the configuration file. Returns null if the port * range is not defined.
    * The port range is in the following form: , * * @return String the port range. */ public String getTcpPortRange() { String value = null; value = System.getProperty("GLOBUS_TCP_PORT_RANGE"); if (value != null) { return value; } value = System.getProperty("org.globus.tcp.port.range"); if (value != null) { return value; } return getProperty("tcp.port.range", null); } /** * Returns the tcp source port range. * It first checks the 'GLOBUS_TCP_SOURCE_PORT_RANGE' system property. * If that system property is not set then * 'org.globus.source.tcp.port.range' system property is checked. * If that system property is not set then it returns * the value specified in the configuration file. Returns null if the port * range is not defined.
    * The port range is in the following form: , * * @return String the port range. */ public String getTcpSourcePortRange() { String value = null; value = System.getProperty("GLOBUS_TCP_SOURCE_PORT_RANGE"); if (value != null) { return value; } value = System.getProperty("org.globus.tcp.source.port.range"); if (value != null) { return value; } return getProperty("tcp.source.port.range", null); } /** * Returns the udp source port range. * It first checks the 'GLOBUS_UDP_SOURCE_PORT_RANGE' system property. * If that system property is not set then * 'org.globus.source.udp.port.range' system property is checked. * If that system property is not set then it returns * the value specified in the configuration file. Returns null if the port * range is not defined.
    * The port range is in the following form: , * * @return String the port range. */ public String getUdpSourcePortRange() { String value = null; value = System.getProperty("GLOBUS_UDP_SOURCE_PORT_RANGE"); if (value != null) { return value; } value = System.getProperty("org.globus.udp.source.port.range"); if (value != null) { return value; } return getProperty("udp.source.port.range", null); } /** * Returns whether to use the /dev/urandom device * for seed generation. * * @return true if the device should be used (if available of course) * Returns true by default unless specified otherwise by the * user. */ public boolean useDevRandom() { String value = System.getProperty("org.globus.dev.random"); if (value != null && value.equalsIgnoreCase("no")) { return false; } return getAsBoolean("org.globus.dev.random", true); } public boolean enforceSigningPolicy() { String value = System.getProperty(ENFORCE_SIGNING_POLICY); if ((value != null) && (value.equalsIgnoreCase("no") || (value.equalsIgnoreCase("false")))) { return false; } return getAsBoolean(ENFORCE_SIGNING_POLICY, true); } /** * Returns the delegation key cache lifetime for all delegations from this * JVM. If this property is not set or set to zero or less, no caching is * done. * * @return the number of milliseconds the key/pair is cached */ public int getDelegationKeyCacheLifetime() { int valueInt = 0; String valueStr = System.getProperty(DELEGATION_KEY_CACHE_LIFETIME); if (valueStr != null && valueStr.length() > 0) { int parsedvalueInt = Integer.parseInt(valueStr); if (parsedvalueInt > 0) { valueInt = parsedvalueInt; } } if (valueInt == -1) { // Didn't find a system property valueStr = getProperty(DELEGATION_KEY_CACHE_LIFETIME); if (valueStr != null && valueStr.length() > 0) { int parsedvalueInt = Integer.parseInt(valueStr); if (parsedvalueInt > 0) { valueInt = parsedvalueInt; } } } return valueInt; } /** * Returns the CRL cache lifetime. If this property is * set to zero or less, no caching is done. The value is the * number of milliseconds the CRLs are cached without checking for * modifications on disk. * * Defaults to 60s. * * @throws NumberFormatException if the cache lifetime property * could not be parsed * @return the CRL cache lifetime in milliseconds * @deprecated replaced by {@link #getCertCacheLifetime()} */ @Deprecated public long getCRLCacheLifetime() { long value = getCertCacheLifetime(); String property = getProperty(CRL_CACHE_LIFETIME); if (property != null && property.length() > 0) { long parsedValue = Long.parseLong(property); if (parsedValue > 0) { value = parsedValue; } } // System property takes precedence property = System.getProperty(CRL_CACHE_LIFETIME); if (property != null && property.length() > 0) { long parsedValue = Long.parseLong(property); if (parsedValue > 0) { value = parsedValue; } } return value; } /** * Returns the Cert cache lifetime. If this property is * set to zero or less, no caching is done. The value is the * number of milliseconds the certificates are cached without checking for * modifications on disk. * * Defaults to 60s. * * @throws NumberFormatException if the cache lifetime property * could not be parsed * @return the Cert cache lifetime in milliseconds */ public long getCertCacheLifetime() throws NumberFormatException { long value = 60*1000; String property = getProperty(CERT_CACHE_LIFETIME); if (property != null && property.length() > 0) { long parsedValue = Long.parseLong(property); if (parsedValue > 0) { value = parsedValue; } } // System property takes precedence property = System.getProperty(CERT_CACHE_LIFETIME); if (property != null && property.length() > 0) { long parsedValue = Long.parseLong(property); if (parsedValue > 0) { value = parsedValue; } } return value; } /** * Returns the reverse DNS cache time. * * Defaults to 1h. * * @throws NumberFormatException if the cache lifetime property * could not be parsed * @return the reverse DNS cache lifetime in milliseconds */ public long getReveseDNSCacheLifetime() throws NumberFormatException { long value = 60*60*1000; String property = getProperty(REVERSE_DNS_CACHE_LIFETIME); if (property != null && property.length() > 0) { long parsedValue = Long.parseLong(property); if (parsedValue > 0) { value = parsedValue; } } // System property takes precedence property = System.getProperty(REVERSE_DNS_CACHE_LIFETIME); if (property != null && property.length() > 0) { long parsedValue = Long.parseLong(property); if (parsedValue > 0) { value = parsedValue; } } return value; } /** * Returns the reverse DNS cache type. * Defaults to a threaded chache. * * @return the type of cache for reverse DNS requests */ public String getReverseDNSCacheType() { String value = System.getProperty(REVERSE_DNS_CACHETYPE); if (value != null) { return value; } return getProperty(REVERSE_DNS_CACHETYPE, THREADED_CACHE); } public String getSecureRandomProvider() { String value = System.getProperty("org.globus.random.provider"); if (value != null) { return value; } return getProperty("random.provider", DEFAULT_RANDOM_PROVIDER); } public String getSecureRandomAlgorithm() { String value = System.getProperty("org.globus.random.algorithm"); if (value != null) { return value; } return getProperty("random.algorithm", DEFAULT_RANDOM_ALGORITHM); } /** * Returns the timeout (in milliseconds) for sockets operations. The default * timeout of 30 seconds (30,000 ms) is returned. * * @return The timeout for sockets operations. Defaults to 30 seconds. */ public int getSocketTimeout() { int timeoutInt = -1; // -1 indicates it hasn't been set yet String timeoutStr = System.getProperty(SOCKET_TIMEOUT); if (timeoutStr != null && timeoutStr.length() > 0) { int parsedTimeoutInt = Integer.parseInt(timeoutStr); if (parsedTimeoutInt >= 0) { timeoutInt = parsedTimeoutInt; } } if (timeoutInt == -1) { // Didn't find a system property timeoutStr = getProperty(SOCKET_TIMEOUT); if (timeoutStr != null && timeoutStr.length() > 0) { int parsedTimeoutInt = Integer.parseInt(timeoutStr); if (parsedTimeoutInt >= 0) { timeoutInt = parsedTimeoutInt; } } } if (timeoutInt == -1) { // Didn't find any property at all timeoutInt = 120 * 1000; } return timeoutInt; } public void setSocketTimeout(int socketTimeout) { put(SOCKET_TIMEOUT, String.valueOf(socketTimeout)); } // ------------------------------------------------------- public int getProxyStrength() { return getAsInt("proxy.strength", 512); } public void setProxyStrength(int strength) { put("proxy.strength", String.valueOf(strength)); } public int getProxyLifeTime() { return getAsInt("proxy.lifetime", 12); } public void setProxyLifeTime(int lifeTimeInHours) { put("proxy.lifetime", String.valueOf(lifeTimeInHours)); } protected boolean getAsBoolean(String key, boolean defaultValue) { String tmp = getProperty(key); if (tmp == null) { return defaultValue; } return (tmp.equalsIgnoreCase("yes") || tmp.equalsIgnoreCase("true")); } protected int getAsInt(String label, int defValue) { String tmp = getProperty(label); return (isNullOrEmpty(tmp)) ? defValue : Integer.parseInt(tmp); } protected final static boolean isNullOrEmpty(String tmp) { return (tmp == null || (tmp != null && tmp.length() == 0)); } } ResourceManagerContact.java000066400000000000000000000100761241116057200334630ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/common/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.common; import java.util.StringTokenizer; /** * The purpose of this class is to parse resource manager contact strings. * It can handle literal IPv6 addresses enclosed in square brackets * ('[' and ']'). */ public class ResourceManagerContact { public final static String DEFAULT_SERVICE = "/jobmanager"; public final static int DEFAULT_PORT = 2119; protected String hostName = null; protected int portNumber = -1; protected String serviceName = null; protected String globusDN = null; /* just for the super classes */ protected ResourceManagerContact() { } public ResourceManagerContact(String contact) { parse(contact); } protected void parse(String contact) { char c; int i; i = getHostToken(contact); if (i == -1) { hostName = contact; return; } hostName = contact.substring(0, i); c = contact.charAt(i); if (c == '/') { parseService(contact, i); } else { int j = getToken(contact, i+1); if (j == -1) { portNumber = parsePort(contact.substring(i+1)); return; } portNumber = parsePort(contact.substring(i+1, j)); c = contact.charAt(j); if (c == ':') { globusDN = contact.substring(j+1); return; } else if (c == '/') { parseService(contact, j); } } } private int parsePort(String port) { if (port.length() == 0) { return DEFAULT_PORT; } else { return Integer.parseInt(port); } } private void parseService(String contact, int from) { int pos = contact.indexOf(":", from); if (pos == -1) { serviceName = contact.substring(from); } else { serviceName = contact.substring(from, pos); globusDN = contact.substring(pos+1); } } private int getToken(String contact, int from) { int len = contact.length(); char c; int i; for (i=from;i org.globus.common package Contains classes commonly used by other classes.

    Related Documentation

    For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/000077500000000000000000000000001241116057200255675ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/CertUtil.java000066400000000000000000000265241241116057200301760ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.gsi.util.CertificateIOUtil; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.util.ProxyCertificateUtil; import java.security.Security; import java.security.Provider; import java.security.GeneralSecurityException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.security.cert.X509CRL; import java.security.Principal; import java.io.BufferedReader; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import org.globus.util.I18n; import org.globus.common.CoGProperties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.jce.provider.BouncyCastleProvider; /** * Contains various security-related utility methods. * @deprecated Use the various utils that are used here. */ public class CertUtil { /** * A no-op function that can be used to force the class * to load and initialize. */ public static void init() { CertificateUtil.init(); CertificateLoadUtil.init(); } /** * Installs SecureRandom provider. * This function is automatically called when this class is loaded. */ public static void installSecureRandomProvider() { CertificateUtil.installSecureRandomProvider(); } /** * Sets a provider name to use for loading certificates * and for generating key pairs. * * @param providerName provider name to use. */ public static void setProvider(String providerName) { CertificateUtil.setProvider(providerName); CertificateLoadUtil.setProvider(providerName); } /** * Loads a X509 certificate from the specified input stream. * Input stream must contain DER-encoded certificate. * * @param in the input stream to read the certificate from. * @return X509Certificate the loaded certificate. * @exception GeneralSecurityException if certificate failed to load. */ public static X509Certificate loadCertificate(InputStream in) throws GeneralSecurityException { return CertificateLoadUtil.loadCertificate(in); } /** * Loads an X.509 certificate from the specified file. * The certificate file must be in PEM/Base64 format and start with * "BEGIN CERTIFICATE" and end with "END CERTIFICATE" line. * * @param file the file to load the certificate from. * @return java.security.cert.X509Certificate * the loaded certificate. * @exception IOException if I/O error occurs * @exception GeneralSecurityException if security problems occurs. */ public static X509Certificate loadCertificate(String file) throws IOException, GeneralSecurityException { return CertificateLoadUtil.loadCertificate(file); } /** * Loads multiple X.509 certificates from the specified file. * Each certificate must be in PEM/Base64 format and start with * "BEGIN CERTIFICATE" and end with "END CERTIFICATE" line. * * @param file the certificate file to load the certificate from. * @return an array of certificates loaded from the file. * @exception IOException if I/O error occurs * @exception GeneralSecurityException if security problems occurs. */ public static X509Certificate[] loadCertificates(String file) throws IOException, GeneralSecurityException { return CertificateLoadUtil.loadCertificates(file); } /** * Loads a X.509 certificate from the specified reader. * The certificate contents must start with "BEGIN CERTIFICATE" line * and end with "END CERTIFICATE" line, and be in PEM/Base64 format. * * This function does not close the input stream. * * @param reader the stream from which load the certificate. * @return the loaded certificate or null if there was no certificate * in the stream or the stream is closed. * @exception IOException if I/O error occurs * @exception GeneralSecurityException if security problems occurs. */ public static X509Certificate readCertificate(BufferedReader reader) throws IOException, GeneralSecurityException { return CertificateLoadUtil.readCertificate(reader); } /** * Writes certificate to the specified output stream in PEM format. */ public static void writeCertificate(OutputStream out, X509Certificate cert) throws IOException, CertificateEncodingException { CertificateIOUtil.writeCertificate(out, cert); } /** * Converts DN of the form "CN=A, OU=B, O=C" into Globus * format "/CN=A/OU=B/O=C".
    * This function might return incorrect Globus-formatted ID when one of * the RDNs in the DN contains commas. * @see #toGlobusID(String, boolean) * * @param dn the DN to convert to Globus format. * @return the converted DN in Globus format. */ public static String toGlobusID(String dn) { return CertificateUtil.toGlobusID(dn); } /** * Converts DN of the form "CN=A, OU=B, O=C" into Globus * format "/CN=A/OU=B/O=C" or "/O=C/OU=B/CN=A" depending on the * noreverse option. If noreverse is true * the order of the DN components is not reveresed - "/CN=A/OU=B/O=C" is * returned. If noreverse is false, the order of the * DN components is reversed - "/O=C/OU=B/CN=A" is returned.
    * This function might return incorrect Globus-formatted ID when one of * the RDNs in the DN contains commas. * * @param dn the DN to convert to Globus format. * @param noreverse the direction of the conversion. * @return the converted DN in Globus format. */ public static String toGlobusID(String dn, boolean noreverse) { return CertificateUtil.toGlobusID(dn, noreverse); } /** * Converts the specified principal into Globus format. * If the principal is of unrecognized type a simple string-based * conversion is made using the {@link #toGlobusID(String) toGlobusID()} * function. * * @see #toGlobusID(String) * * @param name the principal to convert to Globus format. * @return the converted DN in Globus format. */ public static String toGlobusID(Principal name) { return CertificateUtil.toGlobusID(name); } // proxy utilies /** * Determines if a specified certificate type indicates a GSI-2, * GSI-3 or GSI-4proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-2 or GSI-3 or GSI-4 proxy, false * otherwise. */ public static boolean isProxy(int certType) { return ProxyCertificateUtil.isProxy(GSIConstants.CertificateType.get(certType)); } /** * Determines if a specified certificate type indicates a * GSI-4 proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-4 proxy, false * otherwise. */ public static boolean isGsi4Proxy(int certType) { return ProxyCertificateUtil.isGsi4Proxy(GSIConstants.CertificateType.get(certType)); } /** * Determines if a specified certificate type indicates a * GSI-3 proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-3 proxy, false * otherwise. */ public static boolean isGsi3Proxy(int certType) { return ProxyCertificateUtil.isGsi3Proxy(GSIConstants.CertificateType.get(certType)); } /** * Determines if a specified certificate type indicates a * GSI-2 proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-2 proxy, false * otherwise. */ public static boolean isGsi2Proxy(int certType) { return ProxyCertificateUtil.isGsi2Proxy(GSIConstants.CertificateType.get(certType)); } /** * Determines if a specified certificate type indicates a * GSI-2 or GSI-3 or GSI=4 limited proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-2 or GSI-3 or GSI-4 limited proxy, * false otherwise. */ public static boolean isLimitedProxy(int certType) { return ProxyCertificateUtil.isLimitedProxy(GSIConstants.CertificateType.get(certType)); } /** * Determines if a specified certificate type indicates a * GSI-3 or GS-4 limited proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-3 or GSI-4 independent proxy, * false otherwise. */ public static boolean isIndependentProxy(int certType) { return ProxyCertificateUtil.isIndependentProxy(GSIConstants.CertificateType.get(certType)); } /** * Determines if a specified certificate type indicates a * GSI-2 or GSI-3 or GSI-4 impersonation proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-2 or GSI-3 or GSI-4 * impersonation proxy, false otherwise. */ public static boolean isImpersonationProxy(int certType) { return ProxyCertificateUtil.isImpersonationProxy(GSIConstants.CertificateType.get(certType)); } /** * Returns a string description of a specified proxy * type. * * @param proxyType the proxy type to get the string * description of. * @return the string description of the proxy type. */ public static String getProxyTypeAsString(int proxyType) { return ProxyCertificateUtil.getProxyTypeAsString(GSIConstants.CertificateType.get(proxyType)); } /** * Checks if GSI-3 mode is enabled. * * @return true if "org.globus.gsi.version" system property * is set to "3". Otherwise, false. */ public static boolean isGsi3Enabled() { return VersionUtil.isGsi3Enabled(); } /** * Checks if GSI-2 mode is enabled. * * @return true if "org.globus.gsi.version" system property * is set to "2". Otherwise, false. */ public static boolean isGsi2Enabled() { return VersionUtil.isGsi2Enabled(); } // CRL Utilities JGLOBUS-91 public static X509CRL loadCrl(String file) throws IOException, GeneralSecurityException { return CertificateLoadUtil.loadCrl(file); } public static X509CRL loadCrl(InputStream in) throws GeneralSecurityException { return CertificateLoadUtil.loadCrl(in); } } CertificateRevocationLists.java000066400000000000000000000176731241116057200336640ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.gsi.stores.ResourceCertStoreParameters; import org.globus.gsi.stores.Stores; import org.globus.gsi.provider.GlobusProvider; import javax.security.auth.x500.X500Principal; import java.security.cert.X509CRLSelector; import java.security.cert.CertStore; import java.security.cert.X509CRL; import java.util.Map; import java.util.Collection; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.ListIterator; import java.util.StringTokenizer; import java.io.File; import org.globus.common.CoGProperties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // COMMENT: what should be used instead? Probably a cert-store. but that doesn't have a refresh or such // COMMENT: We lost the functionality that stuff is only loaded when it didnt' exist or changed /** * @deprecated */ public class CertificateRevocationLists { static { new ProviderLoader(); } private static Log logger = LogFactory.getLog(CertificateRevocationLists.class.getName()); // the list of ca cert locations needed for getDefaultCRL call private static String prevCaCertLocations = null; // the default crl locations list derived from prevCaCertLocations private static String defaultCrlLocations = null; private static CertificateRevocationLists defaultCrl = null; private volatile Map crlIssuerDNMap; private CertificateRevocationLists() {} public X509CRL[] getCrls() { if (this.crlIssuerDNMap == null) { return null; } Collection crls = this.crlIssuerDNMap.values(); return (X509CRL[]) crls.toArray(new X509CRL[crls.size()]); } public Collection getCRLs(X509CRLSelector selector) { Collection issuers = selector.getIssuers(); int size = issuers.size(); Collection retval = new ArrayList(size); // Yup, this stinks. There's loss when we convert from principal to // string. Hence, depending on weird encoding effects, we may miss // some CRLs. Map crlMap = this.crlIssuerDNMap; if (crlMap == null) return retval; for (X500Principal principal : issuers) { String dn = principal.getName(); X509CRL crl = crlMap.get(dn); if (crl != null) { retval.add(crl); } } return retval; } public X509CRL getCrl(String issuerName) { if (this.crlIssuerDNMap == null) { return null; } return (X509CRL)this.crlIssuerDNMap.get(issuerName); } public void refresh() { reload(null); } public synchronized void reload(String locations) { if (locations == null) { return; } StringTokenizer tokens = new StringTokenizer(locations, ","); Map newCrlIssuerDNMap = new HashMap(); while(tokens.hasMoreTokens()) { try { String location = tokens.nextToken().toString().trim(); CertStore tmp = Stores.getCRLStore("file:" + location + "/*.r*"); Collection coll = (Collection) tmp.getCRLs(new X509CRLSelector()); for (X509CRL crl : coll) { newCrlIssuerDNMap.put(crl.getIssuerX500Principal().getName(), crl); } } catch (Exception e) { throw new RuntimeException(e); } } this.crlIssuerDNMap = newCrlIssuerDNMap; } public static CertificateRevocationLists getCertificateRevocationLists(String locations) { CertificateRevocationLists crl = new CertificateRevocationLists(); crl.reload(locations); return crl; } public static synchronized CertificateRevocationLists getDefaultCertificateRevocationLists() { return getDefault(); } public static void setDefaultCertificateRevocationList(CertificateRevocationLists crl) { defaultCrl = crl; } public static synchronized CertificateRevocationLists getDefault() { if (defaultCrl == null) { defaultCrl = new DefaultCertificateRevocationLists(); } defaultCrl.refresh(); return defaultCrl; } public String toString() { if (this.crlIssuerDNMap == null) { return "crl list is empty"; } else { return this.crlIssuerDNMap.toString(); } } private static class DefaultCertificateRevocationLists extends CertificateRevocationLists { private final long lifetime; private long lastRefresh; public DefaultCertificateRevocationLists() { lifetime = CoGProperties.getDefault().getCertCacheLifetime(); } public void refresh() { long now = System.currentTimeMillis(); if (lastRefresh + lifetime <= now) { reload(getDefaultCRLLocations()); lastRefresh = now; } } private static synchronized String getDefaultCRLLocations() { String caCertLocations = CoGProperties.getDefault().getCaCertLocations(); if (prevCaCertLocations == null || !prevCaCertLocations.equals(caCertLocations)) { if (caCertLocations == null) { logger.debug("No CA cert locations specified"); prevCaCertLocations = null; defaultCrlLocations = null; } else { StringTokenizer tokens = new StringTokenizer(caCertLocations, ","); File crlFile = null; LinkedList crlDirs = new LinkedList(); while(tokens.hasMoreTokens()) { String crlFileName = tokens.nextToken().toString().trim(); crlFile = new File(crlFileName); if (crlFile.isDirectory()) { // all all directories } else if (crlFile.isFile()) { // add parent directory crlFileName = crlFile.getParent(); } else { // skip other types continue; } // don't add directories twice if (crlFileName != null && !crlDirs.contains(crlFileName)) { crlDirs.add(crlFileName); } } ListIterator iterator = crlDirs.listIterator(0); String locations = null; while (iterator.hasNext()) { if (locations == null) { locations = (String)iterator.next(); } else { locations = locations + "," + (String)iterator.next(); } } // set defaults prevCaCertLocations = caCertLocations; defaultCrlLocations = locations; } } return defaultCrlLocations; } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/CredentialException.java000066400000000000000000000020621241116057200323630ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import java.security.GeneralSecurityException; /** * Exception signaling a credential failure. * * @version ${version} * @since 1.0 */ public class CredentialException extends GeneralSecurityException { public CredentialException(String msg) { super(msg); } public CredentialException(String msg, Throwable ex) { super(msg, ex); } public CredentialException(Throwable ex) { super(ex); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/GSIConstants.java000066400000000000000000000207051241116057200307550ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; /** * Defines common constants used by GSI. */ // COMMENT: 2 ways to defined a certificate type: integer and enum. public interface GSIConstants { /** The character sent on the wire to request delegation */ public static final char DELEGATION_CHAR = 'D'; /** Null ciphersuite supported in older Globus servers */ public static final String[] GLOBUS_CIPHER = {"SSL_RSA_WITH_NULL_MD5"}; /** Indicates no delegation * @deprecated Use DelegationType.NONE instead */ public static final int DELEGATION_NONE = 1; /** Indicates limited delegation. * Depending on the settings it might mean GSI-2 limited delegation * or GSI-3 limited delegation. * @deprecated Use DelegationType.LIMITED instead */ public static final int DELEGATION_LIMITED = 2; /** Indicates full delegation. * Depending on the settings it might mean GSI-2 full delegation * or GSI-3 impersonation delegation. * @deprecated Use DelegationType.FULL instead */ public static final int DELEGATION_FULL = 3; /** Indicates GSI mode (allows for delegation during authentication). */ public static final Integer MODE_GSI = new Integer(1); /** Indicates SSL compatibility mode (does not allow for delegation * during authentication). */ public static final Integer MODE_SSL = new Integer(2); /** Indicates full delegation. */ public static final Integer DELEGATION_TYPE_FULL = new Integer(GSIConstants.DELEGATION_FULL); /** Indicates limited delegation. */ public static final Integer DELEGATION_TYPE_LIMITED = new Integer(GSIConstants.DELEGATION_LIMITED); /** Indicates End-Entity Certificate, e.g. user certificate * @deprecated Use CertificateType.EEC instead */ public static final int EEC = 3; /** Indicates Certificate Authority certificate * @deprecated Use CertificateType.CA instead */ public static final int CA = 4; /** Indicates legacy full Globus proxy * @deprecated Use CertificateType.GSI_2_PROXY instead */ public static final int GSI_2_PROXY = 10; /** Indicates legacy limited Globus proxy * @deprecated Use CertificateType.GSI_2_LIMITED_PROXY instead */ public static final int GSI_2_LIMITED_PROXY = 11; /** Indicates proxy draft compliant restricted proxy. * A proxy with embedded policy. * @deprecated Use CertificateType.GSI_3_RESTRICTED_PROXY instead */ public static final int GSI_3_RESTRICTED_PROXY = 12; /** Indicates proxy draft compliant independent proxy. * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#INDEPENDENT * ProxyPolicy.INDEPENDENT} policy language OID. * @deprecated Use CertificateType.GSI_3_INDEPENDENT_PROXY instead */ public static final int GSI_3_INDEPENDENT_PROXY = 13; /** Indicates proxy draft compliant impersonation proxy. * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#IMPERSONATION * ProxyPolicy.IMPERSONATION} policy language OID. * @deprecated Use CertificateType.GSI_3_IMPERSONATION_PROXY instead */ public static final int GSI_3_IMPERSONATION_PROXY = 14; /** Indicates proxy draft compliant limited impersonation proxy. * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#LIMITED * ProxyPolicy.LIMITED} policy language OID. * @deprecated Use CertificateType.GSI_3_RESTRICTED_PROXY instead */ public static final int GSI_3_LIMITED_PROXY = 15; /** Indicates RFC 3820 compliant restricted proxy. * A proxy with embedded policy. * @deprecated Use CertificateType.GSI_4_RESTRICTED_PROXY instead */ public static final int GSI_4_RESTRICTED_PROXY = 16; /** Indicates RFC 3820 compliant independent proxy. * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#INDEPENDENT * ProxyPolicy.INDEPENDENT} policy language OID. * @deprecated Use CertificateType.GSI_4_INDEPENDENT_PROXY instead */ public static final int GSI_4_INDEPENDENT_PROXY = 17; /** Indicates RFC 3820 compliant impersonation proxy. * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#IMPERSONATION * ProxyPolicy.IMPERSONATION} policy language OID. * @deprecated Use CertificateType.GSI_4_IMPERSONATION_PROXY instead */ public static final int GSI_4_IMPERSONATION_PROXY = 18; /** Indicates RFC 3820 compliant limited impersonation proxy. * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#LIMITED * ProxyPolicy.LIMITED} policy language OID. * @deprecated Use CertificateType.GSI_4_LIMITED_PROXY instead */ public static final int GSI_4_LIMITED_PROXY = 19; /** GSI Transport protection method type * that will be used or was used to protect the request. * Can be set to: * {@link GSIConstants#SIGNATURE SIGNATURE} or * {@link GSIConstants#ENCRYPTION ENCRYPTION} or * {@link GSIConstants#NONE NONE}. */ public static final String GSI_TRANSPORT = "org.globus.security.transport.type"; /** integrity message protection method. */ public static final Integer SIGNATURE = new Integer(1); /** privacy message protection method. */ public static final Integer ENCRYPTION = new Integer(2); /** none message protection method. */ public static final Integer NONE = new Integer(Integer.MAX_VALUE); /** * It is used to set a list of trusted certificates * to use during authentication (by default, the trusted certificates * are loaded from a standard location) The value is an instance of * {@link org.globus.gsi.TrustedCertificates TrustedCertificates} */ public static final String TRUSTED_CERTIFICATES = "org.globus.security.trustedCertifictes"; /** * It is set to a Boolean value and if false, * client authorization requirement with delegation is disabled. By * default, client side authorization (to authorize the server) is * required for delegation of credentials. */ public static final String AUTHZ_REQUIRED_WITH_DELEGATION = "org.globus.security.authz.required.delegation"; /** * Enumeration of Certificate types used by the Globus security provider. */ // COMMENT: TODO: replace the the cert type constants with this enum public enum CertificateType { EEC(3), CA(4), GSI_2_PROXY(10), GSI_2_LIMITED_PROXY(11), GSI_3_RESTRICTED_PROXY(12), GSI_3_INDEPENDENT_PROXY(13), GSI_3_IMPERSONATION_PROXY(14), GSI_3_LIMITED_PROXY(15), GSI_4_RESTRICTED_PROXY(16), GSI_4_INDEPENDENT_PROXY(17), GSI_4_IMPERSONATION_PROXY(18), GSI_4_LIMITED_PROXY(19), UNDEFINED(-1); private int code; private CertificateType(int c) { code = c; } public int getCode() { return code; } public static CertificateType get(int code) { for (CertificateType tmp : CertificateType.values()) { if (tmp.getCode() == code) { return tmp; } } throw new IllegalArgumentException("invalid certificate type code"); } } /** * Enumeration of Certificate types used by the Globus security provider. */ // COMMENT: TODO: replace the the delegation type constants with this enum public enum DelegationType { NONE(1), LIMITED(2), FULL(3); private int code; private DelegationType(int c) { code = c; } public int getCode() { return code; } public static DelegationType get(int code) { for (DelegationType tmp : DelegationType.values()) { if (tmp.getCode() == code) { return tmp; } } throw new IllegalArgumentException("invalid delegation type code"); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/GlobusCredential.java000066400000000000000000000273701241116057200316710ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.trustmanager.X509ProxyCertPathValidator; import org.globus.gsi.stores.ResourceCertStoreParameters; import org.globus.gsi.stores.ResourceSigningPolicyStore; import org.globus.gsi.stores.ResourceSigningPolicyStoreParameters; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.provider.KeyStoreParametersFactory; import java.io.File; import java.security.cert.CertStore; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.security.cert.CertificateEncodingException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import org.globus.common.ChainedIOException; import org.globus.common.CoGProperties; import org.globus.gsi.bc.BouncyCastleUtil; /** * Provides a Java object representation of Globus credential which can include the proxy file or host * certificates. * @deprecated */ public class GlobusCredential implements Serializable { private Log logger = LogFactory.getLog(getClass()); private X509Credential cred; private static GlobusCredential defaultCred; private static transient long credentialLastModified = -1; // indicates if default credential was explicitely set // and if so - if the credential expired it try // to load the proxy from a file. private static transient boolean credentialSet = false; private static transient File credentialFile = null; static { new ProviderLoader(); } /** * Creates a GlobusCredential from a private key and a certificate chain. * * @param key * the private key * @param certs * the certificate chain */ public GlobusCredential(PrivateKey key, X509Certificate[] certs) { cred = new X509Credential(key, certs); } /** * Creates a GlobusCredential from a proxy file. * * @param proxyFile * the file to load the credential from. * @exception GlobusCredentialException * if the credential failed to load. */ public GlobusCredential(String proxyFile) throws GlobusCredentialException { try { cred = new X509Credential(proxyFile); } catch (Exception e) { throw new GlobusCredentialException(GlobusCredentialException.FAILURE, e.getMessage(), e); } } /** * Creates a GlobusCredential from certificate file and a unencrypted key file. * * @param certFile * the file containing the certificate * @param unencryptedKeyFile * the file containing the private key. The key must be unencrypted. * @exception GlobusCredentialException * if something goes wrong. */ public GlobusCredential(String certFile, String unencryptedKeyFile) throws GlobusCredentialException { if (certFile == null || unencryptedKeyFile == null) { throw new IllegalArgumentException(); } try { cred = new X509Credential(certFile, unencryptedKeyFile); } catch (Exception e) { throw new GlobusCredentialException(GlobusCredentialException.FAILURE, e.getMessage(), e); } } /** * Creates a GlobusCredential from an input stream. * * @param input * the stream to load the credential from. * @exception GlobusCredentialException * if the credential failed to load. */ public GlobusCredential(InputStream input) throws GlobusCredentialException { try { cred = new X509Credential(input); } catch (Exception e) { throw new GlobusCredentialException(GlobusCredentialException.FAILURE, e.getMessage(), e); } } /** * Saves the credential into a specified output stream. The self-signed certificates in the certificate * chain will not be saved. The output stream should always be closed after calling this function. * * @param out * the output stream to write the credential to. * @exception IOException * if any error occurred during saving. */ public void save(OutputStream out) throws IOException { try { cred.save(out); } catch (CertificateEncodingException e) { throw new ChainedIOException(e.getMessage(), e); } } /** * Verifies the validity of the credentials. All certificate path validation is performed using trusted * certificates in default locations. * * @exception GlobusCredentialException * if one of the certificates in the chain expired or if path validiation fails. */ public void verify() throws GlobusCredentialException { try { String caCertsLocation = "file:" + CoGProperties.getDefault().getCaCertLocations(); String crlPattern = caCertsLocation + "/*.r*"; String sigPolPattern = caCertsLocation + "/*.signing_policy"; KeyStore keyStore = KeyStore.getInstance(GlobusProvider.KEYSTORE_TYPE, GlobusProvider.PROVIDER_NAME); CertStore crlStore = CertStore.getInstance(GlobusProvider.CERTSTORE_TYPE, new ResourceCertStoreParameters(null,crlPattern)); ResourceSigningPolicyStore sigPolStore = new ResourceSigningPolicyStore(new ResourceSigningPolicyStoreParameters(sigPolPattern)); keyStore.load(KeyStoreParametersFactory.createTrustStoreParameters(caCertsLocation)); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, crlStore, sigPolStore, false); X509ProxyCertPathValidator validator = new X509ProxyCertPathValidator(); validator.engineValidate(CertificateUtil.getCertPath(this.cred.getCertificateChain()), parameters); } catch (Exception e) { e.printStackTrace(); throw new GlobusCredentialException(GlobusCredentialException.FAILURE, e.getMessage(), e); } } /** * Returns the identity certificate of this credential. The identity certificate is the first certificate * in the chain that is not an impersonation proxy certificate. * * @return X509Certificate the identity cert. Null, if unable to get the identity certificate * (an error occurred) */ public X509Certificate getIdentityCertificate() { return cred.getIdentityCertificate(); } /** * Returns the path length constraint. The shortest length in the chain of certificates is returned as the * credential's path length. * * @return The path length constraint of the credential. -1 is any error occurs. */ public int getPathConstraint() { return cred.getPathConstraint(); } /** * Returns the identity of this credential. * * @see #getIdentityCertificate() * * @return The identity cert in Globus format (e.g. /C=US/..). Null, if unable to get the identity (an * error occurred) */ public String getIdentity() { return cred.getIdentity(); } /** * Returns the private key of this credential. * * @return PrivateKey the private key */ public PrivateKey getPrivateKey() { try { return (PrivateKey) cred.getPrivateKey(); } catch (Exception e) { return null; } } /** * Returns the certificate chain of this credential. * * @return X509Certificate [] the certificate chain */ public X509Certificate[] getCertificateChain() { return cred.getCertificateChain(); } /** * Returns the number of certificates in the credential without the self-signed certificates. * * @return number of certificates without counting self-signed certificates */ public int getCertNum() { return cred.getCertNum(); } /** * Returns strength of the private/public key in bits. * * @return strength of the key in bits. Returns -1 if unable to determine it. */ public int getStrength() { try { return cred.getStrength(); } catch (Exception e) { return -1; } } /** * Returns the subject DN of the first certificate in the chain. * * @return subject DN. */ public String getSubject() { return cred.getSubject(); } /** * Returns the issuer DN of the first certificate in the chain. * * @return issuer DN. */ public String getIssuer() { return cred.getIssuer(); } /** * Returns the certificate type of the first certificate in the chain. Returns -1 if unable to determine * the certificate type (an error occurred) * * @see BouncyCastleUtil#getCertificateType(X509Certificate) * * @return the type of first certificate in the chain. -1 if unable to determine the certificate type. */ public int getProxyType() { return cred.getProxyType().getCode(); } /** * Returns time left of this credential. The time left of the credential is based on the certificate with * the shortest validity time. * * @return time left in seconds. Returns 0 if the certificate has expired. */ public long getTimeLeft() { return cred.getTimeLeft(); } /** * Returns the default credential. The default credential is usually the user proxy certificate.
    * The credential will be loaded on the initial call. It must not be expired. All subsequent calls to this * function return cached credential object. Once the credential is cached, and the underlying file * changes, the credential will be reloaded. * * @return the default credential. * @exception GlobusCredentialException * if the credential expired or some other error with the credential. */ public synchronized static GlobusCredential getDefaultCredential() throws GlobusCredentialException { if (defaultCred == null) { reloadDefaultCredential(); } else if (!credentialSet) { if (credentialFile.lastModified() == credentialLastModified) { defaultCred.verify(); } else { defaultCred = null; reloadDefaultCredential(); } } return defaultCred; } private static void reloadDefaultCredential() throws GlobusCredentialException { String proxyLocation = CoGProperties.getDefault().getProxyFile(); defaultCred = new GlobusCredential(proxyLocation); credentialFile = new File(proxyLocation); credentialLastModified = credentialFile.lastModified(); defaultCred.verify(); } /** * Sets default credential. * * @param cred * the credential to set a default. */ public synchronized static void setDefaultCredential(GlobusCredential cred) { credentialSet = (cred != null); } public String toString() { return cred.toString(); } } GlobusCredentialException.java000066400000000000000000000041741241116057200334660ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import java.text.MessageFormat; import java.util.ResourceBundle; import java.util.MissingResourceException; /** * Encapsulates the exceptions caused * by various errors in/problems with Globus proxies. */ public class GlobusCredentialException extends Exception { public static final int FAILURE = -1; public static final int EXPIRED = 1; public static final int DEFECTIVE = 2; public static final int IO_ERROR = 3; public static final int SEC_ERROR = 3; private static ResourceBundle resources; static { try { resources = ResourceBundle.getBundle("org.globus.gsi.errors"); } catch (MissingResourceException e) { throw new RuntimeException(e.getMessage()); } } private int errorCode = FAILURE; public GlobusCredentialException(int errorCode, String msgId, Throwable root) { this(errorCode, msgId, null, root); } public GlobusCredentialException(int errorCode, String msgId, Object [] args) { this(errorCode, msgId, args, null); } public GlobusCredentialException(int errorCode, String msgId, Object [] args, Throwable root) { super(getMessage(msgId, args), root); this.errorCode = errorCode; } public int getErrorCode() { return this.errorCode; } private static String getMessage(String msgId, Object[] args) { try { return MessageFormat.format(resources.getString(msgId), args); } catch (MissingResourceException e) { throw new RuntimeException(msgId); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/OpenSSLKey.java000066400000000000000000000461221241116057200303730ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.gsi.util.FileUtil; import org.globus.gsi.util.PEMUtil; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.io.Writer; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.SecureRandom; import java.util.StringTokenizer; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Base64; /** * Represents a OpenSSL-style PEM-formatted private key. It supports encryption and decryption of the key. Currently, * only RSA keys are supported, and only TripleDES encryption is supported. *

    * This is based on work done by Ming Yung at DSTC. * * @version ${version} * @since 1.0 */ public abstract class OpenSSLKey implements Serializable { private static final String HEADER = "-----BEGIN RSA PRIVATE KEY-----"; /* Key algorithm: RSA, DSA */ private String keyAlg; /* Current state of this key class */ private boolean isEncrypted; // base64 encoded key value private byte[] encodedKey; private PrivateKey intKey; private byte[] ivData; private transient IvParameterSpec initializationVector; /* * String representation of the encryption algorithm: * DES-EDE3-CBC, AES-256-CBC, etc. */ private String encAlgStr; /* * Java string representation of the encryption algorithm: * DES, DESede, AES. */ private String encAlg; private int keyLength = -1; private int ivLength = -1; // ASN.1 encoded key value private byte[] keyData; /** * Reads a OpenSSL private key from the specified input stream. * The private key must be PEM encoded and can be encrypted. * * @param is input stream with OpenSSL key in PEM format. * @throws IOException if I/O problems. * @throws GeneralSecurityException if problems with the key */ public OpenSSLKey(InputStream is) throws IOException, GeneralSecurityException { InputStreamReader isr = new InputStreamReader(is); try { readPEM(isr); } finally { isr.close(); } } /** * Reads a OpenSSL private key from the specified file. * The private key must be PEM encoded and can be encrypted. * * @param file file containing the OpenSSL key in PEM format. * @throws IOException if I/O problems. * @throws GeneralSecurityException if problems with the key */ public OpenSSLKey(String file) throws IOException, GeneralSecurityException { FileReader f = new FileReader(file); try { readPEM(f); } finally { f.close(); } } /** * Converts a RSAPrivateCrtKey into OpenSSL key. * * @param key private key - must be a RSAPrivateCrtKey */ public OpenSSLKey(PrivateKey key) { this.intKey = key; this.isEncrypted = false; this.keyData = getEncoded(key); this.encodedKey = null; } /** * Initializes the OpenSSL key from raw byte array. * * @param algorithm the algorithm of the key. Currently only RSA algorithm is supported. * @param data the DER encoded key data. If RSA algorithm, the key must be in PKCS#1 format. * @throws GeneralSecurityException if any security problems. */ public OpenSSLKey(String algorithm, byte[] data) throws GeneralSecurityException { if (data == null) { throw new IllegalArgumentException("Data is null"); } this.keyData = new byte[data.length]; System.arraycopy(data, 0, this.keyData, 0, data.length); this.isEncrypted = false; this.intKey = getKey(algorithm, data); } protected byte[] getEncoded() { return this.keyData; } private void readPEM(Reader rd) throws IOException, GeneralSecurityException { StringBuilder builder = new StringBuilder(); BufferedReader in = new BufferedReader(rd); try { parseKeyAlgorithm(in); builder.append(extractEncryptionInfo(in)); builder.append(extractKey(in)); } finally { in.close(); } this.encodedKey = builder.toString().getBytes(); if (isEncrypted()) { this.keyData = null; } else { this.keyData = Base64.decode(encodedKey); this.intKey = getKey(keyAlg, keyData); } } private String extractKey(BufferedReader in) throws IOException { StringBuilder builder = new StringBuilder(); String next = in.readLine(); while (next != null) { if (next.startsWith("-----END")) { break; } builder.append(next); next = in.readLine(); } return builder.toString(); } private String extractEncryptionInfo(BufferedReader in) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String next = in.readLine(); if (next != null && next.startsWith("Proc-Type: 4,ENCRYPTED")) { this.isEncrypted = true; next = in.readLine(); if (next != null) { parseEncryptionInfo(next); } in.readLine(); } else { this.isEncrypted = false; sb.append(next); } return sb.toString(); } private void parseKeyAlgorithm(BufferedReader in) throws IOException, InvalidKeyException { String next = in.readLine(); while (next != null) { if (next.indexOf("PRIVATE KEY") != -1) { keyAlg = getKeyAlgorithm(next); break; } next = in.readLine(); } if (next == null) { throw new InvalidKeyException("noPrivateKey"); } if (keyAlg == null) { throw new InvalidKeyException("algNotSup"); } } /** * Check if the key was encrypted or not. * * @return true if the key is encrypted, false * otherwise. */ public boolean isEncrypted() { return this.isEncrypted; } /** * Decrypts the private key with given password. * Does nothing if the key is not encrypted. * * @param password password to decrypt the key with. * @throws GeneralSecurityException whenever an error occurs during decryption. */ public void decrypt(String password) throws GeneralSecurityException { decrypt(password.getBytes()); } /** * Decrypts the private key with given password. * Does nothing if the key is not encrypted. * * @param password password to decrypt the key with. * @throws GeneralSecurityException whenever an error occurs during decryption. */ public void decrypt(byte[] password) throws GeneralSecurityException { if (!isEncrypted()) { return; } byte[] enc = Base64.decode(this.encodedKey); SecretKeySpec key = getSecretKey(password, this.initializationVector.getIV()); Cipher cipher = getCipher(); cipher.init(Cipher.DECRYPT_MODE, key, this.initializationVector); enc = cipher.doFinal(enc); this.intKey = getKey(this.keyAlg, enc); this.keyData = enc; this.isEncrypted = false; this.encodedKey = null; } /** * Encrypts the private key with given password. * Does nothing if the key is encrypted already. * * @param password password to encrypt the key with. * @throws GeneralSecurityException whenever an error occurs during encryption. */ public void encrypt(String password) throws GeneralSecurityException { encrypt(password.getBytes()); } /** * Encrypts the private key with given password. * Does nothing if the key is encrypted already. * * @param password password to encrypt the key with. * @throws GeneralSecurityException whenever an error occurs during encryption. */ public void encrypt(byte[] password) throws GeneralSecurityException { if (isEncrypted()) { return; } if (this.encAlg == null) { setEncryptionAlgorithm("DES-EDE3-CBC"); } if (this.ivData == null) { generateIV(); } Key key = getSecretKey(password, this.initializationVector.getIV()); Cipher cipher = getCipher(); cipher.init(Cipher.ENCRYPT_MODE, key, this.initializationVector); /* encrypt the raw PKCS11 */ this.keyData = cipher.doFinal(getEncoded(this.intKey)); this.isEncrypted = true; this.encodedKey = null; } /** * Sets algorithm for encryption. * * @param alg algorithm for encryption * @throws GeneralSecurityException if algorithm is not supported */ public void setEncryptionAlgorithm(String alg) throws GeneralSecurityException { setAlgorithmSettings(alg); } /** * Returns the JCE (RSAPrivateCrtKey) key. * * @return the private key, null if the key * was not decrypted yet. */ public PrivateKey getPrivateKey() { return this.intKey; } /** * Writes the private key to the specified output stream in PEM * format. If the key was encrypted it will be encoded as an encrypted * RSA key. If not, it will be encoded as a regular RSA key. * * @param output output stream to write the key to. * @throws IOException if I/O problems writing the key */ public void writeTo(OutputStream output) throws IOException { output.write(toPEM().getBytes()); } /** * Writes the private key to the specified writer in PEM format. * If the key was encrypted it will be encoded as an encrypted * RSA key. If not, it will be encoded as a regular RSA key. * * @param w writer to output the key to. * @throws IOException if I/O problems writing the key */ public void writeTo(Writer w) throws IOException { w.write(toPEM()); } /** * Writes the private key to the specified file in PEM format. * If the key was encrypted it will be encoded as an encrypted * RSA key. If not, it will be encoded as a regular RSA key. * * @param file file to write the key to. * @throws IOException if I/O problems writing the key */ public void writeTo(String file) throws IOException { File privateKey = FileUtil.createFile(file); // JGLOBUS-96 try{ privateKey.setReadable(false, true);//setOwnerAccessOnly(file); privateKey.setWritable(false, true);//setOwnerAccessOnly(file); }catch(SecurityException e){ } PrintWriter p = new PrintWriter(new FileOutputStream(privateKey)); try { p.write(toPEM()); } finally { p.close(); } } /* * Returns DER encoded byte array (PKCS#1). */ protected abstract byte[] getEncoded(PrivateKey key); /* * Returns PrivateKey object initialized from give byte array (in PKCS#1 format) */ protected abstract PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException; protected String getProvider() { return null; } private Cipher getCipher() throws GeneralSecurityException { String provider = getProvider(); if (provider == null) { return Cipher.getInstance(this.encAlg + "/CBC/PKCS5Padding"); } else { return Cipher.getInstance(this.encAlg + "/CBC/PKCS5Padding", provider); } } private String getKeyAlgorithm(String line) { if (line.contains("RSA")) { return "RSA"; } else if (line.contains("DSA")) { return "DSA"; } else { return null; } } private void parseEncryptionInfo(String line) throws GeneralSecurityException { // TODO: can make this better String keyInfo = line.substring(10); StringTokenizer tknz = new StringTokenizer(keyInfo, ",", false); // set algorithm settings setAlgorithmSettings(tknz.nextToken()); // set IV setIV(tknz.nextToken()); } private void setAlgorithmSettings(String alg) throws GeneralSecurityException { if (alg.equals("DES-EDE3-CBC")) { this.encAlg = "DESede"; this.keyLength = OpenSSLKeyConstants.DES_EDE3_CBC_KEY_LENGTH; this.ivLength = OpenSSLKeyConstants.DES_EDE3_CBC_IV_LENGTH; } else if (alg.equals("AES-128-CBC")) { this.encAlg = "AES"; this.keyLength = OpenSSLKeyConstants.AES_128_CBC_KEY_LENGTH; this.ivLength = OpenSSLKeyConstants.AES_128_CBC_IV_LENGTH; } else if (alg.equals("AES-192-CBC")) { this.encAlg = "AES"; this.keyLength = OpenSSLKeyConstants.AES_192_CBC_KEY_LENGTH; this.ivLength = OpenSSLKeyConstants.AES_192_CBC_IV_LENGTH; } else if (alg.equals("AES-256-CBC")) { this.encAlg = "AES"; this.keyLength = OpenSSLKeyConstants.AES_256_CBC_KEY_LENGTH; this.ivLength = OpenSSLKeyConstants.AES_256_CBC_IV_LENGTH; } else if (alg.equals("DES-CBC")) { this.encAlg = "DES"; this.keyLength = OpenSSLKeyConstants.DES_CBC_KEY_LENGTH; this.ivLength = OpenSSLKeyConstants.DES_CBC_IV_LENGTH; } else { throw new GeneralSecurityException("unsupported Enc algorithm " + alg); } this.encAlgStr = alg; } private void setIV(String s) throws GeneralSecurityException { int len = s.length() / 2; if (len != this.ivLength) { String err = "ivLength"; //JGLOBUS-91 throw new GeneralSecurityException(err); } byte[] ivBytes = new byte[len]; for (int j = 0; j < len; j++) { ivBytes[j] = (byte) Integer.parseInt(s.substring(j * 2, j * 2 + 2), 16); } setIV(ivBytes); } private void generateIV() { byte[] b = new byte[this.ivLength]; SecureRandom sr = new SecureRandom(); //.getInstance("PRNG"); sr.nextBytes(b); setIV(b); } private void setIV(byte[] data) { ivData = data; initializationVector = new IvParameterSpec(data); } private SecretKeySpec getSecretKey(byte[] pwd, byte[] keyInitializationVector) throws GeneralSecurityException { byte[] key = new byte[this.keyLength]; int offset = 0; int bytesNeeded = this.keyLength; MessageDigest md5 = MessageDigest.getInstance("MD5"); while (true) { md5.update(pwd); md5.update(keyInitializationVector, 0, 8); byte[] b = md5.digest(); int len = (bytesNeeded > b.length) ? b.length : bytesNeeded; System.arraycopy(b, 0, key, offset, len); offset += len; // check if we need any more bytesNeeded = key.length - offset; if (bytesNeeded == 0) { break; } // do another round md5.reset(); md5.update(b); } return new SecretKeySpec(key, this.encAlg); } // ------------------------------------------- /* * Converts to PEM encoding. * Assumes keyData is initialized. */ private String toPEM() { byte[] data = (this.keyData == null) ? this.encodedKey : Base64.encode(this.keyData); String header = HEADER; if (isEncrypted()) { StringBuffer buf = new StringBuffer(header); buf.append(PEMUtil.LINE_SEP); buf.append("Proc-Type: 4,ENCRYPTED"); buf.append(PEMUtil.LINE_SEP); buf.append("DEK-Info: ").append(this.encAlgStr); buf.append(",").append(PEMUtil.toHex(initializationVector.getIV())); buf.append(PEMUtil.LINE_SEP); header = buf.toString(); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { PEMUtil.writeBase64(out, header, data, "-----END RSA PRIVATE KEY-----"); } catch (IOException e) { // JGLOBUS-91 throw new RuntimeException("Unexpected error", e); } return new String(out.toByteArray()); } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); if(ivData != null) { initializationVector = new IvParameterSpec(ivData); } } @Override public boolean equals(Object other) { if(other == this) { return true; } if(!(other instanceof OpenSSLKey)) { return false; } OpenSSLKey otherKey = (OpenSSLKey) other; return this.isEncrypted == otherKey.isEncrypted && objectsEquals(this.keyAlg, otherKey.keyAlg) && Arrays.areEqual(this.encodedKey, otherKey.encodedKey) && objectsEquals(this.intKey, otherKey.intKey) && Arrays.areEqual(this.ivData, otherKey.ivData) && objectsEquals(this.encAlgStr, otherKey.encAlgStr) && objectsEquals(this.encAlg, otherKey.encAlg) && Arrays.areEqual(this.keyData, otherKey.keyData); } // Equivalent to Java 7 Objects#equals method; may be replaced when // Java 7 is adopted private static boolean objectsEquals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); } @Override public int hashCode() { return (isEncrypted ? 1 : 0) ^ (keyAlg == null ? 0 : keyAlg.hashCode()) ^ (encodedKey == null ? 0 : encodedKey.hashCode()) ^ (intKey == null ? 0 : intKey.hashCode()) ^ (ivData == null ? 0 : ivData.hashCode()) ^ (encAlgStr == null ? 0 : encAlgStr.hashCode()) ^ (encAlg == null ? 0 : encAlg.hashCode()) ^ (keyData == null ? 0 : keyData.hashCode()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/OpenSSLKeyConstants.java000066400000000000000000000027051241116057200322670ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Jan 21, 2010 * Time: 10:32:19 AM * To change this template use File | Settings | File Templates. */ public final class OpenSSLKeyConstants { public static final int DES_EDE3_CBC_KEY_LENGTH = 24; public static final int DES_EDE3_CBC_IV_LENGTH = 8; public static final int AES_128_CBC_KEY_LENGTH = 16; public static final int AES_128_CBC_IV_LENGTH = 16; public static final int AES_192_CBC_KEY_LENGTH = 24; public static final int AES_192_CBC_IV_LENGTH = 16; public static final int AES_256_CBC_KEY_LENGTH = 32; public static final int AES_256_CBC_IV_LENGTH = 16; public static final int DES_CBC_KEY_LENGTH = 8; public static final int DES_CBC_IV_LENGTH = 8; private OpenSSLKeyConstants() { //should not be instantiated; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/ProviderLoader.java000066400000000000000000000005141241116057200313530ustar00rootroot00000000000000package org.globus.gsi; import org.globus.gsi.provider.GlobusProvider; import java.security.Security; public class ProviderLoader { private GlobusProvider provider; public ProviderLoader(){ provider = new GlobusProvider(); Security.addProvider(provider); } public GlobusProvider getProvider(){ return provider; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/SigningPolicy.java000066400000000000000000000110711241116057200312100ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.gsi.util.CertificateUtil; import java.util.List; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.security.auth.x500.X500Principal; import org.globus.gsi.SigningPolicyParser; /** * Represents a signing policy associated with a particular CA. The signing policy defines a list of distinguished * names which are allowed to sign certificates for a particular Certificate Authority subject distinguished name. * * @version ${version} * @since 1.0 */ // COMMENT: BCB: new method signatures public class SigningPolicy { private X500Principal caSubject; private List allowedDNs; /** * Create a signing policy for the supplied subject which allows the supplied list of DNs to sign certificates. * * @param caSubjectDN The DN for the subject to which this policy applies. * @param allowedDNs The list of DNs which can sign certs for this subject. */ public SigningPolicy(X500Principal caSubjectDN, String[] allowedDNs) { if ((caSubjectDN == null) || (allowedDNs == null)) { throw new IllegalArgumentException(); } this.caSubject = caSubjectDN; int numberOfDNs = allowedDNs.length; this.allowedDNs = new Vector(numberOfDNs); for (String anAllowedDNs : allowedDNs) { this.allowedDNs.add(SigningPolicyParser.getPattern(anAllowedDNs)); } } /** * Create a signing policy for the supplied subject which allows subjects whose DNs match one of the supplied * patterns to sign certificates. * * @param caSubjectDN The DN for the subject to which this policy applies. * @param allowedDNs A list of patterns to which to compare signing entity DNs. */ // COMMENT: allowedDNs != null is new, and causes the test to fail public SigningPolicy(X500Principal caSubjectDN, List allowedDNs) { if ((caSubjectDN == null) || (allowedDNs == null)) { throw new IllegalArgumentException(); } this.caSubject = caSubjectDN; this.allowedDNs = allowedDNs; } /** * Get CA subject DN for which this signing policy is defined. * * @return returns the CA subject */ public X500Principal getCASubjectDN() { return this.caSubject; } /** * Ascertains if the subjectDN is valid against this policy. * * @param subject Subject DN to be validated * @return true if the DN is valid under this policy and false if it is not */ public boolean isValidSubject(X500Principal subject) { if (subject == null) { throw new IllegalArgumentException(); } String subjectDN = CertificateUtil.toGlobusID(subject); if ((this.allowedDNs == null) || (this.allowedDNs.size() < 1)) { return false; } int size = this.allowedDNs.size(); for (int i = 0; i < size; i++) { Pattern pattern = allowedDNs.get(i); Matcher matcher = pattern.matcher(subjectDN); boolean valid = matcher.matches(); if (valid) { return true; } } return false; } /** * Return the patterns which identify the valid signing entities. If this signing policy has been created with a * set of DNs then the patterns will simply match the DNs. * * @return The patterns matching allowed signing entities. */ public List getAllowedDNs() { return this.allowedDNs; } /** * Method to determine if a signing policy is available for a * given DN. * * @return If the patterns vector is not null and has atleast one * element, true is returned. Else the method returns false. */ public boolean isPolicyAvailable() { if ((this.allowedDNs == null) || (this.allowedDNs.size() < 1)) { return false; } return true; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/SigningPolicyException.java000066400000000000000000000021161241116057200330670ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import java.security.GeneralSecurityException; /** * This exception signals an error with the Signing Policy. * * @version ${version} * @since 1.0 */ public class SigningPolicyException extends GeneralSecurityException { public SigningPolicyException(String msg) { super(msg); } public SigningPolicyException(String msg, Throwable ex) { super(msg, ex); } public SigningPolicyException(Throwable ex) { super(ex); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/SigningPolicyParser.java000066400000000000000000000532611241116057200323740ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.gsi.util.CertificateUtil; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import java.util.regex.Pattern; import javax.security.auth.x500.X500Principal; /** * Signing policy BCNF grammar as implemented here: (based on C implementation) *

    * eacl ::= {eacl_entry} eacl_entry ::= {access_identity} pos_rights * {restriction} {pos_rights {restriction}} | {access_identity} neg_rights * access_identity ::= access_identity_type def_authority value \n * access_identity_type ::= "access_id_HOST" | "access_id_USER" | * "access_id_GROUP" | "access_id_CA" | "access_id_APPLICATION" | * "access_id_ANYBODY" pos_rights ::= "pos_rights" def_authority value * {"pos_rights" def_authority value} neg_rights ::= "neg_rights" def_authority * value {"neg_rights" def_authority value} restriction ::= condition_type * def_authority value \n condition_type ::= alphanumeric_string def_authority * ::= alphanumeric_string value ::= alphanumeric_string *

    * This class take a signing policy file as input and parses it to extract the * policy that is enforced. Only the following policy is enforced: access_id_CA * with defining authority as X509 with CA DN as value. Any positive rights * following it with globus as defining authority and value CA:sign. Lastly, * restriction "cond_subjects" with globus as defining authority and the DNs the * CA is authorized to sign. restrictions are assumed to start with cond_. Order * of rights matter, so the first occurance of CA:Sign with allowedDNs is used * and rest of the policy is ignored. *

    * For a given signing policy file, only policy with the particular CA's DN is * parsed. *

    * subject names may include the following wildcard characters: * Matches * zero or any number of characters. ? Matches any single character. *

    * All subject names should be in Globus format, with slashes and should NOT be * revered. *

    * The allowed DN patterns are returned as a vector of java.util.regexp.Pattern. * The BCNF grammar that uses wildcard (*) and single character (?) are replaced * with the regexp grammar needed by the Pattern class. */ // COMMENT: BCB: moved over from crux-security-core: different parse-function name, stricter check for parameters public class SigningPolicyParser { public static final String ACCESS_ID_PREFIX = "access_id_"; public static final String ACCESS_ID_CA = "access_id_CA"; public static final String DEF_AUTH_X509 = "X509"; public static final String DEF_AUTH_GLOBUS = "globus"; public static final String POS_RIGHTS = "pos_rights"; public static final String NEG_RIGHTS = "neg_rights"; public static final String CONDITION_PREFIX = "cond_"; public static final String CONDITION_SUBJECT = "cond_subjects"; public static final String VALUE_CA_SIGN = "CA:sign"; public static final String SINGLE_CHAR = "?"; public static final String WILDCARD = "*"; public static final String SINGLE_PATTERN = "[\\p{Print}\\p{Blank}]"; public static final String WILDCARD_PATTERN = SINGLE_PATTERN + "*"; private static final int MIN_TOKENS_PER_LINE = 3; static final String[] ALLOWED_LINE_START = new String[]{ACCESS_ID_PREFIX, POS_RIGHTS, NEG_RIGHTS, CONDITION_PREFIX}; private Log logger = LogFactory.getLog(SigningPolicyParser.class.getName()); /** * Parses the file to extract signing policy defined for CA with the * specified DN. If the policy file does not exist, a SigningPolicy object * with only CA DN is created. If policy path exists, but no relevant policy * exisit, SigningPolicy object with CA DN and file path is created. * * @param fileName Name of the signing policy file * @return SigningPolicy object that contains the information. If no policy * is found, SigningPolicy object with only the CA DN is returned. * @throws org.globus.gsi.SigningPolicyException * Any errors with parsing the signing policy file. * @throws FileNotFoundException If the signing policy file does not exist. */ public Map parse(String fileName) throws FileNotFoundException, SigningPolicyException { if ((fileName == null) || (fileName.trim().isEmpty())) { throw new IllegalArgumentException(); } logger.debug("Signing policy file name " + fileName); FileReader fileReader = null; try { fileReader = new FileReader(fileName); return parse(fileReader); } catch (Exception e) { throw new SigningPolicyException(e); } finally { if (fileReader != null) { try { fileReader.close(); } catch (Exception exp) { logger.debug("Error closing file reader", exp); } } } } /** * Parses input stream to extract signing policy defined for CA with the * specified DN. * * @param reader Reader to any input stream to get the signing policy * information. * @return signing policy map defined by the signing policy file * @throws org.globus.gsi.SigningPolicyException * Any errors with parsing the signing policy. */ public Map parse(Reader reader) throws SigningPolicyException { Map policies = new HashMap(); BufferedReader bufferedReader = new BufferedReader(reader); try { String line; while ((line = bufferedReader.readLine()) != null) { line = line.trim(); // read line until some line that needs to be parsed. if (!isValidLine(line)) { continue; } logger.debug("Line to parse: " + line); String caDN = null; if (line.startsWith(ACCESS_ID_PREFIX)) { logger.debug("Check if it is CA and get the DN " + line); caDN = getCaDN(line, caDN); boolean usefulEntry = true; Boolean posNegRights = null; // check for neg or pos rights with restrictions checkRights(policies, bufferedReader, caDN, usefulEntry, posNegRights); } // JGLOBUS-94 } } catch (IOException exp) { throw new SigningPolicyException("", exp); } finally { cleanupReaders(reader, bufferedReader); } return policies; } private void checkRights(Map policies, BufferedReader bufferedReader, String caDN, boolean usefulEntry, Boolean posNegRights) throws IOException, SigningPolicyException { boolean tmpUsefulEntry = usefulEntry; Boolean tmpPosNegRights = posNegRights; String line = bufferedReader.readLine(); while (line != null) { if (!isValidLine(line)) { line = bufferedReader.readLine(); continue; } line = line.trim(); logger.debug("Line is " + line); if (line.startsWith(POS_RIGHTS)) { validatePositiveRights(tmpPosNegRights); if (tmpUsefulEntry) { tmpUsefulEntry = isUsefulEntry(line); } tmpPosNegRights = Boolean.TRUE; } else if (line.startsWith(NEG_RIGHTS)) { tmpPosNegRights = handleNegativeRights(tmpPosNegRights); } else if (line.startsWith(CONDITION_PREFIX)) { if (handleConditionalLine(policies, line, caDN, tmpUsefulEntry, tmpPosNegRights)) { break; } } else { String err = "invalidLine"; // no valid start with // String err = i18n.getMessage("invalidLine", line); throw new SigningPolicyException(err + line); } line = bufferedReader.readLine(); } } private boolean handleConditionalLine(Map policies, String line, String caDN, boolean usefulEntry, Boolean posNegRights) throws SigningPolicyException { if (!Boolean.TRUE.equals(posNegRights)) { String err = "invalidRestrictions"; // i18n.getMessage("invalidRestrictions", line); throw new SigningPolicyException(err); } if (usefulEntry && line.startsWith(CONDITION_SUBJECT)) { logger.debug("Read in subject condition."); int startIndex = CONDITION_SUBJECT.length(); int endIndex = line.length(); Vector allowedDNs = getAllowedDNs(line.substring(startIndex, endIndex)); // Some IGTF CA signing policies include all the various versions of having the emailAddress // in the DN. The "E=" variant causes an exception to be thrown in modern JVMs. // Hence, we ignore invalid DNs. Luckily, the signing policies contain all variants so // it is safe to ignore. try { X500Principal caPrincipal = CertificateUtil.toPrincipal(caDN); SigningPolicy policy = new SigningPolicy(caPrincipal, allowedDNs); policies.put(caPrincipal, policy); } catch (java.lang.IllegalArgumentException e) { if (caDN == null) { throw e; } String [] components = caDN.split("/"); boolean hasE = false; for (int i=0; i getAllowedDNs(String line) throws SigningPolicyException { String trimmedLine = line.trim(); int index = findIndex(trimmedLine); if (index == -1) { String err = "invalid tokens"; // i18n.getMessage("invalidTokens", line); throw new SigningPolicyException(err); } String defAuth = trimmedLine.substring(0, index); if (DEF_AUTH_GLOBUS.equals(defAuth)) { String value = trimmedLine.substring(index + 1, trimmedLine.length()); value = value.trim(); int startIndex = 0; int endIndex = value.length(); if (value.charAt(startIndex) == '\'') { startIndex++; int endOfDNIndex = value.indexOf('\'', startIndex); if (endOfDNIndex == -1) { String err = "invlaid subjects"; //i18n.getMessage("invalidSubjects", // lineForErr); throw new SigningPolicyException(err); } endIndex = endOfDNIndex; } value = value.substring(startIndex, endIndex); value = value.trim(); if (value.isEmpty()) { String err = "empty subjects"; //i18n.getMessage("emptySubjects", lineForErr); throw new SigningPolicyException(err); } Vector vector = new Vector(); startIndex = 0; endIndex = value.length(); if (value.indexOf("\"") == -1) { vector.add(getPattern(value)); } else { while (startIndex < endIndex) { int quot1 = value.indexOf("\"", startIndex); int quot2 = value.indexOf("\"", quot1 + 1); if (quot2 == -1) { String err = "unmatched quotes"; //i18n.getMessage("unmatchedQuotes", // lineForErr); throw new SigningPolicyException(err); } String token = value.substring(quot1 + 1, quot2); vector.add(getPattern(token)); startIndex = quot2 + 1; } } return vector; } return null; } private boolean isCASignRight(String line) throws SigningPolicyException { String trimmedLine = line.trim(); int index = findIndex(trimmedLine); if (index == -1) { String err = "invalid tokens"; // i18n.getMessage("invalidTokens", line); throw new SigningPolicyException(err); } String defAuth = trimmedLine.substring(0, index); if (DEF_AUTH_GLOBUS.equals(defAuth)) { trimmedLine = trimmedLine.substring(index + 1, trimmedLine.length()); trimmedLine = trimmedLine.trim(); // check if it is CA:Sign String value = trimmedLine.substring(0, trimmedLine.length()); if (VALUE_CA_SIGN.equals(value)) { return true; } } return false; } private String getCA(String inputLine) throws SigningPolicyException { String line = inputLine.trim(); int index = findIndex(line); if (index == -1) { String err = "invalid tokens"; // i18n.getMessage("invalidTokens", line); throw new SigningPolicyException(err); } String defAuth = line.substring(0, index); if (DEF_AUTH_X509.equals(defAuth)) { line = line.substring(index + 1, line.length()); line = line.trim(); // String dnString = line.substring(0, line.length()); String caDN; // find CA DN int caDNLocation = 0; if (line.charAt(caDNLocation) == '\'') { caDNLocation++; int endofDNIndex = line.indexOf('\'', caDNLocation + 1); if (endofDNIndex == -1) { // String err = i18n.getMessage("invalidCaDN", inputLine); String err = "invalid ca dn"; throw new SigningPolicyException(err); } caDN = line.substring(caDNLocation, endofDNIndex); } else { caDN = line.substring(caDNLocation, line.length() - 1); } caDN = caDN.trim(); return caDN; } return null; } /** * Method that takes a pattern string as described in the signing policy * file with * for zero or many characters and ? for single character, and * converts it into java.util.regexp.Pattern object. This requires replacing * the wildcard characters with equivalent expression in regexp grammar. * * @param patternStr Pattern string as described in the signing policy file * with for zero or many characters and ? for single * character * @return Pattern object with the expression equivalent to patternStr. */ public static Pattern getPattern(String patternStr) { if (patternStr == null) { throw new IllegalArgumentException(); } int startIndex = 0; int endIndex = patternStr.length(); StringBuffer buffer = new StringBuffer(""); while (startIndex < endIndex) { int star = patternStr.indexOf(WILDCARD, startIndex); if (star == -1) { star = endIndex; String preStr = patternStr.substring(startIndex, star); buffer = buffer.append(preStr); } else { String preStr = patternStr.substring(startIndex, star); buffer = buffer.append(preStr).append(WILDCARD_PATTERN); } startIndex = star + 1; } String tmpPatternStr = buffer.toString(); startIndex = 0; endIndex = tmpPatternStr.length(); buffer = new StringBuffer(""); while (startIndex < endIndex) { int qMark = tmpPatternStr.indexOf(SINGLE_CHAR, startIndex); if (qMark == -1) { qMark = endIndex; String preStr = tmpPatternStr.substring(startIndex, qMark); buffer = buffer.append(preStr); } else { String preStr = tmpPatternStr.substring(startIndex, qMark); buffer = buffer.append(preStr).append(SINGLE_PATTERN); } startIndex = qMark + 1; } tmpPatternStr = buffer.toString(); LogFactory.getLog(SigningPolicyParser.class.getCanonicalName()).debug("String with replaced pattern is " + tmpPatternStr); return Pattern.compile(tmpPatternStr, Pattern.CASE_INSENSITIVE); } // find first space or tab as separator. private int findIndex(String line) { int index = -1; if (line == null) { return index; } String trimmedLine = line.trim(); int spaceIndex = trimmedLine.indexOf(" "); int tabIndex = trimmedLine.indexOf("\t"); if (spaceIndex != -1) { if (tabIndex != -1) { if (spaceIndex < tabIndex) { index = spaceIndex; } else { index = tabIndex; } } else { index = spaceIndex; } } else { index = tabIndex; } return index; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/TrustedCertificates.java000066400000000000000000000327601241116057200324220ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.util.KeyStoreUtil; import org.globus.gsi.stores.ResourceSigningPolicyStore; import org.globus.gsi.stores.ResourceSigningPolicyStoreParameters; import org.globus.gsi.stores.Stores; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.provider.KeyStoreParametersFactory; import javax.security.auth.x500.X500Principal; import java.security.cert.CertStore; import java.security.cert.Certificate; import java.security.cert.X509CertSelector; import java.security.KeyStore; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import java.util.Collection; import java.util.Iterator; import java.io.File; import java.io.FilenameFilter; import org.globus.common.CoGProperties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.Serializable; import java.io.IOException; // COMMENT: What is the replacement for this? // COMMENT: We lost the refresh functionality: Currently an entirely new store is loaded upon load() /** * Class that reads in and maintains trusted certificates and signing * policy associated with the CAs. * @deprecated */ public class TrustedCertificates implements Serializable { private static Log logger = LogFactory.getLog(TrustedCertificates.class.getName()); static { new ProviderLoader(); } public static final CertFilter certFileFilter = new CertFilter(); private static TrustedCertificates trustedCertificates = null; // DN is in the format in certificates private Map certSubjectDNMap; // DN is in Globus format here, without any reversal. private Map policyDNMap; // Vector of X.509 Certificate objects private Vector certList; private final Set invalidPolicies = new HashSet(); private boolean changed; /** * Default signing policy suffix. The files are expected to be * .signing_policy in the same directory as the trusted * certificates. */ public final static String SIGNING_POLICY_FILE_SUFFIX = ".signing_policy"; private static KeyStore ms_trustStore = null; private static CertStore ms_crlStore = null; private static ResourceSigningPolicyStore ms_sigPolStore = null; protected TrustedCertificates() {} public TrustedCertificates(X509Certificate [] certs) { this(certs, null); } public TrustedCertificates(X509Certificate [] certs, SigningPolicy[] policies) { // JGLOBUS-91 this.certSubjectDNMap = new HashMap(); for (int i=0;ihashcode.number and will be * loaded automatically as trusted certificates. An attempt will * be made to load signing policy for the CA associated with * that hashcode from .signing_policy. If policy file is * not found, no error will be thrown, only path validation code * enforces the signing policy requirement. * * @param locations a list of certificate files/directories to load * the certificates from. The locations are comma * separated. * * @return java.security.cert.X509Certificate an array * of loaded certificates */ public static X509Certificate[] loadCertificates(String locations) { TrustedCertificates tc = TrustedCertificates.load(locations); return (tc == null) ? null : tc.getCertificates(); } public static TrustedCertificates load(String locations) { TrustedCertificates tc = new TrustedCertificates(); tc.reload(locations); return tc; } public static FilenameFilter getCertFilter() { return certFileFilter; } public static class CertFilter implements FilenameFilter { public boolean accept(File dir, String file) { int length = file.length(); if (length > 2 && file.charAt(length-2) == '.' && file.charAt(length-1) >= '0' && file.charAt(length-1) <= '9') return true; return false; } } public synchronized void reload(String locations) { if (locations == null) { return; } this.changed = false; StringTokenizer tokens = new StringTokenizer(locations, ","); File caDir = null; Map newCertSubjectDNMap = new HashMap(); Map newSigningDNMap = new HashMap(); while(tokens.hasMoreTokens()) { caDir = new File(tokens.nextToken().toString().trim()); if (!caDir.canRead()) { logger.debug("Cannot read: " + caDir.getAbsolutePath()); continue; } String caCertLocation = "file:" + caDir.getAbsolutePath(); // String sigPolPattern = caCertLocation + "/*.signing_policy"; // if (!caDir.isDirectory()) { // sigPolPattern = getPolicyFileName(caCertLocation); // } try { ms_trustStore = Stores.getTrustStore(caCertLocation + "/" + Stores.getDefaultCAFilesPattern()); Collection caCerts = KeyStoreUtil.getTrustedCertificates(ms_trustStore, new X509CertSelector()); Iterator iter = caCerts.iterator(); while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (!newCertSubjectDNMap.containsKey(cert.getSubjectDN().toString())) newCertSubjectDNMap.put(cert.getSubjectDN().toString(), cert); } } catch (Exception e) { logger.warn("Failed to create trust store",e); } try { ms_sigPolStore = Stores.getSigningPolicyStore(caCertLocation + "/" + Stores.getDefaultSigningPolicyFilesPattern()); } catch (GeneralSecurityException e) { logger.warn("Failed to create signing_policy store",e); } try { ms_sigPolStore = Stores.getSigningPolicyStore(caCertLocation+ "/" + Stores.getDefaultSigningPolicyFilesPattern()); Collection caCerts = KeyStoreUtil.getTrustedCertificates(ms_trustStore, new X509CertSelector()); Iterator iter = caCerts.iterator(); while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); X500Principal principal = cert.getSubjectX500Principal(); if (!newCertSubjectDNMap.containsKey(cert.getSubjectDN().toString())) { continue; } SigningPolicy policy; try { policy = ms_sigPolStore.getSigningPolicy(principal); } catch (Exception e) { if (!invalidPolicies.contains(principal)) { logger.warn("Invalid signing policy for CA certificate; skipping"); logger.debug("Invalid signing policy for CA certificate; skipping",e); invalidPolicies.add(principal); } continue; } if (policy != null) { newSigningDNMap.put(CertificateUtil.toGlobusID(policy.getCASubjectDN()), policy); } else { if (!invalidPolicies.contains(principal)) { logger.warn("no signing policy for ca cert " + cert.getSubjectDN()); invalidPolicies.add(principal); } } } } catch (Exception e) { logger.warn("Failed to create signing policy store",e); } } this.changed = true; this.certSubjectDNMap = newCertSubjectDNMap; this.policyDNMap = newSigningDNMap; if (this.changed) { this.certList = null; } } /** * Signing policy name is created as .signing_policy. */ private String getPolicyFileName(String caFileName) { return caFileName.substring(0, caFileName.lastIndexOf(".")) + SIGNING_POLICY_FILE_SUFFIX ; } /** * Indicates if the last reload caused new certificates to be loaded or * existing certificates to be reloaded or any certificates removed */ public boolean isChanged() { return this.changed; } /** * Obtains the default set of trusted certificates and signing policy * * @return TrustedCertificates object. */ public static synchronized TrustedCertificates getDefaultTrustedCertificates() { return getDefault(); } /** * Sets the default set of trusted certificates to use. * * @param trusted the new set of trusted certificates to use. */ public static void setDefaultTrustedCertificates(TrustedCertificates trusted) { trustedCertificates = trusted; } /** * Obtains the default set of trusted certificates and signing policy * * @return TrustedCertificates object. */ public static synchronized TrustedCertificates getDefault() { if (trustedCertificates == null) { trustedCertificates = new DefaultTrustedCertificates(); } return trustedCertificates; } public static KeyStore getTrustStore() { return ms_trustStore; } public static CertStore getcrlStore() { return ms_crlStore; } public static ResourceSigningPolicyStore getsigPolStore() { return ms_sigPolStore; } private static class DefaultTrustedCertificates extends TrustedCertificates { public void refresh() { reload(CoGProperties.getDefault().getCaCertLocations()); } } public String toString() { String returnStr = ""; if (this.certSubjectDNMap == null) { returnStr = "Certificate list is empty."; } else { returnStr = this.certSubjectDNMap.toString(); } if (this.policyDNMap == null) { returnStr = returnStr + "Signing policy list is empty."; } else { returnStr = returnStr + this.policyDNMap.toString(); } return returnStr; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/TrustedCertificatesUtil.java000066400000000000000000000026641241116057200332600ustar00rootroot00000000000000package org.globus.gsi; import org.globus.gsi.stores.ResourceCertStoreParameters; import org.globus.gsi.stores.Stores; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.provider.simple.SimpleMemoryCertStoreParams; import org.globus.gsi.provider.simple.SimpleMemoryProvider; import java.security.cert.CertStore; import org.globus.common.CoGProperties; import java.security.Security; /** * This is a helper class to create convert TrustCertificates * @deprecated */ public class TrustedCertificatesUtil { static { Security.addProvider(new GlobusProvider()); Security.addProvider(new SimpleMemoryProvider()); } /** * Create a CertStore object from TrustedCertificates. * The store only loads trusted certificates, no signing policies */ public static CertStore createCertStore(TrustedCertificates tc) throws Exception { CertStore store = null; if (tc == null) { String caCertPattern = "file:" + CoGProperties.getDefault().getCaCertLocations() + "/*.0"; store = Stores.getCACertStore(caCertPattern); } else { SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(tc.getCertificates(), null); params.setCerts(tc.getCertificates()); store = CertStore.getInstance(SimpleMemoryProvider.CERTSTORE_TYPE, params, SimpleMemoryProvider.PROVIDER_NAME); } return store; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/VersionUtil.java000066400000000000000000000013611241116057200307160ustar00rootroot00000000000000package org.globus.gsi; public class VersionUtil { /** * Checks if GSI-3 mode is enabled. * * @return true if "org.globus.gsi.version" system property * is set to "3". Otherwise, false. */ public static boolean isGsi3Enabled() { String ver = System.getProperty("org.globus.gsi.version"); return (ver != null && ver.equals("3")); } /** * Checks if GSI-2 mode is enabled. * * @return true if "org.globus.gsi.version" system property * is set to "2". Otherwise, false. */ public static boolean isGsi2Enabled() { String ver = System.getProperty("org.globus.gsi.version"); return (ver != null && ver.equals("2")); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/X509Credential.java000066400000000000000000000554761241116057200311130ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.gsi.util.CertificateIOUtil; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.util.ProxyCertificateUtil; import org.globus.gsi.trustmanager.X509ProxyCertPathValidator; import org.globus.gsi.stores.ResourceSigningPolicyStore; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.security.cert.CertStore; import java.security.KeyStore; import org.globus.common.CoGProperties; import java.io.FileNotFoundException; import java.io.FileInputStream; import java.security.cert.CertificateException; import org.globus.gsi.bc.BouncyCastleUtil; import java.security.interfaces.RSAPrivateKey; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Serializable; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Date; import java.util.Vector; import org.bouncycastle.util.encoders.Base64; import org.globus.gsi.stores.Stores; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; /** * FILL ME *

    * This class equivalent was called GlobusCredential in CoG -maybe a better name? * * @author ranantha@mcs.anl.gov */ // COMMENT: Added methods from GlobusCredential // COMMENT: Do we need the getDefaultCred functionality? public class X509Credential implements Serializable { private static final long serialVersionUID = 1L; public static final int BUFFER_SIZE = Integer.MAX_VALUE; private static Log logger = LogFactory.getLog(X509Credential.class.getCanonicalName()); private OpenSSLKey opensslKey; private X509Certificate[] certChain; private static X509Credential defaultCred; private static long credentialLastModified = -1; // indicates if default credential was explicitely set // and if so - if the credential expired it try // to load the proxy from a file. private static boolean credentialSet = false; private static File credentialFile = null; static { new ProviderLoader(); } public X509Credential(PrivateKey initKey, X509Certificate[] initCertChain) { if (initKey == null) { throw new IllegalArgumentException("Key cannot be null"); } if ((initCertChain == null) || (initCertChain.length < 1)) { throw new IllegalArgumentException("At least one public certificate required"); } this.certChain = new X509Certificate[initCertChain.length]; System.arraycopy(initCertChain, 0, this.certChain, 0, initCertChain.length); this.opensslKey = new BouncyCastleOpenSSLKey(initKey); } public X509Credential(InputStream certInputStream, InputStream keyInputStream) throws CredentialException { if (certInputStream.markSupported()) { certInputStream.mark(BUFFER_SIZE); } loadKey(keyInputStream); loadCertificate(certInputStream); validateCredential(); } public X509Credential(String certFile, String keyFile) throws CredentialException, IOException { loadKey(new FileInputStream(new File(keyFile))); loadCertificate(new FileInputStream(new File(certFile))); validateCredential(); } public X509Credential(String proxyFile) throws CredentialException { if (proxyFile == null) { throw new IllegalArgumentException("proxy file is null"); } logger.debug("Loading proxy file: " + proxyFile); try { InputStream in = new FileInputStream(proxyFile); load(in); } catch (FileNotFoundException f) { throw new CredentialException("proxy not found"); } } public X509Credential(InputStream input) throws CredentialException { load(input); } public X509Certificate[] getCertificateChain() { X509Certificate[] returnArray = new X509Certificate[this.certChain.length]; System.arraycopy(this.certChain, 0, returnArray, 0, this.certChain.length); return returnArray; } public PrivateKey getPrivateKey() throws CredentialException { return getPrivateKey(null); } public PrivateKey getPrivateKey(String password) throws CredentialException { if (this.opensslKey.isEncrypted()) { if (password == null) { throw new CredentialException("Key encrypted, password required"); } else { try { this.opensslKey.decrypt(password); } catch (GeneralSecurityException exp) { throw new CredentialException(exp.getMessage(), exp); } } } return this.opensslKey.getPrivateKey(); } public boolean isEncryptedKey() { return this.opensslKey.isEncrypted(); } /** * Reads Base64 encoded data from the stream and returns its decoded value. The reading continues until * the "END" string is found in the data. Otherwise, returns null. */ private static byte[] getDecodedPEMObject(BufferedReader reader) throws IOException { String line; StringBuffer buf = new StringBuffer(); while ((line = reader.readLine()) != null) { if (line.indexOf("--END") != -1) { // found end return Base64.decode(buf.toString().getBytes()); } else { buf.append(line); } } throw new EOFException("Missing PEM end footer"); } public void saveKey(OutputStream out) throws IOException { this.opensslKey.writeTo(out); out.flush(); } // COMMENT Used to be "key cert cert cert ...", which is wrong afaik. must be "cert key cert cert ..." public void saveCertificateChain(OutputStream out) throws IOException, CertificateEncodingException { CertificateIOUtil.writeCertificate(out, this.certChain[0]); for (int i = 1; i < this.certChain.length; i++) { // skip the self-signed certificates if (this.certChain[i].getSubjectDN().equals(certChain[i].getIssuerDN())) { continue; } CertificateIOUtil.writeCertificate(out, this.certChain[i]); } out.flush(); } public void save(OutputStream out) throws IOException, CertificateEncodingException { CertificateIOUtil.writeCertificate(out, this.certChain[0]); saveKey(out); for (int i = 1; i < this.certChain.length; i++) { // This will skip the self-signed certificates? if (this.certChain[i].getSubjectDN().equals(certChain[i].getIssuerDN())) { continue; } CertificateIOUtil.writeCertificate(out, this.certChain[i]); } out.flush(); } public void writeToFile(File file) throws IOException, CertificateEncodingException { writeToFile(file, file); } public void writeToFile(File certFile, File keyFile) throws IOException, CertificateEncodingException { FileOutputStream keyOutputStream = null; FileOutputStream certOutputStream = null; try { keyOutputStream = new FileOutputStream(keyFile); certOutputStream = new FileOutputStream(certFile); saveKey(keyOutputStream); saveCertificateChain(certOutputStream); } finally { try { if (keyOutputStream != null) { keyOutputStream.close(); } } catch (IOException e) { logger.warn("Could not close stream on save of key to file. " + keyFile.getPath()); } try { if (certOutputStream != null) { certOutputStream.close(); } } catch (IOException e) { logger.warn("Could not close stream on save certificate chain to file. " + certFile.getPath()); } } } public Date getNotBefore() { Date notBefore = this.certChain[0].getNotBefore(); for (int i = 1; i < this.certChain.length; i++) { Date date = this.certChain[i].getNotBefore(); if (date.before(notBefore)) { notBefore = date; } } return notBefore; } /** * Returns the number of certificates in the credential without the self-signed certificates. * * @return number of certificates without counting self-signed certificates */ public int getCertNum() { for (int i = this.certChain.length - 1; i >= 0; i--) { if (!this.certChain[i].getSubjectDN().equals(this.certChain[i].getIssuerDN())) { return i + 1; } } return this.certChain.length; } /** * Returns strength of the private/public key in bits. * * @return strength of the key in bits. Returns -1 if unable to determine it. */ public int getStrength() throws CredentialException { return getStrength(null); } /** * Returns strength of the private/public key in bits. * * @return strength of the key in bits. Returns -1 if unable to determine it. */ public int getStrength(String password) throws CredentialException { if (opensslKey == null) { return -1; } if (this.opensslKey.isEncrypted()) { if (password == null) { throw new CredentialException("Key encrypted, password required"); } else { try { this.opensslKey.decrypt(password); } catch (GeneralSecurityException exp) { throw new CredentialException(exp.getMessage(), exp); } } } return ((RSAPrivateKey)opensslKey.getPrivateKey()).getModulus().bitLength(); } /** * Returns the subject DN of the first certificate in the chain. * * @return subject DN. */ public String getSubject() { return this.certChain[0].getSubjectDN().getName(); } /** * Returns the issuer DN of the first certificate in the chain. * * @return issuer DN. */ public String getIssuer() { return this.certChain[0].getIssuerDN().getName(); } /** * Returns the certificate type of the first certificate in the chain. Returns -1 if unable to determine * the certificate type (an error occurred) * * @see BouncyCastleUtil#getCertificateType(X509Certificate) * * @return the type of first certificate in the chain. -1 if unable to determine the certificate type. */ public GSIConstants.CertificateType getProxyType() { try { return BouncyCastleUtil.getCertificateType(this.certChain[0]); } catch (CertificateException e) { logger.error("Error getting certificate type.", e); return GSIConstants.CertificateType.UNDEFINED; } } /** * Returns time left of this credential. The time left of the credential is based on the certificate with * the shortest validity time. * * @return time left in seconds. Returns 0 if the certificate has expired. */ public long getTimeLeft() { Date earliestTime = null; for (int i = 0; i < this.certChain.length; i++) { Date time = this.certChain[i].getNotAfter(); if (earliestTime == null || time.before(earliestTime)) { earliestTime = time; } } long diff = (earliestTime.getTime() - System.currentTimeMillis()) / 1000; return (diff < 0) ? 0 : diff; } /** * Returns the identity of this credential. * @see #getIdentityCertificate() * * @return The identity cert in Globus format (e.g. /C=US/..). Null, * if unable to get the identity (an error occurred) */ public String getIdentity() { try { return BouncyCastleUtil.getIdentity(this.certChain); } catch (CertificateException e) { logger.debug("Error getting certificate identity.", e); return null; } } /** * Returns the identity certificate of this credential. The identity certificate is the first certificate * in the chain that is not an impersonation proxy certificate. * * @return X509Certificate the identity cert. Null, if unable to get the identity certificate * (an error occurred) */ public X509Certificate getIdentityCertificate() { try { return BouncyCastleUtil.getIdentityCertificate(this.certChain); } catch (CertificateException e) { logger.debug("Error getting certificate identity.", e); return null; } } /** * Returns the path length constraint. The shortest length in the chain of * certificates is returned as the credential's path length. * * @return The path length constraint of the credential. -1 is any error * occurs. */ public int getPathConstraint() { int pathLength = Integer.MAX_VALUE; try { for (int i=0; i * The credential will be loaded on the initial call. It must not be expired. All subsequent calls to this * function return cached credential object. Once the credential is cached, and the underlying file * changes, the credential will be reloaded. * * @return the default credential. * @exception CredentialException * if the credential expired or some other error with the credential. */ public synchronized static X509Credential getDefaultCredential() throws CredentialException { if (defaultCred == null) { reloadDefaultCredential(); } else if (!credentialSet) { if (credentialFile.lastModified() == credentialLastModified) { defaultCred.verify(); } else { defaultCred = null; reloadDefaultCredential(); } } return defaultCred; } private static void reloadDefaultCredential() throws CredentialException { String proxyLocation = CoGProperties.getDefault().getProxyFile(); defaultCred = new X509Credential(proxyLocation); credentialFile = new File(proxyLocation); credentialLastModified = credentialFile.lastModified(); defaultCred.verify(); } /** * Sets default credential. * * @param cred * the credential to set a default. */ public synchronized static void setDefaultCredential(X509Credential cred) { defaultCred = cred; credentialSet = (cred != null); } // COMMENT: In case of an exception because of missing password with an // encrypted key: put in -1 as strength public String toString() { String lineSep = System.getProperty("line.separator"); StringBuffer buf = new StringBuffer(); buf.append("subject : ").append(getSubject()).append(lineSep); buf.append("issuer : ").append(getIssuer()).append(lineSep); int strength = -1; try { strength = this.getStrength(); } catch(Exception e) {} buf.append("strength : ").append(strength).append(lineSep); buf.append("timeleft : ").append(getTimeLeft() + " sec").append(lineSep); buf.append("proxy type : ").append(ProxyCertificateUtil.getProxyTypeAsString(getProxyType())); return buf.toString(); } protected void load(InputStream input) throws CredentialException { if (input == null) { throw new IllegalArgumentException("input stream cannot be null"); } X509Certificate cert = null; Vector chain = new Vector(3); String line; BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(input)); while ((line = reader.readLine()) != null) { if (line.indexOf("BEGIN CERTIFICATE") != -1) { byte[] data = getDecodedPEMObject(reader); cert = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(data)); chain.addElement(cert); } else if (line.indexOf("BEGIN RSA PRIVATE KEY") != -1) { byte[] data = getDecodedPEMObject(reader); this.opensslKey = new BouncyCastleOpenSSLKey("RSA", data); } } } catch (Exception e) { throw new CredentialException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } int size = chain.size(); if (size == 0) { throw new CredentialException("no certs"); } if (opensslKey == null) { throw new CredentialException("no key"); } // set chain this.certChain = new X509Certificate[size]; chain.copyInto(certChain); } protected void loadCertificate(InputStream input) throws CredentialException { if (input == null) { throw new IllegalArgumentException("Input stream to load X509Credential is null"); } X509Certificate cert; Vector chain = new Vector(); String line; BufferedReader reader = null; try { if (input.markSupported()) { input.reset(); } reader = new BufferedReader(new InputStreamReader(input)); while ((line = reader.readLine()) != null) { if (line.indexOf("BEGIN CERTIFICATE") != -1) { byte[] data = getDecodedPEMObject(reader); cert = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(data)); chain.addElement(cert); } } } catch (IOException e) { throw new CredentialException(e); } catch (GeneralSecurityException e) { throw new CredentialException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.debug("error closing reader", e); // This is ok } } } int size = chain.size(); if (size > 0) { this.certChain = new X509Certificate[size]; chain.copyInto(this.certChain); } } protected void loadKey(InputStream input) throws CredentialException { // JGLOBUS-95: BC seems to have some PEM utility but the actual // load is in private methods and cannot be leveraged. // Investigate availability of standard libraries for these // low level reads. FOr now, copying from CoG try { this.opensslKey = new BouncyCastleOpenSSLKey(input); } catch (IOException e) { throw new CredentialException(e.getMessage(), e); } catch (GeneralSecurityException e) { throw new CredentialException(e.getMessage(), e); } } private void validateCredential() throws CredentialException { if (this.certChain == null) { throw new CredentialException("No certificates found"); } int size = this.certChain.length; if (size < 0) { throw new CredentialException("No certificates found."); } if (this.opensslKey == null) { throw new CredentialException("NO private key found"); } } @Override public boolean equals(Object object) { if(object == this) { return true; } if(!(object instanceof X509Credential)) { return false; } X509Credential other = (X509Credential) object; return Arrays.equals(this.certChain, other.certChain) && this.opensslKey.equals(other.opensslKey); } @Override public int hashCode() { return (certChain == null ? 0 : Arrays.hashCode(certChain)) ^ opensslKey.hashCode(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/X509Extension.java000066400000000000000000000070551241116057200310030ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.util.I18n; /** * Represents an X.509 extension. It is used to create X.509 extensions * and pass them in a map during certificate generation. */ public class X509Extension { protected boolean critical; protected byte[] value; protected String oid; private static I18n i18n = I18n.getI18n("org.globus.gsi.errors", X509Extension.class.getClassLoader()); /** * Creates a X509Extension object with specified oid. * The extension has no value and is marked as noncritical. * * @param oid the oid of the extension */ public X509Extension(String oid) { this(oid, false, null); } /** * Creates a X509Extension object with specified oid and value. * The extension is marked as noncritical. * * @param oid the oid of the extension * @param value the actual value of the extension (not octet string * encoded). The value can be null. */ public X509Extension(String oid, byte[] value) { this(oid, false, value); } /** * Creates a X509Extension object with specified oid, critical property, * and value. * * @param oid the oid of the extension * @param critical the critical value. * @param value the actual value of the extension (not octet string * encoded). The value can be null. */ public X509Extension(String oid, boolean critical, byte[] value) { if (oid == null) { throw new IllegalArgumentException(i18n.getMessage("oidNull")); } this.oid = oid; this.critical = critical; this.value = value; } /** * Sets the oid of this extension. * * @param oid the oid of this extension. Cannot not null. */ public void setOid(String oid) { if (oid == null) { throw new IllegalArgumentException(i18n.getMessage("oidNull")); } this.oid = oid; } /** * Returns the oid of this extension. * * @return the oid of this extension. Always non-null. */ public String getOid() { return this.oid; } /** * Sets the extension as critical or noncritical. * * @param critical the critical value. */ public void setCritical(boolean critical) { this.critical = critical; } /** * Determines whether or not this extension is critical. * * @return true if extension is critical, false otherwise. */ public boolean isCritical() { return this.critical; } /** * Sets the actual value of the extension (not octet string encoded). * * @param value the actual value of the extension. Can be null. */ public void setValue(byte [] value) { this.value = value; } /** * Returns the actual value of the extension (not octet string encoded) * * @return the actual value of the extension (not octet string encoded). * Null if value not set. */ public byte[] getValue() { return this.value; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/X509ExtensionSet.java000066400000000000000000000062241241116057200314540ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import java.util.Set; import java.util.Hashtable; import org.globus.util.I18n; /** * Represents a set of X.509 extensions. */ public class X509ExtensionSet { private static I18n i18n = I18n.getI18n("org.globus.gsi.errors", X509ExtensionSet.class.getClassLoader()); private Hashtable extensions; /** * Creates an empty X509ExtensionSet object. */ public X509ExtensionSet() { this.extensions = new Hashtable(); } /** * Adds a X509Extension object to this set. * * @param extension the extension to add * @return an extension that was removed with the same oid as the * new extension. Null, if none existed before. */ public X509Extension add(X509Extension extension) { if (extension == null) { throw new IllegalArgumentException(i18n .getMessage("extensionNull")); } return (X509Extension)this.extensions.put(extension.getOid(), extension); } /** * Retrieves X509Extension by given oid. * * @param oid the oid of the extension to retrieve. * @return the extension with the specified oid. Can be null if * there is no extension with such oid. */ public X509Extension get(String oid) { if (oid == null) { throw new IllegalArgumentException(i18n.getMessage("oidNull")); } return (X509Extension)this.extensions.get(oid); } /** * Removes X509Extension by given oid. * * @param oid the oid of the extension to remove. * @return extension that was removed. Null, if extension with the * specified oid does not exist in this set. */ public X509Extension remove(String oid) { if (oid == null) { throw new IllegalArgumentException(i18n.getMessage("oidNull")); } return (X509Extension)this.extensions.remove(oid); } /** * Returns the size of the set. * * @return the size of the set. */ public int size() { return this.extensions.size(); } /** * Returns if the set is empty. * * @return true if the set if empty, false otherwise. */ public boolean isEmpty() { return this.extensions.isEmpty(); } /** * Removes all extensions from the set. */ public void clear() { this.extensions.clear(); } /** * Returns a set view of the OIDs of the extensions contained in this * extension set. * * @return the set with oids. */ public Set oidSet() { return this.extensions.keySet(); } } X509ProxyCertPathParameters.java000066400000000000000000000064501241116057200335460ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import org.globus.gsi.provider.SigningPolicyStore; import java.security.KeyStore; import java.security.cert.CertPathParameters; import java.security.cert.CertStore; import java.util.Map; import org.globus.gsi.proxy.ProxyPolicyHandler; /** * *

    * Refactor to have an interface that retuns trusted certificates, crls, * keys and policy. Manage stores within parameters. PKITrustManager can take * that interface and the validator can also be agnostic of this implementation * (can support say CertStore or KeyStore for trsuted certs). * * @author ranantha@mcs.anl.gov */ public class X509ProxyCertPathParameters implements CertPathParameters { // For trusted CAs private KeyStore trustStore; // For CRLs private CertStore crlStore; // For signing policy private SigningPolicyStore policyStore; private boolean rejectLimitedProxy; private Map handlers; public X509ProxyCertPathParameters(KeyStore initTrustStore, CertStore initCRLStore, SigningPolicyStore initPolicyStore, boolean initRejectLimitedProxy) { this(initTrustStore, initCRLStore, initPolicyStore, initRejectLimitedProxy, null); } public X509ProxyCertPathParameters(KeyStore initTrustStore, CertStore initCRLStore, SigningPolicyStore initPolicyStore, boolean initRejectLimitedProxy, Map initHandlers) { if ((initTrustStore == null) || (initCRLStore == null) || (initPolicyStore == null)) { throw new IllegalArgumentException(); } this.trustStore = initTrustStore; this.crlStore = initCRLStore; this.policyStore = initPolicyStore; this.rejectLimitedProxy = initRejectLimitedProxy; this.handlers = initHandlers; } public KeyStore getTrustStore() { return this.trustStore; } public CertStore getCrlStore() { return this.crlStore; } public SigningPolicyStore getSigningPolicyStore() { return this.policyStore; } public boolean isRejectLimitedProxy() { return this.rejectLimitedProxy; } public Map getPolicyHandlers() { return this.handlers; } /** * Makes a copy of this CertPathParameters. Changes to the copy * will not affect the original and vice versa. * * @return a copy of this CertPathParameters */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } } X509ProxyCertPathValidatorResult.java000066400000000000000000000037331241116057200345700ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import java.security.cert.CertPathValidatorResult; import java.security.cert.X509Certificate; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class X509ProxyCertPathValidatorResult implements CertPathValidatorResult { private X509Certificate idenX509Certificate; private boolean limited; public X509ProxyCertPathValidatorResult( X509Certificate initIdentityCertificate) { this(initIdentityCertificate, false); } public X509ProxyCertPathValidatorResult( X509Certificate initIdentityCertificate, boolean initLimited) { if (initIdentityCertificate != null) { this.idenX509Certificate = initIdentityCertificate; } this.limited = initLimited; } public X509Certificate getIdentityCertificate() { return this.idenX509Certificate; } public boolean isLimited() { return this.limited; } /** * Makes a copy of this CertPathValidatorResult. Changes to the * copy will not affect the original and vice versa. * * @return a copy of this CertPathValidatorResult */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { /* Cannot happen */ throw new RuntimeException(e.getMessage(), e); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/bc/000077500000000000000000000000001241116057200261535ustar00rootroot00000000000000BouncyCastleCertProcessingFactory.java000066400000000000000000001504061241116057200355430ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/bc/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.bc; import org.bouncycastle.asn1.x500.style.BCStyle; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.util.ProxyCertificateUtil; import org.globus.gsi.X509Credential; import org.globus.gsi.VersionUtil; import java.math.BigInteger; import java.security.cert.CertificateException; import java.util.Random; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.Iterator; import java.util.Calendar; import java.io.InputStream; import java.io.IOException; import java.io.ByteArrayInputStream; import java.security.cert.X509Certificate; import java.security.PrivateKey; import java.security.PublicKey; import java.security.GeneralSecurityException; import java.security.KeyPairGenerator; import java.security.KeyPair; import org.globus.util.I18n; import org.globus.gsi.GlobusCredential; import org.globus.gsi.GSIConstants; import org.globus.gsi.X509ExtensionSet; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.globus.gsi.proxy.ext.ProxyPolicy; import org.globus.gsi.proxy.ext.ProxyCertInfoExtension; import org.globus.gsi.proxy.ext.GlobusProxyCertInfoExtension; import org.bouncycastle.x509.X509V3CertificateGenerator; import org.bouncycastle.jce.PKCS10CertificationRequest; import org.bouncycastle.jce.provider.X509CertificateObject; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.x509.Certificate; import org.bouncycastle.asn1.x509.TBSCertificateStructure; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.KeyUsage; /** * Provides certificate processing API such as creating new certificates, certificate requests, etc. */ public class BouncyCastleCertProcessingFactory { private static I18n i18n = I18n.getI18n("org.globus.gsi.errors", BouncyCastleCertProcessingFactory.class .getClassLoader()); private static BouncyCastleCertProcessingFactory factory; protected BouncyCastleCertProcessingFactory() { } /** * Returns an instance of this class.. * * @return BouncyCastleCertProcessingFactory instance. */ public static synchronized BouncyCastleCertProcessingFactory getDefault() { if (factory == null) { factory = new BouncyCastleCertProcessingFactory(); } return factory; } /** * Creates a proxy certificate from the certificate request. * * @see #createCertificate(InputStream, X509Certificate, PrivateKey, int, int, X509ExtensionSet, String) * createCertificate * @deprecated */ public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert, PrivateKey privateKey, int lifetime, int delegationMode) throws IOException, GeneralSecurityException { return createCertificate(certRequestInputStream, cert, privateKey, lifetime, delegationMode, (X509ExtensionSet) null, null); } /** * Creates a proxy certificate from the certificate request. * * @see #createCertificate(InputStream, X509Certificate, PrivateKey, int, int, X509ExtensionSet, String) * createCertificate * @deprecated */ public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert, PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet) throws IOException, GeneralSecurityException { return createCertificate(certRequestInputStream, cert, privateKey, lifetime, delegationMode, extSet, null); } /** * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new * certificate) * * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet, * String) createProxyCertificate * @param certRequestInputStream * the input stream to read the certificate request from. * @param cert * the issuer certificate * @param privateKey * the private key to sign the new certificate with. * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param delegationMode * the type of proxy credential to create * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * @param cnValue * the value of the CN component of the subject of the new certificate. If null, the defaults * will be used depending on the proxy certificate type created. * @return X509Certificate the new proxy certificate * @exception IOException * if error reading the certificate request * @exception GeneralSecurityException * if a security error occurs. * @deprecated */ public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert, PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet, String cnValue) throws IOException, GeneralSecurityException { ASN1InputStream derin = new ASN1InputStream(certRequestInputStream); ASN1Primitive reqInfo = derin.readObject(); PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo); boolean rs = certReq.verify(); if (!rs) { String err = i18n.getMessage("certReqVerification"); throw new GeneralSecurityException(err); } return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, delegationMode, extSet, cnValue); } /** * Creates a new proxy credential from the specified certificate chain and a private key. * * @see #createCredential(X509Certificate[], PrivateKey, int, int, int, X509ExtensionSet, String) * createCredential * @deprecated */ public GlobusCredential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, int delegationMode) throws GeneralSecurityException { return createCredential(certs, privateKey, bits, lifetime, delegationMode, (X509ExtensionSet) null, null); } /** * Creates a new proxy credential from the specified certificate chain and a private key. * * @see #createCredential(X509Certificate[], PrivateKey, int, int, int, X509ExtensionSet, String) * createCredential * @deprecated */ public GlobusCredential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, int delegationMode, X509ExtensionSet extSet) throws GeneralSecurityException { return createCredential(certs, privateKey, bits, lifetime, delegationMode, extSet, null); } /** * Creates a new proxy credential from the specified certificate chain and a private key. A set of X.509 * extensions can be optionally included in the new proxy certificate. This function automatically creates * a "RSA"-based key pair. * * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet, * String) createProxyCertificate * @param certs * the certificate chain for the new proxy credential. The top-most certificate * cert[0] will be designated as the issuing certificate. * @param privateKey * the private key of the issuing certificate. The new proxy certificate will be signed with * that private key. * @param bits * the strength of the key pair for the new proxy certificate. * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param delegationMode * the type of proxy credential to create * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * @param cnValue * the value of the CN component of the subject of the new proxy credential. If null, the * defaults will be used depending on the proxy certificate type created. * @return GlobusCredential the new proxy credential. * @exception GeneralSecurityException * if a security error occurs. * @deprecated */ public GlobusCredential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, int delegationMode, X509ExtensionSet extSet, String cnValue) throws GeneralSecurityException { X509Certificate[] bcCerts = getX509CertificateObjectChain(certs); KeyPairGenerator keyGen = null; keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(bits); KeyPair keyPair = keyGen.genKeyPair(); X509Certificate newCert = createProxyCertificate(bcCerts[0], privateKey, keyPair.getPublic(), lifetime, delegationMode, extSet, cnValue); X509Certificate[] newCerts = new X509Certificate[bcCerts.length + 1]; newCerts[0] = newCert; System.arraycopy(certs, 0, newCerts, 1, certs.length); return new GlobusCredential(keyPair.getPrivate(), newCerts); } /** * Creates a proxy certificate. A set of X.509 extensions can be optionally included in the new proxy * certificate.
    * If a GSI-2 proxy is created, the serial number of the proxy certificate will be the same as of the * issuing certificate. Also, none of the extensions in the issuing certificate will be copied into the * proxy certificate.
    * If a GSI-3 or GSI 4 proxy is created, the serial number of the proxy certificate will be picked * randomly. If the issuing certificate contains a KeyUsage extension, the extension will be copied * into the proxy certificate with keyCertSign and nonRepudiation bits turned off. No other * extensions are currently copied. * * The methods defaults to creating GSI 4 proxy * * @param issuerCert_ * the issuing certificate * @param issuerKey * private key matching the public key of issuer certificate. The new proxy certificate will be * signed by that key. * @param publicKey * the public key of the new certificate * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param proxyType * can be one of {@link GSIConstants#DELEGATION_LIMITED GSIConstants.DELEGATION_LIMITED}, * {@link GSIConstants#DELEGATION_FULL GSIConstants.DELEGATION_FULL}, * * {@link GSIConstants#GSI_2_LIMITED_PROXY GSIConstants.GSI_2_LIMITED_PROXY}, * {@link GSIConstants#GSI_2_PROXY GSIConstants.GSI_2_PROXY}, * {@link GSIConstants#GSI_3_IMPERSONATION_PROXY GSIConstants.GSI_3_IMPERSONATION_PROXY}, * {@link GSIConstants#GSI_3_LIMITED_PROXY GSIConstants.GSI_3_LIMITED_PROXY}, * {@link GSIConstants#GSI_3_INDEPENDENT_PROXY GSIConstants.GSI_3_INDEPENDENT_PROXY}, * {@link GSIConstants#GSI_3_RESTRICTED_PROXY GSIConstants.GSI_3_RESTRICTED_PROXY}. * {@link GSIConstants#GSI_4_IMPERSONATION_PROXY GSIConstants.GSI_4_IMPERSONATION_PROXY}, * {@link GSIConstants#GSI_4_LIMITED_PROXY GSIConstants.GSI_3_LIMITED_PROXY}, * {@link GSIConstants#GSI_4_INDEPENDENT_PROXY GSIConstants.GSI_4_INDEPENDENT_PROXY}, * {@link GSIConstants#GSI_4_RESTRICTED_PROXY GSIConstants.GSI_4_RESTRICTED_PROXY}. * * If {@link GSIConstants#DELEGATION_LIMITED GSIConstants.DELEGATION_LIMITED} and if * {@link VersionUtil#isGsi2Enabled() CertUtil.isGsi2Enabled} returns true then a GSI-2 limited * proxy will be created. Else if {@link VersionUtil#isGsi3Enabled() CertUtil.isGsi3Enabled} * returns true then a GSI-3 limited proxy will be created. If not, a GSI-4 limited proxy will * be created. * * If {@link GSIConstants#DELEGATION_FULL GSIConstants.DELEGATION_FULL} and if * {@link VersionUtil#isGsi2Enabled() CertUtil.isGsi2Enabled} returns true then a GSI-2 full proxy * will be created. Else if {@link VersionUtil#isGsi3Enabled() CertUtil.isGsi3Enabled} returns * true then a GSI-3 full proxy will be created. If not, a GSI-4 full proxy will be created. * * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link GSIConstants#GSI_3_RESTRICTED_PROXY * GSIConstants.GSI_3_RESTRICTED_PROXY} or {@link GSIConstants#GSI_4_RESTRICTED_PROXY * GSIConstants.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * * @param cnValue * the value of the CN component of the subject of the new certificate. If null, the defaults * will be used depending on the proxy certificate type created. * @return X509Certificate the new proxy certificate. * @exception GeneralSecurityException * if a security error occurs. * @deprecated */ public X509Certificate createProxyCertificate(X509Certificate issuerCert_, PrivateKey issuerKey, PublicKey publicKey, int lifetime, int proxyType, X509ExtensionSet extSet, String cnValue) throws GeneralSecurityException { X509Certificate issuerCert = issuerCert_; if (!(issuerCert_ instanceof X509CertificateObject)) { issuerCert = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(issuerCert.getEncoded())); } if (proxyType == GSIConstants.DELEGATION_LIMITED) { GSIConstants.CertificateType type = BouncyCastleUtil.getCertificateType(issuerCert); if (ProxyCertificateUtil.isGsi4Proxy(type)) { proxyType = GSIConstants.GSI_4_LIMITED_PROXY; } else if (ProxyCertificateUtil.isGsi3Proxy(type)) { proxyType = GSIConstants.GSI_3_LIMITED_PROXY; } else if (ProxyCertificateUtil.isGsi2Proxy(type)) { proxyType = GSIConstants.GSI_2_LIMITED_PROXY; } else { // default to RFC compliant proxy if (VersionUtil.isGsi2Enabled()) { proxyType = GSIConstants.GSI_2_LIMITED_PROXY; } else { proxyType = VersionUtil.isGsi3Enabled() ? GSIConstants.GSI_3_LIMITED_PROXY : GSIConstants.GSI_4_LIMITED_PROXY; } } } else if (proxyType == GSIConstants.DELEGATION_FULL) { GSIConstants.CertificateType type = BouncyCastleUtil.getCertificateType(issuerCert); if (ProxyCertificateUtil.isGsi4Proxy(type)) { proxyType = GSIConstants.GSI_4_IMPERSONATION_PROXY; } else if (ProxyCertificateUtil.isGsi3Proxy(type)) { proxyType = GSIConstants.GSI_3_IMPERSONATION_PROXY; } else if (ProxyCertificateUtil.isGsi2Proxy(type)) { proxyType = GSIConstants.GSI_2_PROXY; } else { // Default to RFC complaint proxy if (VersionUtil.isGsi2Enabled()) { proxyType = GSIConstants.GSI_2_PROXY; } else { proxyType = (VersionUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_IMPERSONATION_PROXY : GSIConstants.GSI_4_IMPERSONATION_PROXY; } } } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); org.globus.gsi.X509Extension x509Ext = null; BigInteger serialNum = null; String delegDN = null; if (ProxyCertificateUtil.isGsi3Proxy(GSIConstants.CertificateType.get(proxyType)) || ProxyCertificateUtil.isGsi4Proxy(GSIConstants.CertificateType.get(proxyType))) { Random rand = new Random(); delegDN = String.valueOf(Math.abs(rand.nextInt())); serialNum = new BigInteger(20, rand); if (extSet != null) { x509Ext = extSet.get(ProxyCertInfo.OID.getId()); if (x509Ext == null) { x509Ext = extSet.get(ProxyCertInfo.OLD_OID.getId()); } } if (x509Ext == null) { // create ProxyCertInfo extension ProxyPolicy policy = null; if (ProxyCertificateUtil.isLimitedProxy(GSIConstants.CertificateType.get(proxyType))) { policy = new ProxyPolicy(ProxyPolicy.LIMITED); } else if (ProxyCertificateUtil.isIndependentProxy(GSIConstants.CertificateType.get(proxyType))) { policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT); } else if (ProxyCertificateUtil.isImpersonationProxy(GSIConstants.CertificateType.get(proxyType))) { // since limited has already been checked, this should work. policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION); } else if ((proxyType == GSIConstants.GSI_3_RESTRICTED_PROXY) || (proxyType == GSIConstants.GSI_4_RESTRICTED_PROXY)) { String err = i18n.getMessage("restrictProxy"); throw new IllegalArgumentException(err); } else { String err = i18n.getMessage("invalidProxyType"); throw new IllegalArgumentException(err); } ProxyCertInfo proxyCertInfo = new ProxyCertInfo(policy); x509Ext = new ProxyCertInfoExtension(proxyCertInfo); if (ProxyCertificateUtil.isGsi4Proxy(GSIConstants.CertificateType.get(proxyType))) { // RFC compliant OID x509Ext = new ProxyCertInfoExtension(proxyCertInfo); } else { // old OID x509Ext = new GlobusProxyCertInfoExtension(proxyCertInfo); } } try { // add ProxyCertInfo extension to the new cert certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue()); // handle KeyUsage in issuer cert TBSCertificateStructure crt = BouncyCastleUtil.getTBSCertificateStructure(issuerCert); X509Extensions extensions = crt.getExtensions(); if (extensions != null) { X509Extension ext; // handle key usage ext ext = extensions.getExtension(X509Extension.keyUsage); if (ext != null) { // TBD: handle this better if (extSet != null && (extSet.get(X509Extension.keyUsage.getId()) != null)) { String err = i18n.getMessage("keyUsageExt"); throw new GeneralSecurityException(err); } DERBitString bits = (DERBitString) BouncyCastleUtil.getExtensionObject(ext); byte[] bytes = bits.getBytes(); // make sure they are disabled if ((bytes[0] & KeyUsage.nonRepudiation) != 0) { bytes[0] ^= KeyUsage.nonRepudiation; } if ((bytes[0] & KeyUsage.keyCertSign) != 0) { bytes[0] ^= KeyUsage.keyCertSign; } bits = new DERBitString(bytes, bits.getPadBits()); certGen.addExtension(X509Extension.keyUsage, ext.isCritical(), bits); } } } catch (IOException e) { // but this should not happen throw new GeneralSecurityException(e.getMessage()); } } else if (proxyType == GSIConstants.GSI_2_LIMITED_PROXY) { delegDN = "limited proxy"; serialNum = issuerCert.getSerialNumber(); } else if (proxyType == GSIConstants.GSI_2_PROXY) { delegDN = "proxy"; serialNum = issuerCert.getSerialNumber(); } else { String err = i18n.getMessage("unsupportedProxy", Integer.toString(proxyType)); throw new IllegalArgumentException(err); } // add specified extensions if (extSet != null) { Iterator iter = extSet.oidSet().iterator(); while (iter.hasNext()) { String oid = (String) iter.next(); // skip ProxyCertInfo extension if (oid.equals(ProxyCertInfo.OID.getId()) || oid.equals(ProxyCertInfo.OLD_OID.getId())) { continue; } x509Ext = (org.globus.gsi.X509Extension) extSet.get(oid); certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue()); } } X509Name issuerDN; if (issuerCert.getSubjectDN() instanceof X509Name) { issuerDN = (X509Name)issuerCert.getSubjectDN(); } else { issuerDN = new X509Name(true,issuerCert.getSubjectX500Principal().getName()); } X509NameHelper issuer = new X509NameHelper(issuerDN); X509NameHelper subject = new X509NameHelper(issuerDN); subject.add(BCStyle.CN, (cnValue == null) ? delegDN : cnValue); certGen.setSubjectDN(subject.getAsName()); certGen.setIssuerDN(issuer.getAsName()); certGen.setSerialNumber(serialNum); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm(issuerCert.getSigAlgName()); GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT")); /* Allow for a five minute clock skew here. */ date.add(Calendar.MINUTE, -5); certGen.setNotBefore(date.getTime()); /* If hours = 0, then cert lifetime is set to user cert */ if (lifetime <= 0) { certGen.setNotAfter(issuerCert.getNotAfter()); } else { date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime); certGen.setNotAfter(date.getTime()); } return certGen.generateX509Certificate(issuerKey); } /** * Creates a proxy certificate from the certificate request. * * @see #createCertificate(InputStream, X509Certificate, PrivateKey, int, int, X509ExtensionSet, String) * createCertificate */ public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert, PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType) throws IOException, GeneralSecurityException { return createCertificate(certRequestInputStream, cert, privateKey, lifetime, certType, (X509ExtensionSet) null, null); } /** * Creates a proxy certificate from the certificate request. * * @see #createCertificate(InputStream, X509Certificate, PrivateKey, int, GSIConstants.CertificateType, X509ExtensionSet, String) * createCertificate */ public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert, PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet) throws IOException, GeneralSecurityException { return createCertificate(certRequestInputStream, cert, privateKey, lifetime, certType, extSet, null); } /** * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new * certificate) * * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet, * String) createProxyCertificate * @param certRequestInputStream * the input stream to read the certificate request from. * @param cert * the issuer certificate * @param privateKey * the private key to sign the new certificate with. * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param certType * the type of proxy credential to create * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * @param cnValue * the value of the CN component of the subject of the new certificate. If null, the defaults * will be used depending on the proxy certificate type created. * @return X509Certificate the new proxy certificate * @exception IOException * if error reading the certificate request * @exception GeneralSecurityException * if a security error occurs. */ public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert, PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet, String cnValue) throws IOException, GeneralSecurityException { ASN1InputStream derin = new ASN1InputStream(certRequestInputStream); ASN1Primitive reqInfo = derin.readObject(); PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo); boolean rs = certReq.verify(); if (!rs) { String err = i18n.getMessage("certReqVerification"); throw new GeneralSecurityException(err); } return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, certType, extSet, cnValue); } /** * Creates a new proxy credential from the specified certificate chain and a private key. * * @see #createCredential(X509Certificate[], PrivateKey, int, int, GSIConstants.CertificateType, X509ExtensionSet, String) * createCredential */ public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, GSIConstants.CertificateType certType) throws GeneralSecurityException { return createCredential(certs, privateKey, bits, lifetime, certType, (X509ExtensionSet) null, null); } /** * Creates a new proxy credential from the specified certificate chain and a private key. * * @see #createCredential(X509Certificate[], PrivateKey, int, int, GSIConstants.CertificateType, X509ExtensionSet, String) * createCredential */ public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet) throws GeneralSecurityException { return createCredential(certs, privateKey, bits, lifetime, certType, extSet, null); } /** * Creates a new proxy credential from the specified certificate chain and a private key. A set of X.509 * extensions can be optionally included in the new proxy certificate. This function automatically creates * a "RSA"-based key pair. * * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet, * String) createProxyCertificate * @param certs * the certificate chain for the new proxy credential. The top-most certificate * cert[0] will be designated as the issuing certificate. * @param privateKey * the private key of the issuing certificate. The new proxy certificate will be signed with * that private key. * @param bits * the strength of the key pair for the new proxy certificate. * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param certType * the type of proxy credential to create * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * @param cnValue * the value of the CN component of the subject of the new proxy credential. If null, the * defaults will be used depending on the proxy certificate type created. * @return GlobusCredential the new proxy credential. * @exception GeneralSecurityException * if a security error occurs. */ public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet, String cnValue) throws GeneralSecurityException { X509Certificate[] bcCerts = getX509CertificateObjectChain(certs); KeyPairGenerator keyGen = null; keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(bits); KeyPair keyPair = keyGen.genKeyPair(); X509Certificate newCert = createProxyCertificate(bcCerts[0], privateKey, keyPair.getPublic(), lifetime, certType, extSet, cnValue); X509Certificate[] newCerts = new X509Certificate[bcCerts.length + 1]; newCerts[0] = newCert; System.arraycopy(certs, 0, newCerts, 1, certs.length); return new X509Credential(keyPair.getPrivate(), newCerts); } /** * Creates a new proxy credential from the specified certificate chain and a private key, * using the given delegation mode. * * @see #createCredential(X509Certificate[], PrivateKey, int, int, GSIConstants.CertificateType, X509ExtensionSet, String) * createCredential */ public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, GSIConstants.DelegationType delegType) throws GeneralSecurityException { return createCredential(certs, privateKey, bits, lifetime, delegType, (X509ExtensionSet) null, null); } /** * Creates a new proxy credential from the specified certificate chain and a private key, * using the given delegation mode. * * @see #createCredential(X509Certificate[], PrivateKey, int, int, GSIConstants.CertificateType, X509ExtensionSet, String) * createCredential */ public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, GSIConstants.DelegationType delegType, X509ExtensionSet extSet) throws GeneralSecurityException { return createCredential(certs, privateKey, bits, lifetime, delegType, extSet, null); } /** * Creates a new proxy credential from the specified certificate chain and a private key, * using the given delegation mode. * @see #createCredential(X509Certificate[], PrivateKey, int, int, GSIConstants.CertificateType, X509ExtensionSet, String) */ public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, GSIConstants.DelegationType delegType, X509ExtensionSet extSet, String cnValue) throws GeneralSecurityException { X509Certificate[] bcCerts = getX509CertificateObjectChain(certs); return createCredential(bcCerts, privateKey, bits, lifetime, decideProxyType(bcCerts[0], delegType), extSet, cnValue); } /** * Creates a proxy certificate. A set of X.509 extensions can be optionally included in the new proxy * certificate.
    * If a GSI-2 proxy is created, the serial number of the proxy certificate will be the same as of the * issuing certificate. Also, none of the extensions in the issuing certificate will be copied into the * proxy certificate.
    * If a GSI-3 or GSI 4 proxy is created, the serial number of the proxy certificate will be picked * randomly. If the issuing certificate contains a KeyUsage extension, the extension will be copied * into the proxy certificate with keyCertSign and nonRepudiation bits turned off. No other * extensions are currently copied. * * The methods defaults to creating GSI 4 proxy * * @param issuerCert_ * the issuing certificate * @param issuerKey * private key matching the public key of issuer certificate. The new proxy certificate will be * signed by that key. * @param publicKey * the public key of the new certificate * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param certType * can be one of {@link org.globus.gsi.GSIConstants.CertificateType#GSI_2_LIMITED_PROXY GSIConstants.CertificateType.GSI_2_LIMITED_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_2_PROXY GSIConstants.CertificateType.GSI_2_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_IMPERSONATION_PROXY GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_LIMITED_PROXY GSIConstants.CertificateType.GSI_3_LIMITED_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_INDEPENDENT_PROXY GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY}. * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_IMPERSONATION_PROXY GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_LIMITED_PROXY GSIConstants.CertificateType.GSI_3_LIMITED_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_INDEPENDENT_PROXY GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY}. * * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * * @param cnValue * the value of the CN component of the subject of the new certificate. If null, the defaults * will be used depending on the proxy certificate type created. * @return X509Certificate the new proxy certificate. * @exception GeneralSecurityException * if a security error occurs. */ public X509Certificate createProxyCertificate(X509Certificate issuerCert_, PrivateKey issuerKey, PublicKey publicKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet, String cnValue) throws GeneralSecurityException { X509Certificate issuerCert = issuerCert_; if (!(issuerCert_ instanceof X509CertificateObject)) { issuerCert = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(issuerCert.getEncoded())); } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); org.globus.gsi.X509Extension x509Ext = null; BigInteger serialNum = null; String delegDN = null; if (ProxyCertificateUtil.isGsi3Proxy(certType) || ProxyCertificateUtil.isGsi4Proxy(certType)) { Random rand = new Random(); delegDN = String.valueOf(Math.abs(rand.nextInt())); serialNum = new BigInteger(20, rand); if (extSet != null) { x509Ext = extSet.get(ProxyCertInfo.OID.getId()); if (x509Ext == null) { x509Ext = extSet.get(ProxyCertInfo.OLD_OID.getId()); } } if (x509Ext == null) { // create ProxyCertInfo extension ProxyPolicy policy = null; if (ProxyCertificateUtil.isLimitedProxy(certType)) { policy = new ProxyPolicy(ProxyPolicy.LIMITED); } else if (ProxyCertificateUtil.isIndependentProxy(certType)) { policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT); } else if (ProxyCertificateUtil.isImpersonationProxy(certType)) { // since limited has already been checked, this should work. policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION); } else if ((certType == GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY) || (certType == GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY)) { String err = i18n.getMessage("restrictProxy"); throw new IllegalArgumentException(err); } else { String err = i18n.getMessage("invalidProxyType"); throw new IllegalArgumentException(err); } ProxyCertInfo proxyCertInfo = new ProxyCertInfo(policy); x509Ext = new ProxyCertInfoExtension(proxyCertInfo); if (ProxyCertificateUtil.isGsi4Proxy(certType)) { // RFC compliant OID x509Ext = new ProxyCertInfoExtension(proxyCertInfo); } else { // old OID x509Ext = new GlobusProxyCertInfoExtension(proxyCertInfo); } } try { // add ProxyCertInfo extension to the new cert certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue()); // handle KeyUsage in issuer cert TBSCertificateStructure crt = BouncyCastleUtil.getTBSCertificateStructure(issuerCert); X509Extensions extensions = crt.getExtensions(); if (extensions != null) { X509Extension ext; // handle key usage ext ext = extensions.getExtension(X509Extension.keyUsage); if (ext != null) { // TBD: handle this better if (extSet != null && (extSet.get(X509Extension.keyUsage.getId()) != null)) { String err = i18n.getMessage("keyUsageExt"); throw new GeneralSecurityException(err); } DERBitString bits = (DERBitString) BouncyCastleUtil.getExtensionObject(ext); byte[] bytes = bits.getBytes(); // make sure they are disabled if ((bytes[0] & KeyUsage.nonRepudiation) != 0) { bytes[0] ^= KeyUsage.nonRepudiation; } if ((bytes[0] & KeyUsage.keyCertSign) != 0) { bytes[0] ^= KeyUsage.keyCertSign; } bits = new DERBitString(bytes, bits.getPadBits()); certGen.addExtension(X509Extension.keyUsage, ext.isCritical(), bits); } } } catch (IOException e) { // but this should not happen throw new GeneralSecurityException(e.getMessage()); } } else if (certType == GSIConstants.CertificateType.GSI_2_LIMITED_PROXY) { delegDN = "limited proxy"; serialNum = issuerCert.getSerialNumber(); } else if (certType == GSIConstants.CertificateType.GSI_2_PROXY) { delegDN = "proxy"; serialNum = issuerCert.getSerialNumber(); } else { String err = i18n.getMessage("unsupportedProxy", certType); throw new IllegalArgumentException(err); } // add specified extensions if (extSet != null) { Iterator iter = extSet.oidSet().iterator(); while (iter.hasNext()) { String oid = (String) iter.next(); // skip ProxyCertInfo extension if (oid.equals(ProxyCertInfo.OID.getId()) || oid.equals(ProxyCertInfo.OLD_OID.getId())) { continue; } x509Ext = (org.globus.gsi.X509Extension) extSet.get(oid); certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue()); } } X509Name issuerDN; if (issuerCert.getSubjectDN() instanceof X509Name) { issuerDN = (X509Name)issuerCert.getSubjectDN(); } else { issuerDN = new X509Name(true,issuerCert.getSubjectX500Principal().getName()); } X509NameHelper issuer = new X509NameHelper(issuerDN); X509NameHelper subject = new X509NameHelper(issuerDN); subject.add(BCStyle.CN, (cnValue == null) ? delegDN : cnValue); certGen.setSubjectDN(subject.getAsName()); certGen.setIssuerDN(issuer.getAsName()); certGen.setSerialNumber(serialNum); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm(issuerCert.getSigAlgName()); GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT")); /* Allow for a five minute clock skew here. */ date.add(Calendar.MINUTE, -5); certGen.setNotBefore(date.getTime()); /* If hours = 0, then cert lifetime is set to user cert */ if (lifetime <= 0) { certGen.setNotAfter(issuerCert.getNotAfter()); } else { date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime); certGen.setNotAfter(date.getTime()); } return certGen.generateX509Certificate(issuerKey); } /** * Loads a X509 certificate from the specified input stream. Input stream must contain DER-encoded * certificate. * * @param in * the input stream to read the certificate from. * @return X509Certificate the loaded certificate. * @exception GeneralSecurityException * if certificate failed to load. */ public X509Certificate loadCertificate(InputStream in) throws IOException, GeneralSecurityException { ASN1InputStream derin = new ASN1InputStream(in); ASN1Primitive certInfo = derin.readObject(); ASN1Sequence seq = ASN1Sequence.getInstance(certInfo); return new X509CertificateObject(Certificate.getInstance(seq)); } /** * Creates a certificate request from the specified subject DN and a key pair. The * "MD5WithRSAEncryption" is used as the signing algorithm of the certificate request. * * @param subject * the subject of the certificate request * @param keyPair * the key pair of the certificate request * @return the certificate request. * @exception GeneralSecurityException * if security error occurs. */ public byte[] createCertificateRequest(String subject, KeyPair keyPair) throws GeneralSecurityException { X509Name name = new X509Name(subject); return createCertificateRequest(name, "MD5WithRSAEncryption", keyPair); } /** * Creates a certificate request from the specified certificate and a key pair. The certificate's subject * DN with "CN=proxy" name component appended to the subject is used as the subject of the * certificate request. Also the certificate's signing algorithm is used as the certificate request * signing algorithm. * * @param cert * the certificate to create the certificate request from. * @param keyPair * the key pair of the certificate request * @return the certificate request. * @exception GeneralSecurityException * if security error occurs. */ public byte[] createCertificateRequest(X509Certificate cert, KeyPair keyPair) throws GeneralSecurityException { String issuer = cert.getSubjectDN().getName(); X509Name subjectDN = new X509Name(issuer + ",CN=proxy"); String sigAlgName = cert.getSigAlgName(); return createCertificateRequest(subjectDN, sigAlgName, keyPair); } /** * Creates a certificate request from the specified subject name, signing algorithm, and a key pair. * * @param subjectDN * the subject name of the certificate request. * @param sigAlgName * the signing algorithm name. * @param keyPair * the key pair of the certificate request * @return the certificate request. * @exception GeneralSecurityException * if security error occurs. */ public byte[] createCertificateRequest(X509Name subjectDN, String sigAlgName, KeyPair keyPair) throws GeneralSecurityException { DERSet attrs = null; PKCS10CertificationRequest certReq = null; certReq = new PKCS10CertificationRequest(sigAlgName, subjectDN, keyPair.getPublic(), attrs, keyPair .getPrivate()); return certReq.getEncoded(); } /** * Given a delegation mode and an issuing certificate, decides an * appropriate certificate type to use for proxies * @param issuerCert the issuing certificate of a prospective proxy * @param delegType the desired delegation mode * @return the appropriate certificate type for proxies or * GSIConstants.CertificateType.UNDEFINED when * GSIConstants.DelegationType.NONE was specified * @throws CertificateException when failing to get the certificate type * of the issuing certificate */ public static GSIConstants.CertificateType decideProxyType( X509Certificate issuerCert, GSIConstants.DelegationType delegType) throws CertificateException { GSIConstants.CertificateType proxyType = GSIConstants.CertificateType.UNDEFINED; if (delegType == GSIConstants.DelegationType.LIMITED) { GSIConstants.CertificateType type = BouncyCastleUtil.getCertificateType(issuerCert); if (ProxyCertificateUtil.isGsi4Proxy(type)) { proxyType = GSIConstants.CertificateType.GSI_4_LIMITED_PROXY; } else if (ProxyCertificateUtil.isGsi3Proxy(type)) { proxyType = GSIConstants.CertificateType.GSI_3_LIMITED_PROXY; } else if (ProxyCertificateUtil.isGsi2Proxy(type)) { proxyType = GSIConstants.CertificateType.GSI_2_LIMITED_PROXY; } else { // default to RFC compliant proxy if (VersionUtil.isGsi2Enabled()) { proxyType = GSIConstants.CertificateType.GSI_2_LIMITED_PROXY; } else { proxyType = VersionUtil.isGsi3Enabled() ? GSIConstants.CertificateType.GSI_3_LIMITED_PROXY : GSIConstants.CertificateType.GSI_4_LIMITED_PROXY; } } } else if (delegType == GSIConstants.DelegationType.FULL) { GSIConstants.CertificateType type = BouncyCastleUtil.getCertificateType(issuerCert); if (ProxyCertificateUtil.isGsi4Proxy(type)) { proxyType = GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY; } else if (ProxyCertificateUtil.isGsi3Proxy(type)) { proxyType = GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY; } else if (ProxyCertificateUtil.isGsi2Proxy(type)) { proxyType = GSIConstants.CertificateType.GSI_2_PROXY; } else { // Default to RFC complaint proxy if (VersionUtil.isGsi2Enabled()) { proxyType = GSIConstants.CertificateType.GSI_2_PROXY; } else { proxyType = (VersionUtil.isGsi3Enabled()) ? GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY : GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY; } } } return proxyType; } /** * Returns a chain of X509Certificate's that are instances of X509CertificateObject * This is related to http://bugzilla.globus.org/globus/show_bug.cgi?id=4933 * @param certs input certificate chain * @return a new chain where all X509Certificate's are instances of X509CertificateObject * @throws GeneralSecurityException when failing to get load certificate from encoding */ protected X509Certificate[] getX509CertificateObjectChain(X509Certificate[] certs) throws GeneralSecurityException { X509Certificate[] bcCerts = new X509Certificate[certs.length]; for (int i = 0; i < certs.length; i++) { if (!(certs[i] instanceof X509CertificateObject)) { bcCerts[i] = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(certs[i].getEncoded())); } else { bcCerts[i] = certs[i]; } } return bcCerts; } } BouncyCastleOpenSSLKey.java000066400000000000000000000135411241116057200332130ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/bc/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.bc; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.Security; import java.security.interfaces.RSAPrivateCrtKey; import java.security.spec.PKCS8EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.globus.gsi.OpenSSLKey; /** * BouncyCastle-based implementation of OpenSSLKey. * * @version ${version} * @since 1.0 */ public class BouncyCastleOpenSSLKey extends OpenSSLKey { private static final long serialVersionUID = 1L; private Log logger = LogFactory.getLog(getClass().getCanonicalName()); static { Security.addProvider(new BouncyCastleProvider()); } /** * Reads a OpenSSL private key from the specified input stream. The private * key must be PEM encoded and can be encrypted. * * @param is * input stream with OpenSSL key in PEM format. * @throws IOException * if I/O problems. * @throws GeneralSecurityException * if problems with the key */ public BouncyCastleOpenSSLKey(InputStream is) throws IOException, GeneralSecurityException { super(is); } /** * Reads a OpenSSL private key from the specified file. The private key must * be PEM encoded and can be encrypted. * * @param file * file containing the OpenSSL key in PEM format. * @throws IOException * if I/O problems. * @throws GeneralSecurityException * if problems with the key */ public BouncyCastleOpenSSLKey(String file) throws IOException, GeneralSecurityException { super(file); } /** * Converts a RSAPrivateCrtKey into OpenSSL key. * * @param key * private key - must be a RSAPrivateCrtKey */ public BouncyCastleOpenSSLKey(PrivateKey key) { super(key); } /** * Initializes the OpenSSL key from raw byte array. * * @param algorithm * the algorithm of the key. Currently only RSA algorithm is * supported. * @param data * the DER encoded key data. If RSA algorithm, the key must be in * PKCS#1 format. * @throws GeneralSecurityException * if any security problems. */ public BouncyCastleOpenSSLKey(String algorithm, byte[] data) throws GeneralSecurityException { super(algorithm, data); } protected PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException { if (alg.equals("RSA")) { try { if (data.length == 0) { throw new GeneralSecurityException( "Cannot process empty byte stream."); } ByteArrayInputStream bis = new ByteArrayInputStream(data); ASN1InputStream derin = new ASN1InputStream(bis); ASN1Primitive keyInfo = derin.readObject(); DERObjectIdentifier rsaOid = PKCSObjectIdentifiers.rsaEncryption; AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsaOid); PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo); ASN1Primitive derkey = pkeyinfo.toASN1Primitive(); byte[] keyData = BouncyCastleUtil.toByteArray(derkey); // The DER object needs to be mangled to // create a proper ProvateKeyInfo object PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData); KeyFactory kfac = KeyFactory.getInstance("RSA"); return kfac.generatePrivate(spec); } catch (IOException e) { // that should never happen return null; } } else { return null; } } protected byte[] getEncoded(PrivateKey key) { String format = key.getFormat(); if (format != null && (format.equalsIgnoreCase("PKCS#8") || format .equalsIgnoreCase("PKCS8"))) { try { ASN1Primitive keyInfo = BouncyCastleUtil.toASN1Primitive(key .getEncoded()); PrivateKeyInfo pkey = new PrivateKeyInfo((ASN1Sequence) keyInfo); ASN1Primitive derKey = pkey.getPrivateKey(); return BouncyCastleUtil.toByteArray(derKey); } catch (IOException e) { // that should never happen logger.warn("This shouldn't have happened.", e); return new byte[] {}; } } else if (format != null && format.equalsIgnoreCase("PKCS#1") && key instanceof RSAPrivateCrtKey) { // this condition will rarely be true RSAPrivateCrtKey pKey = (RSAPrivateCrtKey) key; RSAPrivateKeyStructure st = new RSAPrivateKeyStructure(pKey .getModulus(), pKey.getPublicExponent(), pKey .getPrivateExponent(), pKey.getPrimeP(), pKey.getPrimeQ(), pKey.getPrimeExponentP(), pKey.getPrimeExponentQ(), pKey .getCrtCoefficient()); ASN1Primitive ob = st.toASN1Primitive(); try { return BouncyCastleUtil.toByteArray(ob); } catch (IOException e) { // that should never happen return new byte[0]; } } else { return new byte[0]; } } protected String getProvider() { return "BC"; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java000066400000000000000000000531031241116057200322510ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.bc; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.Security; import java.security.cert.CertStore; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.Collection; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName; import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.TBSCertificateStructure; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.globus.gsi.GSIConstants; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.TrustedCertificatesUtil; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.globus.gsi.proxy.ext.ProxyPolicy; import org.globus.gsi.util.ProxyCertificateUtil; import org.globus.util.I18n; // COMMENT: BCB: removed methods createCertificateType(...) that took a TBSCertificateStructure as parameter /** * A collection of various utility functions. */ public class BouncyCastleUtil { static { Security.addProvider(new BouncyCastleProvider()); } private static I18n i18n = I18n.getI18n("org.globus.gsi.errors", BouncyCastleUtil.class.getClassLoader()); /** * Converts given DERObject into * a DER-encoded byte array. * * @param obj DERObject to convert. * @return the DER-encoded byte array * @exception IOException if conversion fails */ public static byte[] toByteArray(ASN1Primitive obj) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DEROutputStream der = new DEROutputStream(bout); der.writeObject(obj); return bout.toByteArray(); } /** * Converts the DER-encoded byte array into a * DERObject. * * @param data the DER-encoded byte array to convert. * @return the DERObject. * @exception IOException if conversion fails */ public static ASN1Primitive toASN1Primitive(byte[] data) throws IOException { ByteArrayInputStream inStream = new ByteArrayInputStream(data); ASN1InputStream derInputStream = new ASN1InputStream(inStream); return derInputStream.readObject(); } /** * Replicates a given DERObject. * * @param obj the DERObject to replicate. * @return a copy of the DERObject. * @exception IOException if replication fails */ public static ASN1Primitive duplicate(ASN1Primitive obj) throws IOException { return toASN1Primitive(toByteArray(obj)); } /** * Extracts the TBS certificate from the given certificate. * * @param cert the X.509 certificate to extract the TBS certificate from. * @return the TBS certificate * @exception IOException if extraction fails. * @exception CertificateEncodingException if extraction fails. */ public static TBSCertificateStructure getTBSCertificateStructure(X509Certificate cert) throws CertificateEncodingException, IOException { ASN1Primitive obj = BouncyCastleUtil.toASN1Primitive(cert.getTBSCertificate()); return TBSCertificateStructure.getInstance(obj); } /** * Extracts the value of a certificate extension. * * @param ext the certificate extension to extract the value from. * @exception IOException if extraction fails. */ public static ASN1Primitive getExtensionObject(X509Extension ext) throws IOException { return toASN1Primitive(ext.getValue().getOctets()); } /** * Returns certificate type of the given certificate. * Please see {@link #getCertificateType(TBSCertificateStructure, * TrustedCertificates) getCertificateType} for details for * determining the certificate type. * * @param cert the certificate to get the type of. * @param trustedCerts the trusted certificates to double check the * {@link GSIConstants#EEC GSIConstants.EEC} * certificate against. * @return the certificate type as determined by * {@link #getCertificateType(TBSCertificateStructure, * TrustedCertificates) getCertificateType}. * @exception CertificateException if something goes wrong. * @deprecated */ public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, TrustedCertificates trustedCerts) throws CertificateException { try { return getCertificateType(cert, TrustedCertificatesUtil.createCertStore(trustedCerts)); } catch (Exception e) { throw new CertificateException("", e); } } /** * Returns the certificate type of the given certificate. * Please see {@link #getCertificateType(TBSCertificateStructure, * TrustedCertificates) getCertificateType} for details for * determining the certificate type. * * @param cert the certificate to get the type of. * @param trustedCerts the trusted certificates to double check the * {@link GSIConstants#EEC GSIConstants.EEC} * certificate against. * @return the certificate type as determined by * {@link #getCertificateType(TBSCertificateStructure, * TrustedCertificates) getCertificateType}. * @exception CertificateException if something goes wrong. */ public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, CertStore trustedCerts) throws CertificateException { try { TBSCertificateStructure crt = getTBSCertificateStructure(cert); GSIConstants.CertificateType type = getCertificateType(crt); // check subject of the cert in trusted cert list // to make sure the cert is not a ca cert if (type == GSIConstants.CertificateType.EEC) { X509CertSelector selector = new X509CertSelector(); selector.setSubject(cert.getSubjectX500Principal()); Collection c = trustedCerts.getCertificates(selector); if (c != null && c.size() > 0) { type = GSIConstants.CertificateType.CA; } } return type; } catch (Exception e) { // but this should not happen throw new CertificateException("", e); } } /** * Returns certificate type of the given certificate. * Please see {@link #getCertificateType(TBSCertificateStructure) * getCertificateType} for details for determining the certificate type. * * @param cert the certificate to get the type of. * @return the certificate type as determined by * {@link #getCertificateType(TBSCertificateStructure) * getCertificateType}. * @exception CertificateException if something goes wrong. */ public static GSIConstants.CertificateType getCertificateType(X509Certificate cert) throws CertificateException { try { TBSCertificateStructure crt = getTBSCertificateStructure(cert); return getCertificateType(crt); } catch (IOException e) { // but this should not happen throw new CertificateException("", e); } } public static GSIConstants.CertificateType getCertificateType(TBSCertificateStructure crt, TrustedCertificates trustedCerts) throws CertificateException, IOException { GSIConstants.CertificateType type = getCertificateType(crt); // check subject of the cert in trusted cert list // to make sure the cert is not a ca cert if (type == GSIConstants.CertificateType.EEC) { if (trustedCerts == null) { trustedCerts = TrustedCertificates.getDefaultTrustedCertificates(); } if (trustedCerts != null && trustedCerts.getCertificate(crt.getSubject().toString()) != null) { type = GSIConstants.CertificateType.CA; } } return type; } /** * Returns certificate type of the given TBS certificate.
    * The certificate type is {@link GSIConstants#CA GSIConstants.CA} * only if the certificate contains a * BasicConstraints extension and it is marked as CA.
    * A certificate is a GSI-2 proxy when the subject DN of the certificate * ends with "CN=proxy" (certificate type {@link * GSIConstants#GSI_2_PROXY GSIConstants.GSI_2_PROXY}) or * "CN=limited proxy" (certificate type {@link * GSIConstants#GSI_2_LIMITED_PROXY GSIConstants.LIMITED_PROXY}) component * and the issuer DN of the certificate matches the subject DN without * the last proxy CN component.
    * A certificate is a GSI-3 proxy when the subject DN of the certificate * ends with a CN component, the issuer DN of the certificate * matches the subject DN without the last CN component and * the certificate contains {@link ProxyCertInfo ProxyCertInfo} critical * extension. * The certificate type is {@link GSIConstants#GSI_3_IMPERSONATION_PROXY * GSIConstants.GSI_3_IMPERSONATION_PROXY} if the policy language of * the {@link ProxyCertInfo ProxyCertInfo} extension is set to * {@link ProxyPolicy#IMPERSONATION ProxyPolicy.IMPERSONATION} OID. * The certificate type is {@link GSIConstants#GSI_3_LIMITED_PROXY * GSIConstants.GSI_3_LIMITED_PROXY} if the policy language of * the {@link ProxyCertInfo ProxyCertInfo} extension is set to * {@link ProxyPolicy#LIMITED ProxyPolicy.LIMITED} OID. * The certificate type is {@link GSIConstants#GSI_3_INDEPENDENT_PROXY * GSIConstants.GSI_3_INDEPENDENT_PROXY} if the policy language of * the {@link ProxyCertInfo ProxyCertInfo} extension is set to * {@link ProxyPolicy#INDEPENDENT ProxyPolicy.INDEPENDENT} OID. * The certificate type is {@link GSIConstants#GSI_3_RESTRICTED_PROXY * GSIConstants.GSI_3_RESTRICTED_PROXY} if the policy language of * the {@link ProxyCertInfo ProxyCertInfo} extension is set to * any other OID then the above.
    * The certificate type is {@link GSIConstants#EEC GSIConstants.EEC} * if the certificate is not a CA certificate or a GSI-2 or GSI-3 proxy. * * @param crt the TBS certificate to get the type of. * @return the certificate type. The certificate type is determined * by rules described above. * @exception IOException if something goes wrong. * @exception CertificateException for proxy certificates, if * the issuer DN of the certificate does not match * the subject DN of the certificate without the * last CN component. Also, for GSI-3 proxies * when the ProxyCertInfo extension is * not marked as critical. */ private static GSIConstants.CertificateType getCertificateType(TBSCertificateStructure crt) throws CertificateException, IOException { X509Extensions extensions = crt.getExtensions(); X509Extension ext = null; if (extensions != null) { ext = extensions.getExtension(X509Extension.basicConstraints); if (ext != null) { BasicConstraints basicExt = BasicConstraints.getInstance(ext); if (basicExt.isCA()) { return GSIConstants.CertificateType.CA; } } } GSIConstants.CertificateType type = GSIConstants.CertificateType.EEC; // does not handle multiple AVAs X500Name subject = crt.getSubject(); ASN1Set entry = X509NameHelper.getLastNameEntry(subject); ASN1Sequence ava = (ASN1Sequence)entry.getObjectAt(0); if (BCStyle.CN.equals(ava.getObjectAt(0))) { String value = ((ASN1String)ava.getObjectAt(1)).getString(); if (value.equalsIgnoreCase("proxy")) { type = GSIConstants.CertificateType.GSI_2_PROXY; } else if (value.equalsIgnoreCase("limited proxy")) { type = GSIConstants.CertificateType.GSI_2_LIMITED_PROXY; } else if (extensions != null) { boolean gsi4 = true; // GSI_4 ext = extensions.getExtension(ProxyCertInfo.OID); if (ext == null) { // GSI_3 ext = extensions.getExtension(ProxyCertInfo.OLD_OID); gsi4 = false; } if (ext != null) { if (ext.isCritical()) { ProxyCertInfo proxyCertExt = getProxyCertInfo(ext); ProxyPolicy proxyPolicy = proxyCertExt.getProxyPolicy(); DERObjectIdentifier oid = proxyPolicy.getPolicyLanguage(); if (ProxyPolicy.IMPERSONATION.equals(oid)) { if (gsi4) { type = GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY; } else { type = GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY; } } else if (ProxyPolicy.INDEPENDENT.equals(oid)) { if (gsi4) { type = GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY; } else { type = GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY; } } else if (ProxyPolicy.LIMITED.equals(oid)) { if (gsi4) { type = GSIConstants.CertificateType.GSI_4_LIMITED_PROXY; } else { type = GSIConstants.CertificateType.GSI_3_LIMITED_PROXY; } } else { if (gsi4) { type = GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY; } else { type = GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY; } } } else { String err = i18n.getMessage("proxyCertCritical"); throw new CertificateException(err); } } } if (ProxyCertificateUtil.isProxy(type)) { X509NameHelper iss = new X509NameHelper(crt.getIssuer()); iss.add((ASN1Set)BouncyCastleUtil.duplicate(entry)); X509Name issuer = iss.getAsName(); if (!issuer.equals(X509Name.getInstance(subject))) { String err = i18n.getMessage("proxyDNErr"); throw new CertificateException(err); } } } return type; } /** * Gets a boolean array representing bits of the KeyUsage extension. * * @see java.security.cert.X509Certificate#getKeyUsage * @exception IOException if failed to extract the KeyUsage extension value. */ public static boolean[] getKeyUsage(X509Extension ext) throws IOException { DERBitString bits = (DERBitString)getExtensionObject(ext); // copied from X509CertificateObject byte [] bytes = bits.getBytes(); int length = (bytes.length * 8) - bits.getPadBits(); boolean[] keyUsage = new boolean[(length < 9) ? 9 : length]; for (int i = 0; i != length; i++) { keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; } return keyUsage; } /** * Creates a ProxyCertInfo object from given * extension. * * @param ext the extension. * @return the ProxyCertInfo object. * @exception IOException if something fails. */ public static ProxyCertInfo getProxyCertInfo(X509Extension ext) throws IOException { return ProxyCertInfo.getInstance(BouncyCastleUtil.getExtensionObject(ext)); } /** * Returns the subject DN of the given certificate in the Globus format. * * @param cert the certificate to get the subject of. The certificate * must be of X509CertificateObject type. * @return the subject DN of the certificate in the Globus format. */ public static String getIdentity(X509Certificate cert) { if (cert == null) { return null; } String subjectDN = cert.getSubjectX500Principal().getName(X500Principal.RFC2253); X509Name name = new X509Name(true, subjectDN); return X509NameHelper.toString(name); } public static String getIdentityPrefix(X509Certificate cert) { if (cert == null) { return null; } String subjectDN = cert.getSubjectX500Principal().getName(X500Principal.RFC2253); LdapName ldapname = null; try { ldapname = new LdapName(subjectDN); ldapname.remove(ldapname.size() - 1); } catch (InvalidNameException e) { return null; } X509Name name = new X509Name(true, ldapname.toString()); return X509NameHelper.toString(name); } /** * Finds the identity certificate in the given chain and * returns the subject DN of that certificate in the Globus format. * * @param chain the certificate chain to find the identity * certificate in. The certificates must be * of X509CertificateObject type. * @return the subject DN of the identity certificate in * the Globus format. * @exception CertificateException if something goes wrong. */ public static String getIdentity(X509Certificate [] chain) throws CertificateException { return getIdentity(getIdentityCertificate(chain)); } /** * Finds the identity certificate in the given chain. * The identity certificate is the first certificate in the * chain that is not an impersonation proxy (full or limited) * * @param chain the certificate chain to find the identity * certificate in. * @return the identity certificate. * @exception CertificateException if something goes wrong. */ public static X509Certificate getIdentityCertificate(X509Certificate [] chain) throws CertificateException { if (chain == null) { throw new IllegalArgumentException(i18n.getMessage("certChainNull")); } GSIConstants.CertificateType certType; for (int i=0;iDEREncodable objects. */ public class BouncyCastleX509Extension extends X509Extension { private static I18n i18n = I18n.getI18n("org.globus.gsi.errors", BouncyCastleX509Extension.class.getClassLoader()); public BouncyCastleX509Extension(String oid) { this(oid, false, null); } public BouncyCastleX509Extension(String oid, ASN1Encodable value) { this(oid, false, value); } public BouncyCastleX509Extension(String oid, boolean critical, ASN1Encodable value) { super(oid, critical, null); setValue(value); } protected void setValue(ASN1Encodable value) { if (value == null) { return; } try { setValue(BouncyCastleUtil.toByteArray(value.toASN1Primitive())); } catch (IOException e) { throw new RuntimeException(i18n.getMessage("byteArrayErr") + e.getMessage()); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/bc/X509NameHelper.java000066400000000000000000000140511241116057200314250ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.bc; import java.io.IOException; import java.util.Enumeration; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DERPrintableString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.X509Name; /** * A helper class to deal with {@link X509Name X509Name} object. */ public class X509NameHelper { private ASN1Sequence seq; /** * Creates an instance using the specified ASN.1 sequence. * * @param seq the name sequence */ public X509NameHelper(ASN1Sequence seq) { this.seq = seq; } /** * Creates an instance using existing {@link X500Name X500Name} * object. * This behaves like a copy constructor. * * @param name existing X500Name */ public X509NameHelper(X500Name name) { try { this.seq = (ASN1Sequence)BouncyCastleUtil.duplicate(name.toASN1Primitive()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } /** * Creates an instance using existing {@link X509Name X509Name} * object. * This behaves like a copy constructor. * * @param name existing X509Name */ public X509NameHelper(X509Name name) { try { this.seq = (ASN1Sequence)BouncyCastleUtil.duplicate(name.toASN1Primitive()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } /** * Converts to {@link X509Name X509Name} object. * * @return the X509Name object. */ public X509Name getAsName() { return new X509Name(this.seq); } /** * Appends the specified OID and value pair name component to the end of the * current name. * * @param oid the name component oid, e.g. {@link org.bouncycastle.asn1.x500.style.BCStyle#CN * BCStyle.CN} * @param value the value (e.g. "proxy") */ public void add( DERObjectIdentifier oid, String value) { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(oid); v.add(new DERPrintableString(value)); add(new DERSet(new DERSequence(v))); } /** * Appends the specified name component entry to the current name. This can * be used to add handle multiple AVAs in one name component. * * @param entry the name component to add. */ public void add(ASN1Set entry) { ASN1EncodableVector v = new ASN1EncodableVector(); int size = seq.size(); for (int i = 0; i < size; i++) { v.add(seq.getObjectAt(i)); } v.add(entry); seq = new DERSequence(v); } /** * Gets the name component at specified position. * * @return the name component the specified position. */ public ASN1Set getNameEntryAt(int i) { return (ASN1Set) seq.getObjectAt(i); } /** * Gets the last name component in the current name. * * @return the last name component. Null if there is none. */ public ASN1Set getLastNameEntry() { int size = seq.size(); return (size > 0) ? getNameEntryAt(size - 1) : null; } /** * Gets the last name component from the {@link X509Name X509Name} name. * * @return the last name component. Null if there is none. */ public static ASN1Set getLastNameEntry(X500Name name) { RDN[] rdns = name.getRDNs(); int size = rdns.length; return (size > 0) ? (ASN1Set) rdns[size - 1].toASN1Primitive() : null; } /** * Returns Globus format representation of the name. It handles names with * multiple AVAs. * * @param name the name to get the Globus format of. * @return the Globus format of the name */ public static String toString(X509Name name) { if (name == null) { return null; } return toString((ASN1Sequence)name.toASN1Primitive()); } private static String toString(ASN1Sequence seq) { if (seq == null) { return null; } Enumeration e = seq.getObjects(); StringBuffer buf = new StringBuffer(); while (e.hasMoreElements()) { ASN1Set set = (ASN1Set)e.nextElement(); Enumeration ee = set.getObjects(); buf.append('/'); while (ee.hasMoreElements()) { ASN1Sequence s = (ASN1Sequence)ee.nextElement(); DERObjectIdentifier oid = (DERObjectIdentifier)s.getObjectAt(0); String sym = (String)X509Name.DefaultSymbols.get(oid); if (sym == null) { buf.append(oid.getId()); } else { buf.append(sym); } buf.append('='); buf.append(((ASN1String)s.getObjectAt(1)).getString()); if (ee.hasMoreElements()) { buf.append('+'); } } } return buf.toString(); } /** * Returns Globus format representation of the name. */ public String toString() { return toString(this.seq); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gridmap/000077500000000000000000000000001241116057200272125ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gridmap/GridMap.java000066400000000000000000000421561241116057200314100ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gridmap; import java.util.Map; import java.util.Vector; import java.util.HashMap; import java.util.Iterator; import java.util.StringTokenizer; import java.io.IOException; import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.Serializable; import org.globus.util.I18n; import org.globus.util.QuotedStringTokenizer; import org.globus.util.ConfigUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class GridMap implements Serializable { private static I18n i18n = I18n.getI18n("org.globus.gsi.gridmap.errors", GridMap.class.getClassLoader()); private static Log logger = LogFactory.getLog(GridMap.class.getName()); private static final String COMMENT_CHARS = "#"; // keywords that need to be replaced private static final char[] EMAIL_KEYWORD_1 = { 'e', '=' }; private static final char[] EMAIL_KEYWORD_2 = { 'e', 'm', 'a', 'i', 'l', '=' }; private static final char[] UID_KEYWORD = { 'u', 'i', 'd', '=' }; // Length of key words that need to be replaced private static final int EMAIL_KEYWORD_1_L = 2; private static final int EMAIL_KEYWORD_2_L = 6; private static final int UID_KEYWORD_L = 4; // Keywords to be replaced with. private static final String EMAIL_KEYWORD = "emailaddress="; private static final String USERID_KEYWORD = "userid="; protected Map map; // the file the grim map was loaded from private File file; // last time the file was modified private long lastModified; // log or throw exception on bad entries private boolean ignoreErrors = false; /** * Sets whether errors in the gridmap file * should be ignored. Errors are not ignored by default. * * @param ignoreErrors if true, errors in the gridmap file * will be ignored (warnings will be logged). If false, * an exception will be raised on errors. */ public void setIgnoreErrors(boolean ignoreErrors) { this.ignoreErrors = ignoreErrors; } /** * Returns whether errors in the gridmap file are * ignored. * * @return true if errors in the gridmap file are ignored. * False, otherwise. */ public boolean getIgnoreErrors() { return this.ignoreErrors; } /** * Returns the absolute path anme of file used to load gridmap * either using the {@link #load(File) load} or {@link * #load(String) load} functions. If no file was used, returns * null. * * @return absolute file path, if gridmap was loaded from * file. Null otherwise. */ public String getFileName() { if (this.file == null) { return null; } return this.file.getAbsolutePath(); } /** * Loads grid map definition from a given file. * * @param file the grid map file * @exception IOException in case of I/O error or * when there are parsing errors in the file (only when errors * are not ignored). * @return true if the file was parsed and loaded successfully. * False otherwise. */ public boolean load(String file) throws IOException { return load(new File(file)); } /** * Loads grid map definition from a given file. * * @param file the grid map file * @exception IOException in case of I/O error or * when there are parsing errors in the file (only when errors * are not ignored). * @return true if the file was parsed and loaded successfully. * False otherwise. */ public boolean load(File file) throws IOException { InputStream in = null; try { in = new FileInputStream(file); this.file = file; this.lastModified = file.lastModified(); return load(in); } finally { if (in != null) { try { in.close(); } catch(Exception e) {} } } } /** * Reloads the gridmap from a file only if the gridmap * was initially loaded using the {@link #load(File) * load} or {@link #load(String) load} functions. * The file will only be reloaded if it has changed * since the last time. * * @exception IOException in case of I/O error or * when there are parsing errors in the file (only when errors * are not ignored). * @return true if the file was parsed and refreshed successfully. * False otherwise. */ public boolean refresh() throws IOException { if (this.file != null && this.file.lastModified() != this.lastModified) { return load(this.file); } else { return true; } } /** * Loads grid map file definition from a given input stream. The input * stream is not closed in case of an error. * * @param input the input stream that contains the gridmap * definitions. * @exception IOException in case of I/O error or * when there are parsing errors in the input (only when errors * are not ignored). * @return true if the input was parsed successfully. * False otherwise. */ public boolean load(InputStream input) throws IOException { boolean success = true; BufferedReader reader = new BufferedReader(new InputStreamReader(input)); Map localMap = new HashMap(); GridMapEntry entry; QuotedStringTokenizer tokenizer; StringTokenizer idTokenizer; String line; while( (line = reader.readLine()) != null) { line = line.trim(); if ( (line.length() == 0) || ( COMMENT_CHARS.indexOf(line.charAt(0)) != -1) ) { continue; } tokenizer = new QuotedStringTokenizer(line); String globusID = null; if (tokenizer.hasMoreTokens()) { globusID = tokenizer.nextToken(); } else { if (this.ignoreErrors) { success = false; logger.warn("Globus ID missing: " + line); continue; } else { throw new IOException(i18n.getMessage("globusIdErr", line)); } } String userIDs = null; if (tokenizer.hasMoreTokens()) { userIDs = tokenizer.nextToken(); } else { if (this.ignoreErrors) { success = false; logger.warn("User ID mapping missing: " + line); continue; } else { throw new IOException(i18n.getMessage("userIdErr", line)); } } idTokenizer = new StringTokenizer(userIDs, ","); String [] ids = new String [ idTokenizer.countTokens() ]; int i = 0; while(idTokenizer.hasMoreTokens()) { ids[i++] = idTokenizer.nextToken(); } String normalizedDN = normalizeDN(globusID); entry = (GridMapEntry)localMap.get(normalizedDN); if (entry == null) { entry = new GridMapEntry(); entry.setGlobusID(globusID); entry.setUserIDs(ids); localMap.put(normalizedDN, entry); } else { entry.addUserIDs(ids); } } this.map = localMap; return success; } /** * Returns first local user name mapped to the specified * globusID. * * @param globusID globusID * @return local user name for the specified globusID. * Null if the globusID is not mapped * to a local user name. */ public String getUserID(String globusID) { String [] ids = getUserIDs(globusID); if (ids != null && ids.length > 0) { return ids[0]; } else { return null; } } /** * Returns local user names mapped to the specified * globusID. * * @param globusID globusID * @return array of local user names for the specified globusID. * Null if the globusID is not mapped * to any local user name. */ public String[] getUserIDs(String globusID) { if (globusID == null) { throw new IllegalArgumentException(i18n .getMessage("globusIdNull")); } if (this.map == null) { return null; } GridMapEntry entry = (GridMapEntry)this.map.get(normalizeDN(globusID)); return (entry == null) ? null : entry.getUserIDs(); } /** * Checks if a given globus ID is associated with given * local user account. * * @param globusID globus ID * @param userID userID * @return true if globus ID is associated with given local * user account, false, otherwise. */ public boolean checkUser(String globusID, String userID) { if (globusID == null) { throw new IllegalArgumentException(i18n.getMessage("glousIdNull")); } if (userID == null) { throw new IllegalArgumentException(i18n.getMessage("userIdNull")); } if (this.map == null) { return false; } GridMapEntry entry = (GridMapEntry)this.map.get(normalizeDN(globusID)); return (entry == null) ? false : entry.containsUserID(userID); } /** * Returns globus ID associated with the * specified local user name. * * @param userID local user name * @return associated globus ID, null * if there is not any. */ public String getGlobusID(String userID) { if (userID == null) { throw new IllegalArgumentException(i18n.getMessage("userIdNull")); } if (this.map == null) { return null; } Iterator iter = this.map.entrySet().iterator(); Map.Entry mapEntry; GridMapEntry entry; while(iter.hasNext()) { mapEntry = (Map.Entry)iter.next(); entry = (GridMapEntry)mapEntry.getValue(); if (entry.containsUserID(userID)) { return entry.getGlobusID(); } } return null; } /** * Returns all globus IDs associated with the * specified local user name. * * @param userID local user name * @return associated globus ID, null * if there is not any. */ public String[] getAllGlobusID(String userID) { if (userID == null) { throw new IllegalArgumentException(i18n.getMessage("userIdNull")); } if (this.map == null) { return null; } Vector v = new Vector(); Iterator iter = this.map.entrySet().iterator(); Map.Entry mapEntry; GridMapEntry entry; while(iter.hasNext()) { mapEntry = (Map.Entry)iter.next(); entry = (GridMapEntry)mapEntry.getValue(); if (entry.containsUserID(userID)) { v.add(entry.getGlobusID()); } } // create array of strings and add values back in if(v.size() == 0) { return null; } String idS[] = new String[v.size()]; for(int ctr = 0; ctr < v.size(); ctr++) { idS[ctr] = (String) v.elementAt(ctr); } return idS; } public void map(String globusID, String userID) { if (globusID == null) { throw new IllegalArgumentException(i18n .getMessage("globusIdNull")); } if (userID == null) { throw new IllegalArgumentException(i18n.getMessage("userIdNull")); } if (this.map == null) { this.map = new HashMap(); } String normalizedDN = normalizeDN(globusID); GridMapEntry entry = (GridMapEntry)this.map.get(normalizedDN); if (entry == null) { entry = new GridMapEntry(); entry.setGlobusID(globusID); entry.setUserIDs(new String [] {userID}); this.map.put(normalizedDN, entry); } else { entry.addUserID(userID); } } static class GridMapEntry implements Serializable { String globusID; String[] userIDs; public String getFirstUserID() { return userIDs[0]; } public String[] getUserIDs() { return userIDs; } public String getGlobusID() { return globusID; } public void setGlobusID(String globusID) { this.globusID = globusID; } public void setUserIDs(String [] userIDs) { this.userIDs = userIDs; } public boolean containsUserID(String userID) { if (userID == null) { return false; } for (int i=0;i args.length) { return false; } int j=startIndex; for (int i=0; igetUserID, getUserIDs, * and checkUser functions will effectively ignore their * globusID parameter. For example, getUserID and * getUserIDs will return the local user name for any * globusID. */ public class GridMapLocal extends GridMap { public String[] getUserIDs(String globusID) { String [] userIDs = super.getUserIDs(globusID); if (userIDs == null && this.map == null) { String user = getLocalUsername(); return (user == null) ? null : new String[] {user}; } return userIDs; } public boolean checkUser(String globusID, String userID) { boolean result = super.checkUser(globusID, userID); if (!result && this.map == null) { String user = getLocalUsername(); return (user == null) ? false : user.equalsIgnoreCase(userID); } return result; } private String getLocalUsername() { String user = System.getProperty("user.name"); if (user == null) { return null; } String tmpUser = user.toLowerCase(); return (tmpUser.equals("root") || tmpUser.equals("administrator")) ? null : user; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/000077500000000000000000000000001241116057200270555ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/000077500000000000000000000000001241116057200277735ustar00rootroot00000000000000GlobusPrincipal.java000066400000000000000000000015261241116057200336600ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.jaas; /** * A Globus DN principal. The Globus DN is in the form: "/CN=foo/O=bar". */ public class GlobusPrincipal extends SimplePrincipal { public GlobusPrincipal(String globusDn) { super(globusDn); } } GlobusSubject.java000066400000000000000000000053201241116057200333320ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.jaas; import javax.security.auth.Subject; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; import java.util.LinkedList; /** * An implementation of the JaasSubject API to circumvent * the JAAS problem of Subject propagation. The implementation uses * a stackable version of * {@link java.lang.InheritableThreadLocal InheritableThreadLocal} * class to associate the Subject object with the current thread. * Any new thread started within a thread that has a Subject object * associated with it, will inherit the parent's Subject object. * Also, nested doAs, runAs calls are supported. */ public class GlobusSubject extends JaasSubject { private static StackableInheritableThreadLocal subjects = new StackableInheritableThreadLocal(); protected GlobusSubject() { super(); } public Subject getSubject() { return (Subject)subjects.peek(); } public Object runAs(Subject subject, PrivilegedAction action) { subjects.push(subject); try { return Subject.doAs(subject, action); } finally { subjects.pop(); } } public Object runAs(Subject subject, PrivilegedExceptionAction action) throws PrivilegedActionException { subjects.push(subject); try { return Subject.doAs(subject, action); } finally { subjects.pop(); } } } class StackableInheritableThreadLocal extends InheritableThreadLocal { protected Object initialValue() { return new LinkedList(); } protected Object childValue(Object parentValue) { LinkedList list = (LinkedList)parentValue; LinkedList newList = new LinkedList(); if (!list.isEmpty()) { newList.add(list.getLast()); } return newList; } public void push(Object object) { LinkedList list = (LinkedList)get(); list.add(object); } public Object pop() { LinkedList list = (LinkedList)get(); return (list.isEmpty()) ? null : list.removeLast(); } public Object peek() { LinkedList list = (LinkedList)get(); return (list.isEmpty()) ? null : list.getLast(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/JaasSubject.java000066400000000000000000000076001241116057200330370ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.jaas; import org.globus.util.I18n; import javax.security.auth.Subject; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; /** * Generic JAAS Subject helper API that provides abstraction layer on top of * vendor-specific JAAS Subject extensions implementations. * Most vendors defined their own JAAS Subject helper classes because of the * * Subject propagation issue in JAAS. */ public abstract class JaasSubject { private static I18n i18n = I18n.getI18n("org.globus.gsi.gssapi.errors", JaasSubject.class.getClassLoader()); private static JaasSubject subject; protected JaasSubject() {} /** * Gets current implementation of the JaasSubject API. * The method attempts to load a JaasSubject implementation * by loading a class specified by the * "org.globus.jaas.provider" system property. If the property * is not set the default Globus implementation is loaded. */ public static synchronized JaasSubject getJaasSubject() { if (subject == null) { String className = System.getProperty("org.globus.jaas.provider"); if (className == null) { className = "org.globus.gsi.gssapi.jaas.GlobusSubject"; } try { Class clazz = Class.forName(className); if (!JaasSubject.class.isAssignableFrom(clazz)) { throw new RuntimeException(i18n.getMessage("invalidJaasSubject", className)); } subject = (JaasSubject)clazz.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException(i18n.getMessage("loadError", className) + e.getMessage()); } catch (InstantiationException e) { throw new RuntimeException(i18n.getMessage("instanError", className) + e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException(i18n.getMessage("instanError", className), e); } } return subject; } // SPI /** * SPI method. */ public abstract Subject getSubject(); /** * SPI method. */ public abstract Object runAs(Subject subject, PrivilegedAction action); /** * SPI method. */ public abstract Object runAs(Subject subject, PrivilegedExceptionAction action) throws PrivilegedActionException; // API /** * A convenience method, calls * JaasSubject.getJaasSubject().runAs(). */ public static Object doAs(Subject subject, PrivilegedExceptionAction action) throws PrivilegedActionException { return JaasSubject.getJaasSubject().runAs(subject, action); } /** * A convenience method, calls * JaasSubject.getJaasSubject().runAs(). */ public static Object doAs(Subject subject, PrivilegedAction action) { return JaasSubject.getJaasSubject().runAs(subject, action); } /** * A convenience method, calls * JaasSubject.getJaasSubject().getSubject(). */ public static Subject getCurrentSubject() { return JaasSubject.getJaasSubject().getSubject(); } } PasswordCredential.java000066400000000000000000000024251241116057200343570ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.jaas; import java.io.Serializable; public class PasswordCredential implements Serializable { private char[] password; public PasswordCredential(String password) { this.password = password.toCharArray(); } public String getPassword() { return new String(this.password); } public boolean equals(Object another) { if (!(another instanceof PasswordCredential)) { return false; } String pass = ((PasswordCredential)another).getPassword(); if (this.password == null) { return (pass == null); } else { return (new String(this.password)).equals(pass); } } public String toString() { return getPassword(); } } SimplePrincipal.java000066400000000000000000000026421241116057200336560ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.jaas; import java.security.Principal; import java.io.Serializable; /** * Simple string-based principal. */ public class SimplePrincipal implements Principal, Serializable { private String name; public SimplePrincipal() { } public SimplePrincipal(String name) { this.name = name; } public String getName() { return this.name; } public int hashCode() { return (this.name == null) ? 0 : this.name.hashCode(); } public boolean equals(Object another) { if (!(another instanceof Principal)) { return false; } String anotherName = ((Principal)another).getName(); if (this.name == null) { return (this.name == anotherName); } else { return this.name.equals(anotherName); } } public String toString() { return getName(); } } StandardSubject.java000066400000000000000000000027501241116057200336430ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.jaas; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; import javax.security.auth.Subject; /** * Standard JAAS implementation of the JAAS Subject helper API. * This implementation (because of a problem in JAAS) can cut off * the Subject object from the thread context. */ public class StandardSubject extends JaasSubject { protected StandardSubject() { super(); } public Subject getSubject() { return Subject.getSubject(AccessController.getContext()); } public Object runAs(Subject subject, PrivilegedAction action) { return Subject.doAs(subject, action); } public Object runAs(Subject subject, PrivilegedExceptionAction action) throws PrivilegedActionException { return Subject.doAs(subject, action); } } UserNamePrincipal.java000066400000000000000000000015761241116057200341510ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gssapi.jaas; /** * An user name principal. Represents the user name (the account) the user * is mapped in the gridmap file. */ public class UserNamePrincipal extends SimplePrincipal { public UserNamePrincipal(String username) { super(username); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/package-info.java000066400000000000000000000013211241116057200307530ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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. */ /** * This package conatins the basic security constructs used to build Globus security. */ package org.globus.gsi;JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/000077500000000000000000000000001241116057200274215ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/GlobusProvider.java000066400000000000000000000042771241116057200332440ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import org.globus.gsi.trustmanager.PKITrustManagerFactory; import org.globus.gsi.trustmanager.X509ProxyCertPathValidator; import org.globus.gsi.stores.PEMKeyStore; import org.globus.gsi.stores.ResourceCertStore; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.Provider; /** * This is a security provider for the Globus SSL support. This supplies a * CertStore, CertValidator and KeyStore implementation * * @version ${version} * @since 1.0 */ public final class GlobusProvider extends Provider { public static final String PROVIDER_NAME = "Globus"; public static final String CERTSTORE_TYPE = "PEMFilebasedCertStore"; public static final String CERT_PATH_VALIDATOR_TYPE = "X509ProxyPath"; public static final String KEYSTORE_TYPE = "PEMFilebasedKeyStore"; public static final String TRUSTMANAGER_TYPE = "GlobusTrustManager"; private static final long serialVersionUID = -6275241207604782362L; /** * Create Provider and add Components to the java security framework. */ public GlobusProvider() { super(PROVIDER_NAME, 1.0, "Globus Security Providers"); AccessController.doPrivileged(new PrivilegedAction() { public Object run() { put("CertStore.PEMFilebasedCertStore", ResourceCertStore.class .getName()); put("CertPathValidator.X509ProxyPath", X509ProxyCertPathValidator.class.getName()); put("KeyStore.PEMFilebasedKeyStore", PEMKeyStore.class .getName()); put("TrustManagerFactory.GSI", PKITrustManagerFactory.class.getCanonicalName()); return null; } }); } } GlobusTrustManagerFactoryParameters.java000066400000000000000000000033441241116057200373550ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/providerpackage org.globus.gsi.provider; import org.globus.gsi.X509ProxyCertPathParameters; import java.security.KeyStore; import java.security.cert.CertStore; import java.util.Map; import javax.net.ssl.ManagerFactoryParameters; import org.globus.gsi.proxy.ProxyPolicyHandler; public class GlobusTrustManagerFactoryParameters implements ManagerFactoryParameters { private KeyStore initTrustStore; private CertStore initCRLStore; private SigningPolicyStore initPolicyStore; private boolean initRejectLimitedProxy; private Map handlers; public GlobusTrustManagerFactoryParameters(KeyStore initTrustStore, CertStore initCRLStore, SigningPolicyStore initPolicyStore, boolean initRejectLimitedProxy) { this.initTrustStore = initTrustStore; this.initCRLStore = initCRLStore; this.initPolicyStore = initPolicyStore; this.initRejectLimitedProxy = initRejectLimitedProxy; } public GlobusTrustManagerFactoryParameters(KeyStore initTrustStore, CertStore initCRLStore, SigningPolicyStore initPolicyStore, boolean initRejectLimitedProxy, Map handlers) { super(); this.initTrustStore = initTrustStore; this.initCRLStore = initCRLStore; this.initPolicyStore = initPolicyStore; this.initRejectLimitedProxy = initRejectLimitedProxy; this.handlers = handlers; } public X509ProxyCertPathParameters getCertPathParameters() { if (this.handlers == null) { return new X509ProxyCertPathParameters(this.initTrustStore, this.initCRLStore, this.initPolicyStore, this.initRejectLimitedProxy); } else { return new X509ProxyCertPathParameters(this.initTrustStore, this.initCRLStore, this.initPolicyStore, this.initRejectLimitedProxy, this.handlers); } } } KeyStoreParametersFactory.java000066400000000000000000000060341241116057200353310ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/providerpackage org.globus.gsi.provider; import org.globus.gsi.stores.PEMKeyStore; import java.security.KeyStore; import java.security.KeyStore.LoadStoreParameter; import java.security.KeyStore.ProtectionParameter; public class KeyStoreParametersFactory { public static KeyStore.LoadStoreParameter createCertKeyParameters( String certLocations, String keyLocation) { return new CertKeyParameters(certLocations, keyLocation); } public static KeyStore.LoadStoreParameter createProxyCertParameters( String proxyCertLocation) { return new ProxyCertParameters(proxyCertLocation); } public static LoadStoreParameter createTrustStoreParameters( String trustedCertificateDirectories) { return new TrustStoreParameters(trustedCertificateDirectories, null); } public static LoadStoreParameter createTrustStoreParameters( String trustedCertificateDirectories, String defaultDirectory) { return new TrustStoreParameters(trustedCertificateDirectories, defaultDirectory); } private static class TrustStoreParameters implements FileStoreParameters { private String trustedCertificateDirectories; private String defaultCertificateDirectory; public TrustStoreParameters(String trustedCertificateDirectories, String defaultCertificateDirectory) { super(); this.trustedCertificateDirectories = trustedCertificateDirectories; this.defaultCertificateDirectory = defaultCertificateDirectory; } public Object getProperty(String key) { if (key.equals(PEMKeyStore.DIRECTORY_LIST_KEY)) { return trustedCertificateDirectories; } else if (key.equals(PEMKeyStore.DEFAULT_DIRECTORY_KEY)) { return defaultCertificateDirectory; } return null; } public ProtectionParameter getProtectionParameter() { // TODO Auto-generated method stub return null; } } private static class ProxyCertParameters implements FileStoreParameters { private String proxyLocation; public ProxyCertParameters(String proxyLocation) { super(); this.proxyLocation = proxyLocation; } public Object getProperty(String key) { if (key.equals(PEMKeyStore.PROXY_FILENAME)) { return this.proxyLocation; } else { return null; } } public ProtectionParameter getProtectionParameter() { // TODO Auto-generated method stub return null; } } private static class CertKeyParameters implements FileStoreParameters { private String certLocations; private String keyLocation; private ProtectionParameter param; public CertKeyParameters(String certLocations, String keyLocation) { super(); this.certLocations = certLocations; this.keyLocation = keyLocation; } public ProtectionParameter getProtectionParameter() { return param; } public Object getProperty(String key) { if (key.equals(PEMKeyStore.KEY_FILENAME)) { return this.keyLocation; } else if (key.equals(PEMKeyStore.CERTIFICATE_FILENAME)) { return this.certLocations; } else { return null; } } } public static interface FileStoreParameters extends LoadStoreParameter { public Object getProperty(String key); } } SigningPolicyStore.java000066400000000000000000000020331241116057200337760ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import javax.security.auth.x500.X500Principal; import org.globus.gsi.SigningPolicy; /** * // JGLOBUS-91 */ public interface SigningPolicyStore { /** * JGLOBUS-87 * * @param caPrincipal Document Me. * @return Document Me. * @throws SigningPolicyStoreException Document Me. */ SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException; } SigningPolicyStoreException.java000066400000000000000000000021301241116057200356530ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import java.security.cert.CertStoreException; /** * This exception signifies an error processing a SigningPolicy in a SigningPolicyStore. */ public class SigningPolicyStoreException extends CertStoreException { public SigningPolicyStoreException(String msg) { super(msg); } public SigningPolicyStoreException(String msg, Throwable ex) { super(msg, ex); } public SigningPolicyStoreException(Throwable ex) { super(ex); } } SigningPolicyStoreParameters.java000066400000000000000000000014621241116057200360270ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import java.security.cert.CertStoreParameters; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public interface SigningPolicyStoreParameters extends CertStoreParameters { } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/simple/000077500000000000000000000000001241116057200307125ustar00rootroot00000000000000SimpleMemoryCertStore.java000066400000000000000000000047431241116057200357630ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import java.security.cert.X509CertSelector; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.security.InvalidAlgorithmParameterException; import java.security.cert.CertStoreParameters; import java.security.cert.CRL; import java.security.cert.CRLSelector; import java.security.cert.CertSelector; import java.security.cert.CertStoreException; import java.security.cert.Certificate; import java.security.cert.CertStoreSpi; /** * @deprecated */ public class SimpleMemoryCertStore extends CertStoreSpi { private List crlStore; private List certStore; public SimpleMemoryCertStore(CertStoreParameters params) throws InvalidAlgorithmParameterException { super(params); if (params == null) { throw new InvalidAlgorithmParameterException(); } crlStore = new LinkedList(); certStore = new LinkedList(); if (! (params instanceof SimpleMemoryCertStoreParams)) { throw new IllegalArgumentException("wrong parameter type"); } SimpleMemoryCertStoreParams pms = (SimpleMemoryCertStoreParams) params; X509Certificate[] certs = pms.getCerts(); X509CRL[] crls = pms.getCrls(); if (certs != null) { for (X509Certificate cert : certs) { if(cert != null) { certStore.add(cert); } } } if (crls != null) { for (X509CRL crl : crls) { if(crl != null) { crlStore.add(crl); } } } } @Override public Collection engineGetCRLs(CRLSelector selector) throws CertStoreException { List l = new LinkedList(); for (X509CRL crl : crlStore) { if (selector.match(crl)) { l.add(crl); } } return l; } @Override public Collection engineGetCertificates(CertSelector selector) throws CertStoreException { List l = new LinkedList(); X509CertSelector select = (X509CertSelector) selector; for (X509Certificate cert : certStore) { if (selector.match(cert)) { l.add(cert); } } return l; } } SimpleMemoryCertStoreParams.java000066400000000000000000000017121241116057200371200ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.security.cert.CertStoreParameters; /** * @deprecated */ public class SimpleMemoryCertStoreParams implements CertStoreParameters { private X509Certificate[] certs; private X509CRL[] crls; public SimpleMemoryCertStoreParams(X509Certificate[] certs, X509CRL[] crls) { this.certs = certs; this.crls = crls; } public X509Certificate[] getCerts() { return certs; } public void setCerts(X509Certificate[] certs) { this.certs = certs; } public X509CRL[] getCrls() { return crls; } public void setCrls(X509CRL[] crls) { this.crls = crls; } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } } SimpleMemoryKeyStore.java000066400000000000000000000106121241116057200356060ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.security.KeyStore.LoadStoreParameter; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.Map; import java.security.cert.X509Certificate; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.Key; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.Date; import java.util.Enumeration; import java.security.KeyStoreSpi; /** * @deprecated */ public class SimpleMemoryKeyStore extends KeyStoreSpi { private Log logger = LogFactory.getLog(SimpleMemoryKeyStore.class); private Map certMap; @Override public void engineLoad(LoadStoreParameter params) throws IOException, NoSuchAlgorithmException, CertificateException { logger.debug("creating cert store."); if (params == null) { throw new IllegalArgumentException("parameter null"); } else if (!(params instanceof SimpleMemoryKeyStoreLoadStoreParameter)) { throw new IllegalArgumentException("Wrong parameter type"); } X509Certificate[] certs = ((SimpleMemoryKeyStoreLoadStoreParameter) params).getCerts(); this.certMap = new ConcurrentHashMap(); if (certs != null) { for (X509Certificate cert : certs) { if (cert != null) { logger.debug("adding cert " + cert.getSubjectDN().getName()); certMap.put(cert.getSubjectDN().getName(), cert); } } } } @Override public Enumeration engineAliases() { return Collections.enumeration(this.certMap.keySet()); } @Override public boolean engineContainsAlias(String alias) { return this.certMap.containsKey(alias); } @Override public void engineDeleteEntry(String alias) throws KeyStoreException { this.certMap.remove(alias); } @Override public Certificate engineGetCertificate(String alias) { return this.certMap.get(alias); } @Override public boolean engineIsCertificateEntry(String alias) { return engineContainsAlias(alias); } @Override public boolean engineIsKeyEntry(String alias) { return false; } @Override public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { if (cert == null) { return; } if (cert instanceof X509Certificate) { this.certMap.put(alias, (X509Certificate) cert); } else { throw new IllegalArgumentException("Certificate should be X509Cert"); } } @Override public int engineSize() { return this.certMap.size(); } @Override public void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { throw new UnsupportedOperationException(); } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { throw new UnsupportedOperationException(); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException { throw new UnsupportedOperationException(); } @Override public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { throw new UnsupportedOperationException(); } @Override public String engineGetCertificateAlias(Certificate cert) { throw new UnsupportedOperationException(); } @Override public Certificate[] engineGetCertificateChain(String alias) { throw new UnsupportedOperationException(); } @Override public Date engineGetCreationDate(String alias) { throw new UnsupportedOperationException(); } @Override public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { throw new UnsupportedOperationException(); } } SimpleMemoryKeyStoreLoadStoreParameter.java000066400000000000000000000011041241116057200412600ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import java.security.cert.X509Certificate; import java.security.KeyStore.ProtectionParameter; import java.security.KeyStore.LoadStoreParameter; /** * @deprecated */ public class SimpleMemoryKeyStoreLoadStoreParameter implements LoadStoreParameter { private X509Certificate[] certs; public X509Certificate[] getCerts() { return certs; } public void setCerts(X509Certificate[] certs) { this.certs = certs; } public ProtectionParameter getProtectionParameter() { return null; } } SimpleMemoryProvider.java000066400000000000000000000020471241116057200356360ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import java.security.PrivilegedAction; import java.security.AccessController; import java.security.Provider; /** * @deprecated */ public final class SimpleMemoryProvider extends Provider { public static final String PROVIDER_NAME = "Simple"; public static final String CERTSTORE_TYPE = "SimpleMemoryCertStore"; public static final String KEYSTORE_TYPE = "SimpleMemoryKeyStore"; private static final long serialVersionUID = -6275241207604782364L; /** * Create Provider and add Components to the java security framework. */ public SimpleMemoryProvider() { super(PROVIDER_NAME, 1.0, "Simple Memory Security Provider"); AccessController.doPrivileged(new PrivilegedAction() { public Object run() { put("CertStore.SimpleMemoryCertStore", SimpleMemoryCertStore.class.getName()); put("KeyStore.SimpleMemoryKeyStore", SimpleMemoryKeyStore.class.getName()); return null; } }); } } SimpleMemorySigningPolicyStore.java000066400000000000000000000036111241116057200376350ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.security.auth.x500.X500Principal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.asn1.x509.X509Name; import org.globus.gsi.SigningPolicy; import org.globus.gsi.bc.X509NameHelper; import org.globus.gsi.provider.SigningPolicyStore; import org.globus.gsi.provider.SigningPolicyStoreException; /** * @deprecated */ public class SimpleMemorySigningPolicyStore implements SigningPolicyStore { private static Log logger = LogFactory.getLog(SimpleMemorySigningPolicyStore.class); private Map store; public SimpleMemorySigningPolicyStore(SigningPolicy[] policies) { store = new ConcurrentHashMap(); int numPolicies = 0; if (policies != null) { numPolicies = policies.length; for (SigningPolicy policy : policies) { if (policy != null) { X509Name name = new X509Name(false, policy.getCASubjectDN().getName(X500Principal.RFC2253)); store.put(X509NameHelper.toString(name), policy); logger.debug("Adding to policy store: " + X509NameHelper.toString(name)); } } } logger.debug("Loaded " + store.size() + " policies of " + numPolicies); } public SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException { SigningPolicy policy = store.get(caPrincipal.getName(X500Principal.RFC2253)); if (policy == null) { X509Name name = new X509Name(false, caPrincipal.getName(X500Principal.RFC2253)); logger.debug("Getting from policy store: " + X509NameHelper.toString(name)); policy = store.get(X509NameHelper.toString(name)); } return policy; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/000077500000000000000000000000001241116057200267505ustar00rootroot00000000000000IgnoreProxyPolicyHandler.java000066400000000000000000000025661241116057200345100ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPath; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A simple restricted proxy policy handler that logs the * proxy policy language oid. It can be used for debugging purposes. */ public class IgnoreProxyPolicyHandler implements ProxyPolicyHandler { private static Log logger = LogFactory.getLog(IgnoreProxyPolicyHandler.class.getName()); public void validate(ProxyCertInfo proxyCertInfo, CertPath certPath, int index) throws CertPathValidatorException { logger.info("ProxyPolicy ignored: " + proxyCertInfo.getProxyPolicy().getPolicyLanguage().getId()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/ProxyPathValidator.java000066400000000000000000000313771241116057200334320ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.trustmanager.X509ProxyCertPathValidator; import org.globus.gsi.X509ProxyCertPathParameters; import org.globus.gsi.provider.simple.SimpleMemoryCertStoreParams; import org.globus.gsi.provider.simple.SimpleMemoryKeyStoreLoadStoreParameter; import org.globus.gsi.provider.simple.SimpleMemoryProvider; import org.globus.gsi.provider.simple.SimpleMemorySigningPolicyStore; import java.security.Security; import java.util.Map; import java.util.HashMap; import java.util.Hashtable; import java.security.KeyStore; import java.security.cert.CertStore; import java.security.cert.X509Certificate; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.SigningPolicy; import org.globus.gsi.CertificateRevocationLists; import org.globus.gsi.bc.BouncyCastleUtil; import org.globus.util.I18n; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Performs certificate/proxy path validation. It supports both old * style Globus proxy as well as the new proxy certificate format. It * checks BasicConstraints, KeyUsage, and ProxyCertInfo (if * applicable) extensions. It also checks for presence in CRLs and * signing policy compliance. This validator requires that each CA be * installed with signing policy. It also provides a callback interface * for custom policy checking of restricted proxies.
    Currently, * does not perform the following checks for the new proxy * certificates:
    1. Check if proxy serial number is unique (and * the version number)
    2. Check for empty subject names
    */ public class ProxyPathValidator { static { Security.addProvider(new SimpleMemoryProvider()); } private static I18n i18n = I18n.getI18n("org.globus.gsi.proxy.errors", ProxyPathValidator.class.getClassLoader()); private static Log logger = LogFactory.getLog(ProxyPathValidator.class.getName()); private X509ProxyCertPathValidator validator = new X509ProxyCertPathValidator(); private boolean rejectLimitedProxyCheck = false; private boolean limited = false; private X509Certificate identityCert = null; private Hashtable proxyPolicyHandlers = null; /** * Returns if the validated proxy path is limited. A proxy path * is limited when a limited proxy is present anywhere after the * first non-impersonation proxy certificate. * * @return true if the validated path is limited */ public boolean isLimited() { return this.limited; } /** * Returns the identity certificate. The first certificates in the * path that is not an impersonation proxy, e.g. it could be a * restricted proxy or end-entity certificate * * @return X509Certificate the identity certificate */ public X509Certificate getIdentityCertificate() { return this.identityCert; } /** * Returns the subject name of the identity certificate (in the * Globus format) * @see #getIdentityCertificate * @return the subject name of the identity certificate in the * Globus format */ public String getIdentity() { return BouncyCastleUtil.getIdentity(this.identityCert); } /** * Removes a restricted proxy policy handler. * * @param id the Oid of the policy handler to remove. * @return ProxyPolicyHandler the removed handler, or * null if there is no handler registered under that * id. */ public ProxyPolicyHandler removeProxyPolicyHandler(String id) { return (id != null && this.proxyPolicyHandlers != null) ? (ProxyPolicyHandler)this.proxyPolicyHandlers.remove(id) : null; } /** * Sets a restricted proxy policy handler. * * @param id the Oid of the proxy policy to install the handler for. * @param handler the proxy policy handler. * @return ProxyPolicyHandler the previous handler * installed under the specified id. Usually, will be null. */ public ProxyPolicyHandler setProxyPolicyHandler(String id, ProxyPolicyHandler handler) { if (id == null) { throw new IllegalArgumentException(i18n.getMessage("proxyPolicyId")); } if (handler == null) { throw new IllegalArgumentException(i18n. getMessage("proxyPolicyHandler")); } if (this.proxyPolicyHandlers == null) { this.proxyPolicyHandlers = new Hashtable(); } return (ProxyPolicyHandler)this.proxyPolicyHandlers.put(id, handler); } /** * Retrieves a restricted proxy policy handler for a given policy id. * * @param id the Oid of the proxy policy to get the handler for. * @return ProxyPolicyHandler the policy handler * registered for the given id or null if none is * registered. */ public ProxyPolicyHandler getProxyPolicyHandler(String id) { return (id != null && this.proxyPolicyHandlers != null) ? (ProxyPolicyHandler)this.proxyPolicyHandlers.get(id) : null; } /** * Resets the internal state. Useful for reusing the same * instance for validating multiple certificate paths. */ public void reset() { this.rejectLimitedProxyCheck= false; this.limited = false; this.identityCert = null; } /** * If set, the validate rejects certificate chain if limited proxy if found */ public void setRejectLimitedProxyCheck(boolean rejectLimProxy) { this.rejectLimitedProxyCheck = rejectLimProxy; } /** * Performs all certificate path validation including * checking of the signatures, validity of the certificates, * extension checking, etc.
    * It uses the PureTLS code to do basic cert signature checking * checking and then calls {@link #validate(X509Certificate[], * TrustedCertificates) validate} for further checks. * * @param certPath the certificate path to validate. * @param trustedCerts the trusted (CA) certificates. * @exception ProxyPathValidatorException if certificate * path validation fails. */ public void validate(X509Certificate[] certPath, X509Certificate[] trustedCerts) throws ProxyPathValidatorException { validate(certPath, trustedCerts, null); } public void validate(X509Certificate[] certPath, X509Certificate[] trustedCerts, CertificateRevocationLists crls) throws ProxyPathValidatorException { validate(certPath, trustedCerts, crls, null); } public void validate(X509Certificate[] certPath, X509Certificate[] trustedCerts, CertificateRevocationLists crls, SigningPolicy[] signingPolicies) throws ProxyPathValidatorException { validate(certPath, trustedCerts, crls, signingPolicies, null); } public void validate(X509Certificate[] certPath, X509Certificate[] trustedCerts, CertificateRevocationLists crls, SigningPolicy[] signingPolicies, Boolean enforceSigningPolicy) throws ProxyPathValidatorException { if (certPath == null) { throw new IllegalArgumentException(i18n.getMessage("certsNull")); } // If trusted certificates is not null, but signing policy is, // then this might fail down the line. TrustedCertificates trustedCertificates = null; if (trustedCerts != null) { trustedCertificates = new TrustedCertificates(trustedCerts, signingPolicies); } validate(certPath, trustedCertificates, crls, enforceSigningPolicy); } /** * Performs certificate path validation. Does not check * the cert signatures but it performs all other checks like * the extension checking, validity checking, restricted policy * checking, CRL checking, etc. * * @param certPath the certificate path to validate. * @exception ProxyPathValidatorException if certificate * path validation fails. */ protected void validate(X509Certificate [] certPath) throws ProxyPathValidatorException { validate(certPath, (TrustedCertificates)null, (CertificateRevocationLists)null); } /** * Performs certificate path validation. Does not check * the cert signatures but it performs all other checks like * the extension checking, validity checking, restricted policy * checking, CRL checking, etc. * * @param certPath the certificate path to validate. * @param trustedCerts the trusted (CA) certificates. If null, * the default trusted certificates will be used. * @exception ProxyPathValidatorException if certificate * path validation fails. */ protected void validate(X509Certificate [] certPath, TrustedCertificates trustedCerts) throws ProxyPathValidatorException { validate(certPath, trustedCerts, null); } protected void validate(X509Certificate [] certPath, TrustedCertificates trustedCerts, CertificateRevocationLists crlsList) throws ProxyPathValidatorException { validate(certPath, trustedCerts, crlsList, null); } /** * Performs certificate path validation. Does not check * the cert signatures but it performs all other checks like * the extension checking, validity checking, restricted policy * checking, CRL checking, etc. * * @param certPath the certificate path to validate. * @param trustedCerts the trusted (CA) certificates. If null, * the default trusted certificates will be used. * @param crlsList the certificate revocation list. If null, * the default certificate revocation list will be used. * @exception ProxyPathValidatorException if certificate * path validation fails. */ protected synchronized void validate(X509Certificate [] certPath, TrustedCertificates trustedCerts, CertificateRevocationLists crlsList, Boolean enforceSigningPolicy) throws ProxyPathValidatorException { if (certPath == null) { throw new IllegalArgumentException(i18n.getMessage("certsNull")); } if (crlsList == null) { crlsList = CertificateRevocationLists.getDefaultCertificateRevocationLists(); } if (trustedCerts == null) { trustedCerts = TrustedCertificates.getDefault(); } try { SimpleMemoryKeyStoreLoadStoreParameter ksParams = new SimpleMemoryKeyStoreLoadStoreParameter(); SimpleMemoryCertStoreParams csParams = new SimpleMemoryCertStoreParams(null, crlsList.getCrls()); ksParams.setCerts(trustedCerts.getCertificates()); Map initHandlers = new HashMap(); if (this.proxyPolicyHandlers != null) { initHandlers.putAll(proxyPolicyHandlers); } KeyStore ks = KeyStore.getInstance(SimpleMemoryProvider.KEYSTORE_TYPE, SimpleMemoryProvider.PROVIDER_NAME); CertStore cs = CertStore.getInstance(SimpleMemoryProvider.CERTSTORE_TYPE, csParams, SimpleMemoryProvider.PROVIDER_NAME); SimpleMemorySigningPolicyStore spStore = new SimpleMemorySigningPolicyStore(trustedCerts.getSigningPolicies()); ks.load(ksParams); X509ProxyCertPathParameters params = new X509ProxyCertPathParameters(ks, cs, spStore, this.rejectLimitedProxyCheck, initHandlers); validator.engineValidate(CertificateUtil.getCertPath(certPath), params); this.identityCert = validator.getIdentityCertificate(); this.limited = validator.isLimited(); } catch (Exception e) { throw new ProxyPathValidatorException( ProxyPathValidatorException.FAILURE, e); } } protected synchronized void setValidator(X509ProxyCertPathValidator validator) { this.validator = validator; } } ProxyPathValidatorException.java000066400000000000000000000061401241116057200352200ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy; import java.util.Date; import java.text.DateFormat; import java.util.TimeZone; import java.text.SimpleDateFormat; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; /** * @deprecated */ public class ProxyPathValidatorException extends GeneralSecurityException { public static final int FAILURE = -1; // proxy constraints violation public static final int PROXY_VIOLATION = 1; // unsupported critical extensions public static final int UNSUPPORTED_EXTENSION = 2; // proxy or CA path length exceeded public static final int PATH_LENGTH_EXCEEDED = 3; // unknown CA public static final int UNKNOWN_CA = 4; // unknown proxy policy public static final int UNKNOWN_POLICY = 5; // cert revoked public static final int REVOKED = 6; // limited proxy not accepted public static final int LIMITED_PROXY_ERROR = 7; // CRL expired public static final int EXPIRED_CRL = 8; // signing policy not found public static final int NO_SIGNING_POLICY_FILE = 9; // no relevant signing policy in the file public static final int NO_SIGNING_POLICY = 10; // DN violates signing policy public static final int SIGNING_POLICY_VIOLATION = 11; private X509Certificate cert; private int errorCode = FAILURE; public ProxyPathValidatorException(int errorCode) { this(errorCode, null); } public ProxyPathValidatorException(int errorCode, Throwable root) { this(errorCode, "", root); } public ProxyPathValidatorException(int errorCode, String msg, Throwable root) { super(msg, root); this.errorCode = errorCode; } public ProxyPathValidatorException(int errorCode, X509Certificate cert, String msg) { super(msg, null); this.errorCode = errorCode; this.cert = cert; } public int getErrorCode() { return this.errorCode; } /** * Returns the certificate that was being validated when * the exception was thrown. * * @return the Certificate that was being validated when * the exception was thrown (or null if not specified) */ public X509Certificate getCertificate() { return this.cert; } public static String getDateAsString(Date date) { TimeZone tz = TimeZone.getTimeZone("GMT"); DateFormat df = new SimpleDateFormat("MMM dd HH:mm:ss yyyy z"); df.setTimeZone(tz); return df.format(date); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/ProxyPolicyHandler.java000066400000000000000000000030531241116057200334130ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy; import org.globus.gsi.proxy.ext.ProxyCertInfo; import java.security.cert.CertPath; import java.security.cert.CertPathValidatorException; /** * A restricted proxy policy handler interface. All policy handlers must * implement this interface. */ public interface ProxyPolicyHandler { /** * @param proxyCertInfo the ProxyCertInfo extension found in * the restricted proxy certificate. * @param certPath the certificate path being validated. * @param index the index of the certificate in the certPath that is * being validated - the index of the restricted proxy * certificate. * @throws CertPathValidatorException if policy validation fails. */ void validate( ProxyCertInfo proxyCertInfo, CertPath certPath, int index) throws CertPathValidatorException; } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/ext/000077500000000000000000000000001241116057200275505ustar00rootroot00000000000000GlobusProxyCertInfoExtension.java000066400000000000000000000027221241116057200361630ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/ext/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy.ext; import org.globus.gsi.bc.BouncyCastleX509Extension; import org.globus.util.I18n; /** * Represents ProxyCertInfo X.509 extension. */ public class GlobusProxyCertInfoExtension extends BouncyCastleX509Extension { private static I18n i18n = I18n.getI18n("org.globus.gsi.errors", GlobusProxyCertInfoExtension.class.getClassLoader()); public GlobusProxyCertInfoExtension(ProxyCertInfo value) { super(ProxyCertInfo.OLD_OID.getId(), true, null); if (value == null) { throw new IllegalArgumentException(i18n.getMessage("proxyErr22")); } setValue(value); } public void setOid(String oid) { throw new RuntimeException(i18n.getMessage("proxyErr23")); } public void setCritical(boolean critical) { throw new RuntimeException(i18n.getMessage("proxyErr24")); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/ext/ProxyCertInfo.java000066400000000000000000000127661241116057200332020ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy.ext; import org.globus.gsi.util.CertificateUtil; import org.bouncycastle.asn1.DERObjectIdentifier; import java.io.IOException; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DERSequence; /** * Represents ProxyCertInfo extension.
    *

    *

     * ProxyCertInfo ::= SEQUENCE { pCPathLenConstraint      INTEGER (0..MAX) OPTIONAL, proxyPolicy ProxyPolicy }
     * 
    */ public class ProxyCertInfo implements ASN1Encodable { /** ProxyCertInfo extension OID */ public static final DERObjectIdentifier OID = new DERObjectIdentifier("1.3.6.1.5.5.7.1.14"); public static final DERObjectIdentifier OLD_OID = new DERObjectIdentifier("1.3.6.1.4.1.3536.1.222"); private DERInteger pathLenConstraint; private ProxyPolicy proxyPolicy; /** * Creates a new instance of the ProxyCertInfo extension from given ASN1Sequence object. * * @param seq ASN1Sequence object to create the instance from. */ public ProxyCertInfo(ASN1Sequence seq) { if (seq.size() < 1) { throw new IllegalArgumentException(); } int seqPos = 0; if (seq.getObjectAt(seqPos) instanceof DERInteger) { this.pathLenConstraint = (DERInteger) seq.getObjectAt(seqPos); seqPos++; } ASN1Sequence policy = (ASN1Sequence) seq.getObjectAt(seqPos); this.proxyPolicy = new ProxyPolicy(policy); } /** * Creates a new instance of the ProxyCertInfo extension. * * @param pathLenConstraint the path length constraint of the extension. * @param policy the policy of the extension. */ public ProxyCertInfo(int pathLenConstraint, ProxyPolicy policy) { if (policy == null) { throw new IllegalArgumentException(); } this.pathLenConstraint = new DERInteger(pathLenConstraint); this.proxyPolicy = policy; } /** * Creates a new instance of the ProxyCertInfo extension with no path length constraint. * * @param policy the policy of the extension. */ public ProxyCertInfo(ProxyPolicy policy) { if (policy == null) { throw new IllegalArgumentException(); } this.pathLenConstraint = null; this.proxyPolicy = policy; } /** * Returns an instance of ProxyCertInfo from given object. * * @param obj the object to create the instance from. * @return ProxyCertInfo instance. * @throws IllegalArgumentException if unable to convert the object to ProxyCertInfo instance. */ public static ProxyCertInfo getInstance(Object obj) { // String err = obj.getClass().getName(); if (obj instanceof ProxyCertInfo) { return (ProxyCertInfo) obj; } else if (obj instanceof ASN1Sequence) { return new ProxyCertInfo((ASN1Sequence) obj); } else if (obj instanceof byte[]) { ASN1Primitive derObj; try { derObj = CertificateUtil.toASN1Primitive((byte[]) obj); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } if (derObj instanceof ASN1Sequence) { return new ProxyCertInfo((ASN1Sequence) derObj); } } throw new IllegalArgumentException(); } /** * Returns the DER-encoded ASN.1 representation of the extension. * * @return DERObject the encoded representation of the extension. */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector vec = new ASN1EncodableVector(); if (this.pathLenConstraint != null) { vec.add(this.pathLenConstraint); } vec.add(this.proxyPolicy.toASN1Primitive()); return new DERSequence(vec); } /** * Returns the policy object in the proxy. * * @return ProxyPolicy the policy object */ public ProxyPolicy getProxyPolicy() { return this.proxyPolicy; } /** * Returns the maximum depth of the path of proxy certificates that can be signed by this proxy certificate. * * @return the maximum depth of the path of proxy certificates that can be * signed by this proxy certificate. If 0 then this certificate must * not be used to sign a proxy certificate. If the path length * constraint field is not defined Integer.MAX_VALUE is * returned. */ public int getPathLenConstraint() { if (this.pathLenConstraint != null) { return this.pathLenConstraint.getValue().intValue(); } return Integer.MAX_VALUE; } } ProxyCertInfoExtension.java000066400000000000000000000027001241116057200350030ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/ext/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy.ext; import org.globus.gsi.bc.BouncyCastleX509Extension; import org.globus.util.I18n; /** * Represents ProxyCertInfo X.509 extension. */ public class ProxyCertInfoExtension extends BouncyCastleX509Extension { private static I18n i18n = I18n.getI18n("org.globus.gsi.errors", ProxyCertInfoExtension.class.getClassLoader()); public ProxyCertInfoExtension(ProxyCertInfo value) { super(ProxyCertInfo.OID.getId(), true, null); if (value == null) { throw new IllegalArgumentException(i18n.getMessage("proxyErr28")); } setValue(value); } public void setOid(String oid) { throw new RuntimeException(i18n.getMessage("proxyErr23")); } public void setCritical(boolean critical) { throw new RuntimeException(i18n.getMessage("proxyErr29")); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/proxy/ext/ProxyPolicy.java000066400000000000000000000137101241116057200327160ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy.ext; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERTaggedObject; /** * Represents the policy part of the ProxyCertInfo extension.
     * ProxyPolicy ::= SEQUENCE { policyLanguage    OBJECT IDENTIFIER, policy OCTET STRING OPTIONAL } 
    */ public class ProxyPolicy implements ASN1Encodable { /** * Impersonation proxy OID */ public static final DERObjectIdentifier IMPERSONATION = new DERObjectIdentifier("1.3.6.1.5.5.7.21.1"); /** * Independent proxy OID */ public static final DERObjectIdentifier INDEPENDENT = new DERObjectIdentifier("1.3.6.1.5.5.7.21.2"); /** * Limited proxy OID */ public static final DERObjectIdentifier LIMITED = new DERObjectIdentifier("1.3.6.1.4.1.3536.1.1.1.9"); private DERObjectIdentifier policyLanguage; private DEROctetString policy; /** * Creates a new instance of the ProxyPolicy object from given ASN1Sequence object. * * @param seq ASN1Sequence object to create the instance from. */ public ProxyPolicy(ASN1Sequence seq) { if (seq.size() < 1) { throw new IllegalArgumentException(); } this.policyLanguage = (DERObjectIdentifier) seq.getObjectAt(0); if (seq.size() > 1) { ASN1Encodable obj = seq.getObjectAt(1); if (obj instanceof DERTaggedObject) { obj = ((DERTaggedObject) obj).getObject(); } this.policy = (DEROctetString) obj; } checkConstraints(); } /** * Creates a new instance of the ProxyPolicy object. * * @param policyLanguage the language policy Oid. * @param policy the policy. */ public ProxyPolicy( DERObjectIdentifier policyLanguage, byte[] policy) { if (policyLanguage == null) { throw new IllegalArgumentException(); } this.policyLanguage = policyLanguage; if (policy != null) { this.policy = new DEROctetString(policy); } checkConstraints(); } /** * Creates a new instance of the ProxyPolicy object. * * @param policyLanguageOid the language policy Oid. * @param policy the policy. */ public ProxyPolicy( String policyLanguageOid, byte[] policy) { if (policyLanguageOid == null) { throw new IllegalArgumentException(); } this.policyLanguage = new DERObjectIdentifier(policyLanguageOid); if (policy != null) { this.policy = new DEROctetString(policy); } checkConstraints(); } /** * Creates a new instance of the ProxyPolicy object. * * @param policyLanguage the language policy Oid. * @param policy the policy. */ public ProxyPolicy( DERObjectIdentifier policyLanguage, String policy) { this(policyLanguage, (policy != null) ? policy.getBytes() : null); } /** * Creates a new instance of the ProxyPolicy object with no policy. * * @param policyLanguage the language policy Oid. */ public ProxyPolicy(DERObjectIdentifier policyLanguage) { this(policyLanguage, (byte[]) null); } /** * Returns the DER-encoded ASN.1 representation of proxy policy. * * @return DERObject the encoded representation of the proxy * policy. */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(this.policyLanguage); if (this.policy != null) { vec.add(this.policy); } return new DERSequence(vec); } protected void checkConstraints() { if ((this.policyLanguage.equals(IMPERSONATION) || this.policyLanguage.equals(INDEPENDENT)) && this.policy != null) { throw new IllegalArgumentException(); } } /** * Returns the actual policy embedded in the ProxyPolicy object. * * @return the policy in bytes. Might be null. */ public byte[] getPolicy() { return (this.policy != null) ? this.policy.getOctets() : new byte[0]; } /** * Returns the actual policy embedded in the ProxyPolicy object. * * @return the policy as String. Might be null. */ @SuppressWarnings("PMD.StringInstantiation") public String getPolicyAsString() { return (this.policy != null) ? new String(this.policy.getOctets()) : null; } /** * Returns the policy language of the ProxyPolicy. * * @return the policy language Oid. */ public DERObjectIdentifier getPolicyLanguage() { return this.policyLanguage; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("ProxyPolicy: "); buf.append(this.policyLanguage.getId()); if (this.policy != null) { buf.append(System.getProperty("line.separator")); buf.append(getPolicyAsString()); } return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/000077500000000000000000000000001241116057200271065ustar00rootroot00000000000000AbstractResourceSecurityWrapper.java000066400000000000000000000105001241116057200362320ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.File; import java.io.IOException; import java.net.URL; import org.globus.common.CoGProperties; import org.globus.util.GlobusResource; import org.globus.util.GlobusPathMatchingResourcePatternResolver; /** * // JGLOBUS-91 : add javadoc * * @param * Type of security object */ public abstract class AbstractResourceSecurityWrapper implements SecurityObjectWrapper, Storable { protected GlobusPathMatchingResourcePatternResolver globusResolver = new GlobusPathMatchingResourcePatternResolver(); protected GlobusResource globusResource; private Log logger = LogFactory.getLog(getClass().getCanonicalName()); private boolean changed; private T securityObject; private long lastModified = -1; private long lastRefresh; private final long cacheLifetime; private String alias; private boolean inMemory = false; protected AbstractResourceSecurityWrapper(boolean inMemory) { this.inMemory = inMemory; cacheLifetime = CoGProperties.getDefault().getCertCacheLifetime(); } protected void init(String locationPattern) throws ResourceStoreException { init(globusResolver.getResource(locationPattern)); } protected void init(GlobusResource initialResource) throws ResourceStoreException { init(initialResource, create(initialResource)); } public String getAlias() { return alias; } protected void init(String locationPattern, T initialSecurityObject) throws ResourceStoreException { init(globusResolver.getResource(locationPattern), initialSecurityObject); } protected void init(GlobusResource initialResource, T initialSecurityObject) throws ResourceStoreException { if (initialSecurityObject == null) { // JGLOBUS-88 : better exception? throw new IllegalArgumentException("Object cannot be null"); } this.securityObject = initialSecurityObject; this.globusResource = initialResource; logger.debug(String.format("Loading initialResource: %s", this.globusResource.toString())); try { this.alias = this.globusResource.getURL().toExternalForm(); if(!inMemory){ this.lastModified = this.globusResource.lastModified(); this.lastRefresh = System.currentTimeMillis(); } } catch (IOException e) { throw new ResourceStoreException(e); } } public GlobusResource getGlobusResource(){ return globusResource; } public URL getResourceURL() { try { return globusResource.getURL(); } catch (IOException e) { logger.warn("Unable to extract url", e); return null; } } public File getFile() { try { return globusResource.getFile(); } catch (IOException e) { logger.debug("Resource is not a file", e); return null; } } public void refresh() throws ResourceStoreException { if(!inMemory){ long now = System.currentTimeMillis(); if (this.lastRefresh + this.cacheLifetime < now) { this.changed = false; long latestLastModified; try { latestLastModified = this.globusResource.lastModified(); } catch (IOException e) { throw new ResourceStoreException(e); } if (this.lastModified < latestLastModified) { this.securityObject = create(this.globusResource); this.lastModified = latestLastModified; this.changed = true; } this.lastRefresh = now; } } } protected abstract T create(GlobusResource targetResource) throws ResourceStoreException; public T getSecurityObject() throws ResourceStoreException { refresh(); return this.securityObject; } public boolean hasChanged() { return this.changed; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/CertKeyCredential.java000066400000000000000000000133431241116057200333160ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.CredentialException; import org.globus.gsi.X509Credential; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.cert.CertificateEncodingException; import org.apache.commons.io.FileUtils; import org.globus.util.GlobusResource; /** * Fill Me */ public class CertKeyCredential implements SecurityObjectWrapper, Storable, CredentialWrapper { protected GlobusResource globusCertFile; protected GlobusResource globusKeyFile; private long certLastModified = -1; private long keyLastModified = -1; private X509Credential credential; private boolean changed; public CertKeyCredential(GlobusResource certResource, GlobusResource keyResource) throws ResourceStoreException { init(certResource, keyResource); } public CertKeyCredential(GlobusResource certResource, GlobusResource keyResource, X509Credential credential) throws ResourceStoreException { this.globusCertFile = certResource; try { if (!certResource.exists()) { FileUtils.touch(certResource.getFile()); this.certLastModified = certResource.lastModified(); } this.globusKeyFile = keyResource; if (!keyResource.exists()) { FileUtils.touch(keyResource.getFile()); this.keyLastModified = keyResource.lastModified(); } } catch (IOException e) { throw new ResourceStoreException(e); } this.credential = credential; } protected void init(GlobusResource initCertResource, GlobusResource initKeyResource) throws ResourceStoreException { if ((initCertResource == null) || (initKeyResource == null)) { throw new IllegalArgumentException(); } this.globusCertFile = initCertResource; this.globusKeyFile = initKeyResource; this.credential = createObject(this.globusCertFile, this.globusKeyFile); try { this.certLastModified = this.globusCertFile.lastModified(); this.keyLastModified = this.globusKeyFile.lastModified(); } catch (IOException ioe) { throw new ResourceStoreException(ioe); } } protected void init(GlobusResource initCertFile, GlobusResource keyResource, X509Credential initCredential) throws ResourceStoreException { if (initCredential == null) { // JGLOBUS-88 : better exception? throw new IllegalArgumentException("Object cannot be null"); } this.credential = initCredential; this.globusCertFile = initCertFile; this.globusKeyFile = keyResource; } public void refresh() throws ResourceStoreException { long cLatestLastModified; long kLatestLastModified; this.changed = false; try { cLatestLastModified = this.globusCertFile.lastModified(); kLatestLastModified = this.globusKeyFile.lastModified(); } catch (IOException ioe) { throw new ResourceStoreException(ioe); } if ((this.certLastModified < cLatestLastModified) || (this.keyLastModified < kLatestLastModified)) { this.credential = createObject(this.globusCertFile, this.globusKeyFile); this.certLastModified = cLatestLastModified; this.keyLastModified = kLatestLastModified; this.changed = true; } } public GlobusResource getCertificateFile() { return this.globusCertFile; } public GlobusResource getKeyFile() { return this.globusKeyFile; } // for creation of credential from a file protected X509Credential createObject(GlobusResource certSource, GlobusResource keySource) throws ResourceStoreException { InputStream certIns; InputStream keyIns; try { certIns = certSource.getInputStream(); keyIns = keySource.getInputStream(); return new X509Credential(certIns, keyIns); } catch (FileNotFoundException e) { throw new ResourceStoreException(e); } catch (CredentialException e) { throw new ResourceStoreException(e); } catch (IOException ioe) { throw new ResourceStoreException(ioe); } } public X509Credential getSecurityObject() throws ResourceStoreException { refresh(); return credential; } public boolean hasChanged() { return this.changed; } public X509Credential getCredential() throws ResourceStoreException { return getSecurityObject(); } public void store() throws ResourceStoreException { try { this.credential.writeToFile(this.globusCertFile.getFile(), this.globusKeyFile.getFile()); } catch (IOException e) { throw new ResourceStoreException(e); } catch (CertificateEncodingException e) { throw new ResourceStoreException(e); } } public String getAlias() { return null; //To change body of implemented methods use File | Settings | File Templates. } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/CredentialWrapper.java000066400000000000000000000015311241116057200333640ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.X509Credential; /** * Fill Me */ public interface CredentialWrapper extends SecurityObjectWrapper, Storable { X509Credential getCredential() throws ResourceStoreException; } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/PEMKeyStore.java000066400000000000000000000575561241116057200321020ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import static org.globus.gsi.util.CertificateIOUtil.writeCertificate; import org.globus.gsi.CredentialException; import org.globus.gsi.X509Credential; import org.globus.gsi.provider.KeyStoreParametersFactory; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.KeyStoreSpi; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Set; import java.util.HashSet; import java.util.Properties; import org.globus.util.GlobusResource; import org.globus.util.GlobusPathMatchingResourcePatternResolver; import org.globus.gsi.util.CertificateIOUtil; /** * This class provides a KeyStore implementation that supports trusted * certificates stored in PEM format and proxy certificates stored in PEM * format. It reads trusted certificates from multiple directories and a proxy * certificate from a file. * * @version ${version} * @since 1.0 */ public class PEMKeyStore extends KeyStoreSpi { // Default trusted certificates directory public static final String DEFAULT_DIRECTORY_KEY = "default_directory"; // List of directory names to load certificates from // JGLOBUS-90 : does it take certificate file names in this list? public static final String DIRECTORY_LIST_KEY = "directory_list"; // X.509 Certificate file name, should be set along with KEY_FILENAME public static final String CERTIFICATE_FILENAME = "certificateFilename"; // Key, typically private key, accompanying the certificate public static final String KEY_FILENAME = "keyFilename"; // X.509 PRoxy Cerificate file name public static final String PROXY_FILENAME = "proxyFilename"; private static Log logger = LogFactory.getLog(PEMKeyStore.class .getCanonicalName()); // Map from alias to the object (either key or certificate) private Map> aliasObjectMap = new Hashtable>(); // Map from trusted certificate to filename private Map certFilenameMap = new HashMap(); // default directory for trusted certificates private File defaultDirectory; private ResourceSecurityWrapperStore caDelegate = new ResourceCACertStore(); private ResourceSecurityWrapperStore proxyDelegate = new ResourceProxyCredentialStore(); private boolean inMemoryOnly = false; public void setCACertStore( ResourceSecurityWrapperStore caCertStore) { this.caDelegate = caCertStore; } public void setProxyDelegate( ResourceSecurityWrapperStore proxyDelegate) { this.proxyDelegate = proxyDelegate; } private CredentialWrapper getKeyEntry(String alias) { SecurityObjectWrapper object = this.aliasObjectMap.get(alias); if ((object != null) && (object instanceof CredentialWrapper)) { return (CredentialWrapper) object; } return null; } private ResourceTrustAnchor getCertificateEntry(String alias) { SecurityObjectWrapper object = this.aliasObjectMap.get(alias); if ((object != null) && (object instanceof ResourceTrustAnchor)) { return (ResourceTrustAnchor) object; } return null; } /** * Get the key referenced by the specified alias. * * @param s * The key's alias. * @param chars * The key's password. * @return The key reference by the alias or null. * @throws NoSuchAlgorithmException * If the key is encoded with an invalid algorithm. * @throws UnrecoverableKeyException * If the key can not be retrieved. */ @Override public Key engineGetKey(String s, char[] chars) throws NoSuchAlgorithmException, UnrecoverableKeyException { CredentialWrapper credential = getKeyEntry(s); Key key = null; if (credential != null) { try { String password = null; if (chars != null) { password = new String(chars); } key = credential.getCredential().getPrivateKey(password); } catch (ResourceStoreException e) { throw new UnrecoverableKeyException(e.getMessage()); } catch (CredentialException e) { throw new UnrecoverableKeyException(e.getMessage()); } } return key; } /** * Does the supplied alias refer to a key in this key store. * * @param s * The alias. * @return True if the alias refers to a key. */ @Override public boolean engineIsKeyEntry(String s) { return getKeyEntry(s) != null; } /** * Persist the security material in this keystore. If the object has a path * associated with it, the object will be persisted to that path. Otherwise * it will be stored in the default certificate directory. As a result, the * parameters of this method are ignored. * * @param outputStream * This parameter is ignored. * @param chars * This parameter is ignored. * @throws IOException * @throws NoSuchAlgorithmException * @throws CertificateException */ @Override public void engineStore(OutputStream outputStream, char[] chars) throws IOException, NoSuchAlgorithmException, CertificateException { for (SecurityObjectWrapper object : this.aliasObjectMap.values()) { if (object instanceof Storable) { try { ((Storable) object).store(); } catch (ResourceStoreException e) { throw new CertificateException(e); } } } } /** * Get the creation date for the object referenced by the alias. * * @param s * The alias of the security object. * @return The creation date of the security object. */ @Override public Date engineGetCreationDate(String s) { try { ResourceTrustAnchor trustAnchor = getCertificateEntry(s); if (trustAnchor != null) { return trustAnchor.getTrustAnchor().getTrustedCert() .getNotBefore(); } else { CredentialWrapper credential = getKeyEntry(s); if (credential != null) { return credential.getCredential().getNotBefore(); } } } catch (ResourceStoreException e) { return null; } return null; } /** * Get the alias associated with the supplied certificate. * * @param certificate * The certificate to query * @return The certificate's alias or null if the certificate is not present * in this keystore. */ @Override public String engineGetCertificateAlias(Certificate certificate) { return this.certFilenameMap.get(certificate); } /** * Get the certificateChain for the key referenced by the alias. * * @param s * The key alias. * @return The key's certificate chain or a 0 length array if the key is not * in the keystore. */ @Override public Certificate[] engineGetCertificateChain(String s) { CredentialWrapper credential = getKeyEntry(s); X509Certificate[] chain = new X509Certificate[0]; if (credential != null) { try { chain = credential.getCredential().getCertificateChain(); } catch (ResourceStoreException e) { logger.warn(e.getMessage(), e); chain = null; } } return chain; } /** * Get the certificate referenced by the supplied alias. * * @param s * The alias. * @return The Certificate or null if the alias does not exist in the * keyStore. */ @Override public Certificate engineGetCertificate(String s) { ResourceTrustAnchor trustAnchor = getCertificateEntry(s); if (trustAnchor != null) { try { return trustAnchor.getTrustAnchor().getTrustedCert(); } catch (ResourceStoreException e) { return null; } } return null; } /** * Load the keystore based on parameters in the LoadStoreParameter. The * parameter object must be an instance of FileBasedKeyStoreParameters. * * @param loadStoreParameter * The parameters to load. * @throws IOException * @throws NoSuchAlgorithmException * @throws CertificateException */ @Override public void engineLoad(KeyStore.LoadStoreParameter loadStoreParameter) throws IOException, NoSuchAlgorithmException, CertificateException { if (!(loadStoreParameter instanceof KeyStoreParametersFactory.FileStoreParameters)) { throw new IllegalArgumentException("Unable to process parameters: " + loadStoreParameter); } KeyStoreParametersFactory.FileStoreParameters params = (KeyStoreParametersFactory.FileStoreParameters) loadStoreParameter; String defaultDirectoryString = (String) params .getProperty(DEFAULT_DIRECTORY_KEY); String directoryListString = (String) params .getProperty(DIRECTORY_LIST_KEY); String certFilename = (String) params.getProperty(CERTIFICATE_FILENAME); String keyFilename = (String) params.getProperty(KEY_FILENAME); String proxyFilename = (String) params.getProperty(PROXY_FILENAME); initialize(defaultDirectoryString, directoryListString, proxyFilename, certFilename, keyFilename); } /** * Load the keystore from the supplied input stream. Unlike many other * implementations of keystore (most notably the default JKS * implementation), the input stream does not hold the keystore objects. * Instead, it must be a properties file defining the locations of the * keystore objects. The password is not used. * * @param inputStream * An input stream to the properties file. * @param chars * The password is not used. * @throws IOException * @throws NoSuchAlgorithmException * @throws CertificateException */ @Override public void engineLoad(InputStream inputStream, char[] chars) throws IOException, NoSuchAlgorithmException, CertificateException { try { Properties properties = new Properties(); if(inputStream != null){ properties.load(inputStream); if (properties.size() == 0) { throw new CertificateException( "Properties file for configuration was empty?"); } }else{ if(chars == null){ // keyStore.load(null,null) -> in memory only keystore inMemoryOnly = true; } } String defaultDirectoryString = properties .getProperty(DEFAULT_DIRECTORY_KEY); String directoryListString = properties .getProperty(DIRECTORY_LIST_KEY); String proxyFilename = properties.getProperty(PROXY_FILENAME); String certFilename = properties.getProperty(CERTIFICATE_FILENAME); String keyFilename = properties.getProperty(KEY_FILENAME); initialize(defaultDirectoryString, directoryListString, proxyFilename, certFilename, keyFilename); } finally { if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { logger.info("Error closing inputStream", e); } } } } /** * Initialize resources from filename, proxyfile name * * @param defaultDirectoryString * Name of the default directory name as: * "file: directory name" * @param directoryListString * @param proxyFilename * @param certFilename * @param keyFilename * * @throws IOException * @throws CertificateException */ private void initialize(String defaultDirectoryString, String directoryListString, String proxyFilename, String certFilename, String keyFilename) throws IOException, CertificateException { if (defaultDirectoryString != null) { defaultDirectory = new GlobusPathMatchingResourcePatternResolver().getResource(defaultDirectoryString).getFile(); if (!defaultDirectory.exists()) { boolean directoryMade = defaultDirectory.mkdirs(); if (!directoryMade) { throw new IOException( "Unable to create default certificate directory"); } } loadDirectories(defaultDirectoryString); } if (directoryListString != null) { loadDirectories(directoryListString); } try { if (proxyFilename != null && proxyFilename.length() > 0) { loadProxyCertificate(proxyFilename); } if ((certFilename != null && certFilename.length() > 0) && (keyFilename != null && keyFilename.length() > 0)) { loadCertificateKey(certFilename, keyFilename); } } catch (ResourceStoreException e) { throw new CertificateException(e); } catch (CredentialException e) { e.printStackTrace(); throw new CertificateException(e); } } private void loadProxyCertificate(String proxyFilename) throws ResourceStoreException { if (proxyFilename == null) { return; } proxyDelegate.loadWrappers(proxyFilename); Map wrapperMap = proxyDelegate .getWrapperMap(); for (ResourceProxyCredential credential : wrapperMap.values()) { this.aliasObjectMap.put(proxyFilename, credential); } } private void loadCertificateKey(String userCertFilename, String userKeyFilename) throws CredentialException, ResourceStoreException { GlobusPathMatchingResourcePatternResolver resolver = new GlobusPathMatchingResourcePatternResolver(); if ((userCertFilename == null) || (userKeyFilename == null)) { return; } // File certFile = new File(userCertFilename); // File keyFile = new File(userKeyFilename); GlobusResource certResource = resolver.getResource(userCertFilename); GlobusResource keyResource = resolver.getResource(userKeyFilename); CertKeyCredential credential = new CertKeyCredential(certResource, keyResource); // What do we name this alias? String alias = userCertFilename + ":" + userKeyFilename; this.aliasObjectMap.put(alias, credential); } private void loadDirectories(String directoryList) throws CertificateException { try { caDelegate.loadWrappers(directoryList); Map wrapperMap = caDelegate .getWrapperMap(); Set knownCerts = new HashSet(); // The alias hashing merits explanation. Loading all the files in a directory triggers a // deadlock bug for old jglobus clients if the directory contains repeated CAs (like the // modern IGTF bundle does). So, we ignore the cert if the alias is incorrect or already seen. // However, we track all the certs we ignore and load any that were completely ignored due to // aliases. So, non-hashed directories will still work. Map ignoredAlias = new HashMap(); Map ignoredAnchor = new HashMap(); Map ignoredCert = new HashMap(); for (ResourceTrustAnchor trustAnchor : wrapperMap.values()) { String alias = trustAnchor.getResourceURL().toExternalForm(); TrustAnchor tmpTrustAnchor = trustAnchor.getTrustAnchor(); X509Certificate trustCert = tmpTrustAnchor.getTrustedCert(); String hash = CertificateIOUtil.nameHash(trustCert.getSubjectX500Principal()); if (this.aliasObjectMap == null) { System.out.println("Alias Map Null"); } boolean hash_in_alias = !alias.contains(hash); if (knownCerts.contains(hash) || !hash_in_alias) { if (!hash_in_alias) { ignoredAlias.put(hash, alias); ignoredAnchor.put(hash, trustAnchor); ignoredCert.put(hash, trustCert); } continue; } knownCerts.add(hash); this.aliasObjectMap.put(alias, trustAnchor); certFilenameMap.put(trustCert, alias); } // Add any CA we skipped above. for (String hash : ignoredAlias.keySet()) { if (knownCerts.contains(hash)) { continue; } String alias = ignoredAlias.get(hash); this.aliasObjectMap.put(alias, ignoredAnchor.get(hash)); certFilenameMap.put(ignoredCert.get(hash), alias); } } catch (ResourceStoreException e) { throw new CertificateException("",e); } } /** * Delete a security object from this keystore. * * @param s * The alias of the object to delete. * @throws KeyStoreException */ @Override public void engineDeleteEntry(String s) throws KeyStoreException { SecurityObjectWrapper object = this.aliasObjectMap.remove(s); if (object != null) { if (object instanceof ResourceTrustAnchor) { ResourceTrustAnchor descriptor = (ResourceTrustAnchor) object; Certificate cert; try { cert = descriptor.getTrustAnchor().getTrustedCert(); } catch (ResourceStoreException e) { throw new KeyStoreException(e); } this.certFilenameMap.remove(cert); boolean success = descriptor.getFile().delete(); if (!success) { // JGLOBUS-91 : warn? throw error? logger.info("Unable to delete certificate"); } } else if (object instanceof ResourceProxyCredential) { ResourceProxyCredential proxy = (ResourceProxyCredential) object; try { proxy.getCredential(); } catch (ResourceStoreException e) { throw new KeyStoreException(e); } boolean success = proxy.getFile().delete(); if (!success) { // JGLOBUS-91 : warn? throw error? logger.info("Unable to delete credential"); } } } } /** * Get an enumertion of all of the aliases in this keystore. * * @return An enumeration of the aliases in this keystore. */ @Override public Enumeration engineAliases() { return Collections.enumeration(this.aliasObjectMap.keySet()); } /** * Add a new private key to the keystore. * * @param s * The alias for the object. * @param key * The private key. * @param chars * The password. * @param certificates * The key's certificate chain. * @throws KeyStoreException */ @Override public void engineSetKeyEntry(String s, Key key, char[] chars, Certificate[] certificates) throws KeyStoreException { if (!(key instanceof PrivateKey)) { throw new KeyStoreException("PrivateKey expected"); } if (!(certificates instanceof X509Certificate[])) { throw new KeyStoreException( "Certificate chain of X509Certificate expected"); } CredentialWrapper wrapper; X509Credential credential = new X509Credential((PrivateKey) key, (X509Certificate[]) certificates); if (credential.isEncryptedKey()) { wrapper = createCertKeyCredential(s, credential); } else { wrapper = createProxyCredential(s, credential); } storeWrapper(wrapper); this.aliasObjectMap.put(wrapper.getAlias(), wrapper); } @SuppressWarnings("rawtypes") private CredentialWrapper createProxyCredential(String s, X509Credential credential) throws KeyStoreException { CredentialWrapper wrapper; CredentialWrapper proxyCredential = getKeyEntry(s); File file; if (proxyCredential != null && proxyCredential instanceof AbstractResourceSecurityWrapper) { AbstractResourceSecurityWrapper proxyWrapper = (AbstractResourceSecurityWrapper) proxyCredential; file = proxyWrapper.getFile(); } else { // JGLOBUS-91 : should alias be file name? or generate? file = new File(defaultDirectory, s + "-key.pem"); } try { wrapper = new ResourceProxyCredential(inMemoryOnly, new GlobusResource(file.getAbsolutePath()), credential); } catch (ResourceStoreException e) { throw new KeyStoreException(e); } return wrapper; } private CredentialWrapper createCertKeyCredential(String s, X509Credential credential) throws KeyStoreException { GlobusResource certResource; GlobusResource keyResource; CredentialWrapper wrapper; CredentialWrapper credentialWrapper = getKeyEntry(s); if (credentialWrapper != null && credentialWrapper instanceof CertKeyCredential) { CertKeyCredential certKeyCred = (CertKeyCredential) credentialWrapper; certResource = certKeyCred.getCertificateFile(); keyResource = certKeyCred.getKeyFile(); } else { certResource = new GlobusResource(new File(defaultDirectory, s + ".0").getAbsolutePath()); keyResource = new GlobusResource(new File(defaultDirectory, s + "-key.pem").getAbsolutePath()); } try { wrapper = new CertKeyCredential(certResource, keyResource, credential); } catch (ResourceStoreException e) { throw new KeyStoreException(e); } return wrapper; } private void storeWrapper(CredentialWrapper wrapper) throws KeyStoreException { if(!inMemoryOnly){ try { wrapper.store(); } catch (ResourceStoreException e) { throw new KeyStoreException("Error storing credential", e); } } } /** * currently unsupported. * * @param s * The key's alias * @param bytes * The encoded private key. * @param certificates * The key's certificate chain. * @throws KeyStoreException */ @Override public void engineSetKeyEntry(String s, byte[] bytes, Certificate[] certificates) throws KeyStoreException { throw new UnsupportedOperationException(); // JGLOBUS-91 } /** * Does the specified alias exist in this keystore? * * @param s * The alias. * @return True if the alias refers to a security object in the keystore. */ @Override public boolean engineContainsAlias(String s) { return this.aliasObjectMap.containsKey(s); } /** * Get the number of security objects stored in this keystore. * * @return The number of security objects. */ @Override public int engineSize() { return this.aliasObjectMap.size(); } /** * Does the supplied alias refer to a certificate in this keystore? * * @param s * The alias. * @return True if this store contains a certificate with the specified * alias. */ @Override public boolean engineIsCertificateEntry(String s) { return getCertificateEntry(s) != null; } /** * Add a certificate to the keystore. * * @param alias * The certificate alias. * @param certificate * The certificate to store. * @throws KeyStoreException */ @Override public void engineSetCertificateEntry(String alias, Certificate certificate) throws KeyStoreException { if (!(certificate instanceof X509Certificate)) { throw new KeyStoreException( "Certificate must be instance of X509Certificate"); } File file; ResourceTrustAnchor trustAnchor = getCertificateEntry(alias); if (trustAnchor != null) { file = trustAnchor.getFile(); } else { file = new File(defaultDirectory, alias); } X509Certificate x509Cert = (X509Certificate) certificate; try { if(!inMemoryOnly){ writeCertificate(x509Cert, file); } ResourceTrustAnchor anchor = new ResourceTrustAnchor(inMemoryOnly, new GlobusResource(file.getAbsolutePath()), new TrustAnchor(x509Cert, null)); this.aliasObjectMap.put(alias, anchor); this.certFilenameMap.put(x509Cert, alias); } catch (ResourceStoreException e) { throw new KeyStoreException(e); } catch (IOException e) { throw new KeyStoreException(e); } catch (CertificateEncodingException e) { throw new KeyStoreException(e); } } } PEMKeyStoreParameters.java000066400000000000000000000126151241116057200340320ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import java.security.KeyStore; import java.security.KeyStore.ProtectionParameter; /** * This parameter class provides all of the options for creating a FileBasedKeyStore. *

    * It is immutable. * * @version ${vesion} * @since 1.0 */ public class PEMKeyStoreParameters implements KeyStore.LoadStoreParameter { private String certDirs; private String defaultCertDir; private String userCertFilename; private String userKeyFilename; private KeyStore.ProtectionParameter protectionParameter; private String proxyFilename; /** * This is the simplest constructor which only accepts a directory where all of the security material is stored. * New security material written to this KeyStore will be stored in this directory as well. * * @param initDefaultCertDir The directory for storage of security material */ public PEMKeyStoreParameters(String initDefaultCertDir) { this.defaultCertDir = initDefaultCertDir; } /** * This is a slightly more complicated constructor which allows the user to specify one or more directory where the * certificates are currently stored. The user can also specify a default directory where new security material * can be stored. * * @param initCertDirs Directories where security material exists. * @param initDefaultCertDir A default directory for the storage of security material */ public PEMKeyStoreParameters(String initCertDirs, String initDefaultCertDir) { this.certDirs = initCertDirs; this.defaultCertDir = initDefaultCertDir; } /** * A Constructor supporting the initial storage directories for the certificates, the default storage directory, * the filename of the user's certificate file, the file name of the user's key file and a ProtectionParameter. * * @param initCertDirs Directories where security material exists. * @param initDefaultCertDir A default directory for the storage of security material. * @param initUserCertFileName The file name for the user's certificate. * @param initUserKeyFileName The file name for the user's key. * @param initProtectionParameter A protection parameter for this keystore. */ public PEMKeyStoreParameters(String initCertDirs, String initDefaultCertDir, String initUserCertFileName, String initUserKeyFileName, ProtectionParameter initProtectionParameter) { this(initCertDirs, initDefaultCertDir); this.userCertFilename = initUserCertFileName; this.userKeyFilename = initUserKeyFileName; this.protectionParameter = initProtectionParameter; } /** * This constructor is for users who have a proxy certificate in addition to other security materials. * * @param initCertDirs Directories where security material exists. * @param initDefaultCertDir A default directory for the storage of security material. * @param initProxyFileName The file name for the user's proxy certificate. */ public PEMKeyStoreParameters(String initCertDirs, String initDefaultCertDir, String initProxyFileName) { this(initCertDirs, initDefaultCertDir); this.proxyFilename = initProxyFileName; } /** * This is the full constructor for users with proxy certificates. * * @param initCertDirs Directories where security material exists. * @param initDefaultCertDir A default directory for the storage of security material. * @param initUserCertFileName The file name for the user's certificate. * @param initUserKeyFileName The file name for the user's key. * @param initProtectionParameter A protection parameter for this keystore. * @param initProxyFileName The file name for the user's proxy certificate. */ public PEMKeyStoreParameters(String initCertDirs, String initDefaultCertDir, String initUserCertFileName, String initUserKeyFileName, ProtectionParameter initProtectionParameter, String initProxyFileName) { this(initCertDirs, initDefaultCertDir, initUserCertFileName, initUserKeyFileName, initProtectionParameter); this.proxyFilename = initProxyFileName; } public ProtectionParameter getProtectionParameter() { return this.protectionParameter; } public String getCertDirs() { return certDirs; } public String getDefaultCertDir() { return defaultCertDir; } public String getUserCertFilename() { return this.userCertFilename; } public String getUserKeyFilename() { return this.userKeyFilename; } public String getProxyFilename() { return this.proxyFilename; } } ResourceCACertStore.java000066400000000000000000000041771241116057200335310ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.FilenameFilter; import java.security.cert.TrustAnchor; import org.globus.util.GlobusResource; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Dec 29, 2009 * Time: 11:49:20 AM * To change this template use File | Settings | File Templates. */ public class ResourceCACertStore extends ResourceSecurityWrapperStore { private static FilenameFilter filter = new TrustAnchorFilter(); private Log logger = LogFactory.getLog(getClass().getCanonicalName()); @Override public ResourceTrustAnchor create(GlobusResource globusResource) throws ResourceStoreException { return new ResourceTrustAnchor(false, globusResource); } @Override protected Log getLog() { return logger; } @Override public FilenameFilter getDefaultFilenameFilter() { return filter; } /** * File filter for determining a Trust Anchor */ public static class TrustAnchorFilter implements FilenameFilter { public boolean accept(File dir, String file) { if (file == null) { throw new IllegalArgumentException(); } int length = file.length(); return length > 2 && file.charAt(length - 2) == '.' && file.charAt(length - 1) >= '0' && file.charAt(length - 1) <= '9'; } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/ResourceCRL.java000066400000000000000000000046341241116057200321100ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.util.GlobusResource; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.cert.X509CRL; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Dec 29, 2009 * Time: 12:41:39 PM * To change this template use File | Settings | File Templates. */ public class ResourceCRL extends AbstractResourceSecurityWrapper { public ResourceCRL(String fileName) throws ResourceStoreException { super(false); init(globusResolver.getResource(fileName)); } public ResourceCRL(boolean inMemory, GlobusResource globusResource) throws ResourceStoreException { super(inMemory); init(globusResource); } public ResourceCRL(String fileName, X509CRL crl) throws ResourceStoreException { super(false); init(globusResolver.getResource(fileName), crl); } public X509CRL getCrl() throws ResourceStoreException { return getSecurityObject(); } @Override protected X509CRL create(GlobusResource resource) throws ResourceStoreException { try { InputStream is = resource.getInputStream(); try { return CertificateLoadUtil.loadCrl(new BufferedInputStream(is)); } finally { try { is.close(); } catch (IOException ignored) { } } } catch (IOException e) { throw new ResourceStoreException(e); } catch (GeneralSecurityException e) { throw new ResourceStoreException(e); } } public void store() throws ResourceStoreException { //TODO: does this need an implementation } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/ResourceCRLStore.java000066400000000000000000000036021241116057200331170ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.File; import java.io.FilenameFilter; import java.security.cert.X509CRL; import org.globus.util.GlobusResource; /** * Fill Me */ public class ResourceCRLStore extends ResourceSecurityWrapperStore { private static CrlFilter filter = new CrlFilter(); private static final int MIN_NAME_LENGTH = 3; private Log logger = LogFactory.getLog(getClass().getCanonicalName()); @Override public ResourceCRL create(GlobusResource globusResource) throws ResourceStoreException { return new ResourceCRL(false, globusResource); } @Override protected Log getLog() { return logger; } @Override public FilenameFilter getDefaultFilenameFilter() { return filter; } /** * This filter identifies file whose names are valid for crl files. */ public static class CrlFilter implements FilenameFilter { public boolean accept(File dir, String file) { if (file == null) { throw new IllegalArgumentException(); } int length = file.length(); return length > MIN_NAME_LENGTH && file.endsWith(".r09"); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/ResourceCertStore.java000066400000000000000000000157151241116057200334040ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.security.InvalidAlgorithmParameterException; import java.security.cert.CRL; import java.security.cert.CRLSelector; import java.security.cert.CertSelector; import java.security.cert.CertStoreException; import java.security.cert.CertStoreParameters; import java.security.cert.CertStoreSpi; import java.security.cert.Certificate; import java.security.cert.TrustAnchor; import java.security.cert.X509CRL; import java.security.cert.X509CRLSelector; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Vector; /** * Created by IntelliJ IDEA. User: turtlebender Date: Dec 29, 2009 Time: * 12:57:23 PM To change this template use File | Settings | File Templates. */ public class ResourceCertStore extends CertStoreSpi { private static Log logger = LogFactory.getLog(ResourceCertStore.class.getCanonicalName()); private ResourceCACertStore caDelegate = new ResourceCACertStore(); private ResourceCRLStore crlDelegate = new ResourceCRLStore(); /** * The sole constructor. * * @param params * the initialization parameters (may be null) * @throws java.security.InvalidAlgorithmParameterException * if the initialization parameters are inappropriate for this * CertStoreSpi * @throws ResourceStoreException * If error loading certs and crls. */ public ResourceCertStore(CertStoreParameters params) throws InvalidAlgorithmParameterException, ResourceStoreException { super(params); if (params == null) { throw new InvalidAlgorithmParameterException(); } if (params instanceof ResourceCertStoreParameters) { ResourceCertStoreParameters storeParams = (ResourceCertStoreParameters) params; crlDelegate.loadWrappers(storeParams.getCrlLocationPattern()); caDelegate.loadWrappers(storeParams.getCertLocationPattern()); } else { throw new InvalidAlgorithmParameterException(); } } /** * Returns a Collection of Certificates that match * the specified selector. If no Certificates match the * selector, an empty Collection will be returned. *

    * For some CertStore types, the resulting * Collection may not contain all of the * Certificates that match the selector. For instance, an LDAP * CertStore may not search all entries in the directory. * Instead, it may just search entries that are likely to contain the * Certificates it is looking for. *

    * Some CertStore implementations (especially LDAP * CertStores) may throw a CertStoreException * unless a non-null CertSelector is provided that includes * specific criteria that can be used to find the certificates. Issuer * and/or subject names are especially useful criteria. * * @param selector * A CertSelector used to select which * Certificates should be returned. Specify * null to return all Certificates (if * supported). * @return A Collection of Certificates that match * the specified selector (never null) * @throws java.security.cert.CertStoreException * if an exception occurs */ public Collection engineGetCertificates( CertSelector selector) throws CertStoreException { logger.debug("selecting Certificates"); if (selector != null && !(selector instanceof X509CertSelector)) { throw new IllegalArgumentException(); } if (caDelegate.getCollection() == null) { return null; } // Given that we always only use subject, how can we improve performance // here. Custom Vector certSet = new Vector(); if (selector == null) { for (TrustAnchor trustAnchor : caDelegate.getCollection()) { certSet.add(trustAnchor.getTrustedCert()); } } else { for (TrustAnchor trustAnchor : caDelegate.getCollection()) { X509Certificate cert = trustAnchor.getTrustedCert(); if (selector.match(cert)) { certSet.add(cert); } } } return certSet; } /** * Returns a Collection of CRLs that match the * specified selector. If no CRLs match the selector, an empty * Collection will be returned. *

    * For some CertStore types, the resulting * Collection may not contain all of the * CRLs that match the selector. For instance, an LDAP * CertStore may not search all entries in the directory. * Instead, it may just search entries that are likely to contain the * CRLs it is looking for. *

    * Some CertStore implementations (especially LDAP * CertStores) may throw a CertStoreException * unless a non-null CRLSelector is provided that includes * specific criteria that can be used to find the CRLs. Issuer names and/or * the certificate to be checked are especially useful. * * @param selector * A CRLSelector used to select which * CRLs should be returned. Specify * null to return all CRLs (if * supported). * @return A Collection of CRLs that match the * specified selector (never null) * @throws java.security.cert.CertStoreException * if an exception occurs */ public Collection engineGetCRLs(CRLSelector selector) throws CertStoreException { if (selector != null && !(selector instanceof X509CRLSelector)) { throw new IllegalArgumentException(); } if (crlDelegate.getCollection() == null) { return new Vector(); } // Given that we always only use subject, how can we improve performance // here. Custom if (selector == null) { return crlDelegate.getCollection(); } else { Vector certSet = new Vector(); for (X509CRL crl : crlDelegate.getCollection()) { if (selector.match(crl)) { certSet.add(crl); } } return certSet; } } } ResourceCertStoreParameters.java000066400000000000000000000073721241116057200353510ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import java.security.cert.CertStoreParameters; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Dec 29, 2009 * Time: 1:06:39 PM * To change this template use File | Settings | File Templates. */ public class ResourceCertStoreParameters implements CertStoreParameters { private String certLocationPattern; private String crlLocationPattern; /** * Please use the {@link Stores} class to generate Key/Cert stores */ public ResourceCertStoreParameters(String certLocationPattern, String crlLocationPattern) { this.certLocationPattern = certLocationPattern; this.crlLocationPattern = crlLocationPattern; } // public ResourceCertStoreParameters(String... initLocations) { // if (initLocations != null) { // this.certLocations = new String[initLocations.length]; // System.arraycopy(initLocations, 0, this.certLocations, 0, initLocations.length); // } // } // public String[] getCertLocations() { // String[] returnArray = new String[certLocations.length]; // System.arraycopy(certLocations, 0, returnArray, 0, certLocations.length); // return returnArray; // } public String getCrlLocationPattern() { return crlLocationPattern; } public String getCertLocationPattern() { return certLocationPattern; } /** * Makes a copy of this CertStoreParameters. *

    * The precise meaning of "copy" may depend on the class of the * CertStoreParameters object. A typical implementation * performs a "deep copy" of this object, but this is not an absolute * requirement. Some implementations may perform a "shallow copy" of some or * all of the fields of this object. *

    * Note that the CertStore.getInstance methods make a copy of * the specified CertStoreParameters. A deep copy * implementation of clone is safer and more robust, as it * prevents the caller from corrupting a shared CertStore by * subsequently modifying the contents of its initialization parameters. * However, a shallow copy implementation of clone is more * appropriate for applications that need to hold a reference to a parameter * contained in the CertStoreParameters. For example, a shallow * copy clone allows an application to release the stores of a particular * CertStore initialization parameter immediately, rather than * waiting for the garbage collection mechanism. This should be done with * the utmost care, since the CertStore may still be in use by * other threads. *

    * Each subclass should state the precise behavior of this method so that * users and developers know what to expect. * * @return a copy of this CertStoreParameters */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { /* Cannot happen */ throw new InternalError(e.toString()); } } } ResourceProxyCredential.java000066400000000000000000000070031241116057200345160ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.CredentialException; import org.globus.gsi.X509Credential; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.security.cert.CertificateEncodingException; import org.globus.util.GlobusResource; /** * JGLOBUS-87 : document me * * @author Tom Howe */ public class ResourceProxyCredential extends AbstractResourceSecurityWrapper implements CredentialWrapper { private Log logger = LogFactory.getLog(getClass().getCanonicalName()); public ResourceProxyCredential(String locationPattern) throws ResourceStoreException { super(false); init(locationPattern); } public ResourceProxyCredential(GlobusResource globusResource) throws ResourceStoreException { super(false); init(globusResource); } public ResourceProxyCredential(String filename, X509Credential object) throws ResourceStoreException { super(false); init(filename, object); } public ResourceProxyCredential(boolean inMemory, GlobusResource globusResource, X509Credential object) throws ResourceStoreException { super(inMemory); init(globusResource, object); } public X509Credential getCredential() throws ResourceStoreException { return getSecurityObject(); } protected X509Credential create(GlobusResource globusResource) throws ResourceStoreException { InputStream keyInputStream = null; InputStream certInputStream = null; try { keyInputStream = new BufferedInputStream(globusResource.getInputStream()); certInputStream = new BufferedInputStream(globusResource.getInputStream()); return new X509Credential(keyInputStream, certInputStream); } catch (IOException e) { throw new ResourceStoreException(e); } catch (CredentialException e) { throw new ResourceStoreException(e); } finally { if (keyInputStream != null) { try { keyInputStream.close(); } catch (Exception e) { logger.warn("Unable to close stream."); } } if (certInputStream != null) { try { certInputStream.close(); } catch (Exception e) { logger.warn("Unable to close stream."); } } } } public void store() throws ResourceStoreException { try { X509Credential credential = getCredential(); credential.writeToFile(globusResource.getFile()); } catch (IOException ioe) { throw new ResourceStoreException(ioe); } catch (CertificateEncodingException e) { throw new ResourceStoreException(e); } } } ResourceProxyCredentialStore.java000066400000000000000000000035401241116057200355350ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.X509Credential; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.File; import java.io.FilenameFilter; import org.globus.util.GlobusResource; /** * Created by IntelliJ IDEA. User: turtlebender Date: Dec 29, 2009 Time: * 12:53:02 PM To change this template use File | Settings | File Templates. */ public class ResourceProxyCredentialStore extends ResourceSecurityWrapperStore { private static FilenameFilter filter = new ProxyFilenameFilter(); private Log logger = LogFactory.getLog(getClass().getCanonicalName()); @Override public ResourceProxyCredential create(GlobusResource globusResource) throws ResourceStoreException { return new ResourceProxyCredential(globusResource); } @Override protected Log getLog() { return logger; } @Override public FilenameFilter getDefaultFilenameFilter() { return ResourceProxyCredentialStore.filter; } /** * This filename filter returns files whose names are valid for a Proxy * Certificate. */ public static class ProxyFilenameFilter implements FilenameFilter { public boolean accept(File file, String s) { return true; } } } ResourceSecurityWrapperStore.java000066400000000000000000000136771241116057200356050ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.globus.util.GlobusResource; import org.globus.util.GlobusPathMatchingResourcePatternResolver; /** * Created by IntelliJ IDEA. User: turtlebender Date: Dec 29, 2009 Time: * 12:29:45 PM To change this template use File | Settings | File Templates. * * @param * @param */ public abstract class ResourceSecurityWrapperStore, V> { private Collection rootObjects; private GlobusPathMatchingResourcePatternResolver globusResolver = new GlobusPathMatchingResourcePatternResolver(); private Map wrapperMap = new HashMap(); private Log logger = LogFactory.getLog(ResourceSecurityWrapperStore.class.getCanonicalName()); public Map getWrapperMap() { return this.wrapperMap; } public void loadWrappers(String[] locations) throws ResourceStoreException { for (String location : locations) { File file = new File(location); GlobusResource globusResource = new GlobusResource(file.getAbsolutePath()); try { loadWrappers(globusResource.getURL().toExternalForm()); } catch (IOException ioe) { throw new ResourceStoreException(ioe); } } } public void loadWrappers(String locationPattern) throws ResourceStoreException { Set updatedList = new HashSet(); boolean changed = false; Map newWrapperMap = new HashMap(); if (locationPattern == null) { this.rootObjects = updatedList; this.wrapperMap = newWrapperMap; return; } if (locationPattern.indexOf(",") >= 0) { String[] locationPatterns = locationPattern.split(","); boolean tmpChanged = false; for (String lp : locationPatterns) { if (!tmpChanged) { tmpChanged = loadResources(lp, updatedList, newWrapperMap); } changed = tmpChanged; } } else { changed = loadResources(locationPattern, updatedList, newWrapperMap); } // in case certificates were removed if (!changed && this.rootObjects != null && this.wrapperMap.size() != newWrapperMap.size()) { changed = true; } if (changed) { this.rootObjects = updatedList; } this.wrapperMap = newWrapperMap; } private boolean loadResources(String locationPattern, Set updatedList, Map newWrapperMap) throws ResourceStoreException { boolean changed = false; try { GlobusResource[] globusResources = globusResolver.getResources(locationPattern); for (GlobusResource globusResource : globusResources){ URI uri =globusResource.getURI(); if (!globusResource.isReadable()) { getLog().warn("Cannot read: " + uri.toASCIIString()); continue; } changed = load(globusResource, updatedList, newWrapperMap); } } catch (IOException e) { throw new ResourceStoreException(e); } return changed; } private boolean load(GlobusResource resource, Set currentRoots, Map newWrapperMap) throws ResourceStoreException { if (!resource.isReadable()) { throw new ResourceStoreException("Cannot read file"); } try { if (resource.getFile().isDirectory()) { File directory = resource.getFile(); currentRoots.addAll(addCredentials(directory, newWrapperMap)); return true; } } catch (IOException e) { // This is ok, it just means the resource is not a // filesystemresources logger.debug("Not a filesystem resource", e); } try { String resourceUri = resource.getURL().toExternalForm(); T fbo = this.wrapperMap.get(resourceUri); if (fbo == null) { fbo = create(resource); } V target = fbo.create(resource); newWrapperMap.put(resourceUri, fbo); currentRoots.add(target); return true; } catch (IOException e) { throw new ResourceStoreException(e); } } private Set addCredentials(File directory, Map newWrapperMap) throws ResourceStoreException { FilenameFilter filter = getDefaultFilenameFilter(); String[] children = directory.list(filter); Set roots = new HashSet(); if (children == null) { return roots; } try { for (String child : children) { File childFile = new File(directory, child); if (childFile.isDirectory()) { roots.addAll(addCredentials(childFile, newWrapperMap)); } else { GlobusResource resource = new GlobusResource(childFile.getAbsolutePath()); String resourceUri = resource.getURI().toASCIIString(); T fbo = this.wrapperMap.get(resourceUri); if (fbo == null) { fbo = create(new GlobusResource(childFile.getAbsolutePath())); } V target = fbo.create(resource); newWrapperMap.put(resourceUri, fbo); roots.add(target); } } return roots; } catch (IOException e) { throw new ResourceStoreException(e); } } public abstract T create(GlobusResource resource) throws ResourceStoreException; public abstract FilenameFilter getDefaultFilenameFilter(); public Collection getCollection() { return this.rootObjects; } protected abstract Log getLog(); } ResourceSigningPolicy.java000066400000000000000000000111231241116057200341560ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.SigningPolicyException; import org.globus.gsi.provider.SigningPolicyStoreException; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.IOException; import java.io.Reader; import java.io.InputStreamReader; import java.util.Collection; import java.util.Map; import javax.security.auth.x500.X500Principal; import org.globus.gsi.SigningPolicy; import org.globus.gsi.SigningPolicyParser; import org.globus.util.GlobusResource; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Dec 28, 2009 * Time: 2:57:09 PM * To change this template use File | Settings | File Templates. */ public class ResourceSigningPolicy { protected GlobusResource globusResource; private Log logger = LogFactory.getLog(ResourceSigningPolicy.class.getCanonicalName()); private boolean changed; private Map signingPolicyMap; private long lastModified = -1; public ResourceSigningPolicy(GlobusResource resource) throws ResourceStoreException { init(resource); } protected void init(GlobusResource initResource) throws ResourceStoreException { this.globusResource = initResource; this.signingPolicyMap = create(this.globusResource); logger.debug(String.format("Loading initResource: %s", this.globusResource.toString())); try { this.lastModified = this.globusResource.lastModified(); } catch (IOException e) { throw new ResourceStoreException(e); } } protected void init(GlobusResource initResource, Map initSigningPolicy) throws ResourceStoreException { if (initSigningPolicy == null) { // JGLOBUS-88 : better exception? throw new IllegalArgumentException("Object cannot be null"); } this.signingPolicyMap = initSigningPolicy; this.globusResource = initResource; } public Collection getSigningPolicies() throws SigningPolicyStoreException { try { Map object = getObject(); if (object != null) { return object.values(); } } catch (ResourceStoreException e) { throw new SigningPolicyStoreException(e); } return null; } public Map create(GlobusResource signingPolicyResource) throws ResourceStoreException { SigningPolicyParser parser = new SigningPolicyParser(); Map policies; Reader reader; try { reader = new InputStreamReader(signingPolicyResource.getInputStream()); } catch (IOException e) { throw new ResourceStoreException(e); } try { policies = parser.parse(reader); } catch (SigningPolicyException e) { throw new ResourceStoreException(e); } finally { try { reader.close(); } catch (IOException e) { throw new ResourceStoreException(e); } } return policies; } protected void reload() throws ResourceStoreException { this.changed = false; long latestLastModified; try { latestLastModified = this.globusResource.lastModified(); } catch (IOException e) { throw new ResourceStoreException(e); } if (this.lastModified < latestLastModified) { this.signingPolicyMap = create(this.globusResource); this.lastModified = latestLastModified; this.changed = true; } } public GlobusResource getResource() { return this.globusResource; } protected Map getObject() throws ResourceStoreException { reload(); return this.signingPolicyMap; } public boolean hasChanged() { return this.changed; } } ResourceSigningPolicyStore.java000066400000000000000000000154511241116057200352030ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.provider.SigningPolicyStore; import org.globus.gsi.provider.SigningPolicyStoreException; import org.globus.gsi.provider.SigningPolicyStoreParameters; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.IOException; import java.net.URI; import java.security.InvalidAlgorithmParameterException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.security.auth.x500.X500Principal; import org.globus.gsi.SigningPolicy; import org.globus.gsi.util.CertificateIOUtil; import org.globus.util.GlobusResource; import org.globus.util.GlobusPathMatchingResourcePatternResolver; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class ResourceSigningPolicyStore implements SigningPolicyStore { private Map signingPolicyFileMap = new HashMap(); private Map policyMap = new HashMap(); private ResourceSigningPolicyStoreParameters parameters; private final static Log logger = LogFactory.getLog(ResourceSigningPolicyStore.class.getCanonicalName()); private final Map invalidPoliciesCache = new HashMap(); private final Map validPoliciesCache = new HashMap(); private final static long CACHE_TIME_MILLIS = 3600*1000; /** * Please use the {@link Stores} class to generate Key/Cert stores */ public ResourceSigningPolicyStore(SigningPolicyStoreParameters param) throws InvalidAlgorithmParameterException { if (param == null) { throw new IllegalArgumentException(); } if (!(param instanceof ResourceSigningPolicyStoreParameters)) { throw new InvalidAlgorithmParameterException(); } this.parameters = (ResourceSigningPolicyStoreParameters) param; } public synchronized SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException { if (caPrincipal == null) { return null; } String caPrincipalName = caPrincipal.getName(); long now = System.currentTimeMillis(); String hash = CertificateIOUtil.nameHash(caPrincipal); Long validCacheTime = validPoliciesCache.get(caPrincipalName); Long invalidCacheTime = invalidPoliciesCache.get(caPrincipalName); if ((invalidCacheTime != null) && (now - invalidCacheTime < 10*CACHE_TIME_MILLIS)) { return null; } if ((validCacheTime == null) || (now - validCacheTime >= CACHE_TIME_MILLIS) || !this.policyMap.containsKey(caPrincipalName)) { loadPolicy(hash, caPrincipalName); } return this.policyMap.get(caPrincipalName); } private synchronized void loadPolicy(String hash, String caPrincipalName) throws SigningPolicyStoreException { String locations = this.parameters.getTrustRootLocations(); GlobusResource[] resources = new GlobusPathMatchingResourcePatternResolver(). getResources(locations); long now = System.currentTimeMillis(); boolean found_policy = false; // Optimization: If we find a hash for this CA, only process that. // Otherwise, we will process all policies. for (GlobusResource resource : resources) { String filename = resource.getFilename(); if (!filename.startsWith(hash)) { continue; } if (loadSigningPolicy(resource, policyMap, signingPolicyFileMap, now)) { found_policy = true; } } if (!found_policy) { // Poor-man's implementation. Note it is much more expensive than a hashed directory for (GlobusResource resource : resources) { loadSigningPolicy(resource, policyMap, signingPolicyFileMap, now); } } if (!validPoliciesCache.containsKey(caPrincipalName)) { invalidPoliciesCache.put(caPrincipalName, now); } } private boolean loadSigningPolicy( GlobusResource policyResource, Map policyMapToLoad, Map currentPolicyFileMap, long currentMillis) { String filename = policyResource.getFilename(); long now = currentMillis; boolean loaded = false; Long invalidCacheTime = invalidPoliciesCache.get(filename); if ((invalidCacheTime != null) && (now - invalidCacheTime < 10 * CACHE_TIME_MILLIS)) { return false; } try { URI uri; if (!policyResource.isReadable()) { throw new SigningPolicyStoreException("file is not readable"); } try { uri = policyResource.getURI(); } catch (IOException e) { throw new SigningPolicyStoreException(e); } ResourceSigningPolicy filePolicy = this.signingPolicyFileMap.get(uri); if (filePolicy == null) { try { filePolicy = new ResourceSigningPolicy(policyResource); } catch (ResourceStoreException e) { throw new SigningPolicyStoreException(e); } } Collection policies = filePolicy.getSigningPolicies(); currentPolicyFileMap.put(uri, filePolicy); if (policies != null) { for (SigningPolicy policy : policies) { X500Principal caPrincipal = policy.getCASubjectDN(); policyMapToLoad.put(caPrincipal.getName(), policy); validPoliciesCache.put(caPrincipal.getName(), now); } } loaded = true; } catch (SigningPolicyStoreException e) { if ((invalidCacheTime == null) || (now - invalidCacheTime >= 10 * CACHE_TIME_MILLIS)) { logger.warn("Failed to load signing policy: " + filename + " : " + e.getMessage()); logger.debug("Failed to load signing policy: " + filename, e); invalidPoliciesCache.put(filename, now); } } return loaded; } } ResourceSigningPolicyStoreParameters.java000066400000000000000000000060131241116057200372210ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.provider.SigningPolicyStoreParameters; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class ResourceSigningPolicyStoreParameters implements SigningPolicyStoreParameters { private String locations; /** * Please use the {@link Stores} class to generate Key/Cert stores */ public ResourceSigningPolicyStoreParameters(String locations) { if (locations == null) { throw new IllegalArgumentException(); } this.locations = locations; } public String getTrustRootLocations() { return this.locations; } /** * Makes a copy of this CertStoreParameters. *

    * The precise meaning of "copy" may depend on the class of the * CertStoreParameters object. A typical implementation * performs a "deep copy" of this object, but this is not an absolute * requirement. Some implementations may perform a "shallow copy" of some or * all of the fields of this object. *

    * Note that the CertStore.getInstance methods make a copy of * the specified CertStoreParameters. A deep copy * implementation of clone is safer and more robust, as it * prevents the caller from corrupting a shared CertStore by * subsequently modifying the contents of its initialization parameters. * However, a shallow copy implementation of clone is more * appropriate for applications that need to hold a reference to a parameter * contained in the CertStoreParameters. For example, a shallow * copy clone allows an application to release the stores of a particular * CertStore initialization parameter immediately, rather than * waiting for the garbage collection mechanism. This should be done with * the utmost care, since the CertStore may still be in use by * other threads. *

    * Each subclass should state the precise behavior of this method so that * users and developers know what to expect. * * @return a copy of this CertStoreParameters */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { /* Cannot happen */ throw new RuntimeException(e.getMessage(), e); } } } ResourceStoreException.java000066400000000000000000000023171241116057200343600ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import java.security.GeneralSecurityException; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Dec 30, 2009 * Time: 9:25:02 AM * To change this template use File | Settings | File Templates. */ public class ResourceStoreException extends GeneralSecurityException { public ResourceStoreException() { } public ResourceStoreException(String s) { super(s); } public ResourceStoreException(String s, Throwable throwable) { super(s, throwable); } public ResourceStoreException(Throwable throwable) { super(throwable); } } ResourceTrustAnchor.java000066400000000000000000000063701241116057200336640ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import org.globus.gsi.util.CertificateIOUtil; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.util.GlobusResource; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.cert.CertificateEncodingException; import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Dec 29, 2009 * Time: 11:37:52 AM * To change this template use File | Settings | File Templates. */ public class ResourceTrustAnchor extends AbstractResourceSecurityWrapper { public ResourceTrustAnchor(String fileName) throws ResourceStoreException { super(false); init(globusResolver.getResource(fileName)); } public ResourceTrustAnchor(boolean inMemory, GlobusResource globusResource) throws ResourceStoreException { super(inMemory); init(globusResource); } public ResourceTrustAnchor(String fileName, TrustAnchor cachedAnchor) throws ResourceStoreException { super(false); init(globusResolver.getResource(fileName), cachedAnchor); } public ResourceTrustAnchor(boolean inMemory, GlobusResource globusResource, TrustAnchor cachedAnchor) throws ResourceStoreException { super(inMemory); init(globusResource, cachedAnchor); } public TrustAnchor getTrustAnchor() throws ResourceStoreException { return super.getSecurityObject(); } @Override protected TrustAnchor create(GlobusResource globusResource) throws ResourceStoreException { X509Certificate certificate; try { InputStream inputStream = globusResource.getInputStream(); try { certificate = CertificateLoadUtil.loadCertificate(new BufferedInputStream(inputStream)); } finally { try { inputStream.close(); } catch (IOException ignored) { } } } catch (IOException e) { throw new ResourceStoreException(e); } catch (GeneralSecurityException e) { throw new ResourceStoreException(e); } return new TrustAnchor(certificate, null); } public void store() throws ResourceStoreException { try { CertificateIOUtil.writeCertificate(this.getTrustAnchor().getTrustedCert(), globusResource.getFile()); } catch (CertificateEncodingException e) { throw new ResourceStoreException(e); } catch (IOException e) { throw new ResourceStoreException(e); } } } SecurityObjectWrapper.java000066400000000000000000000016271241116057200341770ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; /** * Fill Me * * @param The type of security object to be wrapped */ public interface SecurityObjectWrapper { void refresh() throws ResourceStoreException; T getSecurityObject() throws ResourceStoreException; String getAlias(); boolean hasChanged(); } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/Storable.java000066400000000000000000000015571241116057200315340ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Jan 6, 2010 * Time: 1:25:44 PM * To change this template use File | Settings | File Templates. */ public interface Storable { void store() throws ResourceStoreException; } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/Stores.java000066400000000000000000000226271241116057200312410ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.stores; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.cert.CertStore; import java.security.cert.CertificateException; import java.util.HashMap; import org.globus.common.CoGProperties; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.provider.KeyStoreParametersFactory; /** * @author Jerome Revillard * */ public class Stores { private static String defaultCAFilesPattern = "*.0"; private static String defaultCRLFilesPattern = "*.r*"; private static String defaultSigningPolicyFilesPattern = "*.signing_policy"; private static final HashMap TRUST_STORES = new HashMap(); private static final HashMap CRL_STORES = new HashMap(); private static final HashMap CA_CERT_STORES = new HashMap(); private static final HashMap SIGNING_POLICY_STORES = new HashMap(); private final static long CACHE_TIME_MILLIS = 3600 * 1000; public static KeyStore getDefaultTrustStore() throws GeneralSecurityException, IOException { String pattern = "file:" + CoGProperties.getDefault().getCaCertLocations() + "/" + defaultCAFilesPattern; return getTrustStore(pattern); } public static KeyStore getTrustStore(String casLocationPattern) throws GeneralSecurityException, IOException { synchronized (TRUST_STORES) { ReloadableTrustStore reloadableKeystore = TRUST_STORES.get(casLocationPattern); if (reloadableKeystore != null) { return reloadableKeystore.getTrustStore(); } reloadableKeystore = new ReloadableTrustStore(casLocationPattern); TRUST_STORES.put(casLocationPattern, reloadableKeystore); return reloadableKeystore.getTrustStore(); } } public static CertStore getDefaultCACertStore() throws GeneralSecurityException, NoSuchAlgorithmException { String pattern = "file:" + CoGProperties.getDefault().getCaCertLocations() + "/" + defaultCAFilesPattern; return getCACertStore(pattern); } public static CertStore getCACertStore(String casLocationPattern) throws GeneralSecurityException, NoSuchAlgorithmException { synchronized (CA_CERT_STORES) { ReloadableCaCertStore reloadableCaCertStore = CA_CERT_STORES.get(casLocationPattern); if (reloadableCaCertStore == null) { reloadableCaCertStore = new ReloadableCaCertStore(casLocationPattern); CA_CERT_STORES.put(casLocationPattern, reloadableCaCertStore); } return reloadableCaCertStore.getCaCertStore(); } } public static CertStore getDefaultCRLStore() throws GeneralSecurityException, NoSuchAlgorithmException { String pattern = "file:" + CoGProperties.getDefault().getCaCertLocations() + "/" + defaultCRLFilesPattern; return getCRLStore(pattern); } public static CertStore getCRLStore(String crlsLocationPattern) throws GeneralSecurityException, NoSuchAlgorithmException { synchronized (CRL_STORES) { ReloadableCrlStore reloadableCrlStore = CRL_STORES.get(crlsLocationPattern); if (reloadableCrlStore == null) { reloadableCrlStore = new ReloadableCrlStore(crlsLocationPattern); CRL_STORES.put(crlsLocationPattern, reloadableCrlStore); } return reloadableCrlStore.getCrlStore(); } } public static ResourceSigningPolicyStore getDefaultSigningPolicyStore() throws GeneralSecurityException { String pattern = "file:" + CoGProperties.getDefault().getCaCertLocations() + "/" + defaultSigningPolicyFilesPattern; return getSigningPolicyStore(pattern); } public static ResourceSigningPolicyStore getSigningPolicyStore(String signingPolicyLocationPattern) throws GeneralSecurityException { synchronized (SIGNING_POLICY_STORES) { ResourceSigningPolicyStore signingPolicyStore = SIGNING_POLICY_STORES.get(signingPolicyLocationPattern); if (signingPolicyStore == null) { signingPolicyStore = new ResourceSigningPolicyStore(new ResourceSigningPolicyStoreParameters( signingPolicyLocationPattern)); SIGNING_POLICY_STORES.put(signingPolicyLocationPattern, signingPolicyStore); } return signingPolicyStore; } } public static String getDefaultCAFilesPattern() { return defaultCAFilesPattern; } public static void setDefaultCAFilesPattern(String defaultCAFilesPattern) { synchronized (TRUST_STORES) { synchronized (CA_CERT_STORES) { if (defaultCAFilesPattern == null || Stores.defaultCAFilesPattern.equals(defaultCAFilesPattern)) { return; } Stores.defaultCAFilesPattern = defaultCAFilesPattern; // Clear if we change the default pattern to prevent potential // memory issue; TRUST_STORES.clear(); CA_CERT_STORES.clear(); } } } public static String getDefaultCRLFilesPattern() { return defaultCRLFilesPattern; } public static void setDefaultCRLFilesPattern(String defaultCRLFilesPattern) { synchronized (CRL_STORES) { if (defaultCRLFilesPattern == null || Stores.defaultCRLFilesPattern.equals(defaultCRLFilesPattern)) { return; } Stores.defaultCRLFilesPattern = defaultCRLFilesPattern; // Clear if we change the default pattern to prevent potential // memory issue; CRL_STORES.clear(); } } public static String getDefaultSigningPolicyFilesPattern() { return defaultSigningPolicyFilesPattern; } public static void setDefaultSigningPolicyFilesPattern(String defaultSigningPolicyFilesPattern) { synchronized (SIGNING_POLICY_STORES) { if (defaultSigningPolicyFilesPattern == null || Stores.defaultSigningPolicyFilesPattern.equals(defaultSigningPolicyFilesPattern)) { return; } Stores.defaultSigningPolicyFilesPattern = defaultSigningPolicyFilesPattern; // Clear if we change the default pattern to prevent potential // memory issue; SIGNING_POLICY_STORES.clear(); } } private static class ReloadableTrustStore { private final String casLocationPattern; private final KeyStore keyStore; private long lastUpdateTime; protected ReloadableTrustStore(String casLocationPattern) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException { this.casLocationPattern = casLocationPattern; keyStore = KeyStore.getInstance(GlobusProvider.KEYSTORE_TYPE, GlobusProvider.PROVIDER_NAME); reload(); } private void reload() throws NoSuchAlgorithmException, CertificateException, IOException { keyStore.load(KeyStoreParametersFactory.createTrustStoreParameters(casLocationPattern)); lastUpdateTime = System.currentTimeMillis(); } protected boolean isStillValid() { return lastUpdateTime + CACHE_TIME_MILLIS > System.currentTimeMillis(); } protected KeyStore getTrustStore() throws NoSuchAlgorithmException, CertificateException, IOException { if (!isStillValid()) { reload(); } return keyStore; } } private static class ReloadableCrlStore { private final String crlsLocationPattern; private CertStore certStore; private long lastUpdateTime; protected ReloadableCrlStore(String crlsLocationPattern) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { this.crlsLocationPattern = crlsLocationPattern; load(); } private void load() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { certStore = CertStore.getInstance(GlobusProvider.CERTSTORE_TYPE, new ResourceCertStoreParameters(null, crlsLocationPattern)); lastUpdateTime = System.currentTimeMillis(); } protected boolean isStillValid() { return lastUpdateTime + CACHE_TIME_MILLIS > System.currentTimeMillis(); } protected CertStore getCrlStore() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { if (!isStillValid()) { load(); } return certStore; } } private static class ReloadableCaCertStore { private final String casLocationPattern; private CertStore certStore; private long lastUpdateTime; protected ReloadableCaCertStore(String casLocationPattern) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { this.casLocationPattern = casLocationPattern; load(); } private void load() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { certStore = CertStore.getInstance(GlobusProvider.CERTSTORE_TYPE, new ResourceCertStoreParameters( casLocationPattern, null)); lastUpdateTime = System.currentTimeMillis(); } protected boolean isStillValid() { return lastUpdateTime + CACHE_TIME_MILLIS > System.currentTimeMillis(); } protected CertStore getCaCertStore() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { if (!isStillValid()) { load(); } return certStore; } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/stores/package-info.java000066400000000000000000000014631241116057200323010ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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. */ /** * This package provides classes for accessing security material from generic "stores" (which can be defined via a * url). They are formatted in the traditional Globus style. */ package org.globus.gsi.stores;JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/000077500000000000000000000000001241116057200303035ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/CRLChecker.java000066400000000000000000000166711241116057200330660ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import org.globus.gsi.util.KeyStoreUtil; import org.globus.gsi.CertificateRevocationLists; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SignatureException; import java.security.cert.CRL; import java.security.cert.CRLException; import java.security.cert.CertPathValidatorException; import java.security.cert.CertStore; import java.security.cert.CertStoreException; import java.security.cert.Certificate; import java.security.cert.X509CRL; import java.security.cert.X509CRLSelector; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Date; import javax.security.auth.x500.X500Principal; import org.globus.gsi.GSIConstants; /** * This checks to see if the certificate is in a CRL. * * @version ${version} * @since 1.0 */ public class CRLChecker implements CertificateChecker { private CertificateRevocationLists crlsList; private CertStore certStore; private KeyStore keyStore; private boolean checkDateValidity; /** * Creates a CRLChecker where the CRL's are in the supplied stores. * * @param crlsList The object containing the CRL's * @param keyStore The store used to get trusted certs. * @param checkDateValidity Should we check if the CRL date is valid. */ public CRLChecker(CertificateRevocationLists crlsList, KeyStore keyStore, boolean checkDateValidity) { this.crlsList = crlsList; this.certStore = null; this.keyStore = keyStore; this.checkDateValidity = checkDateValidity; } /** * Creates a CRLChecker where the CRL's are in the supplied stores. * * @param certStore The store containing the CRL's * @param keyStore The store used to get trusted certs. * @param checkDateValidity Should we check if the CRL date is valid. */ public CRLChecker(CertStore certStore, KeyStore keyStore, boolean checkDateValidity) { this.crlsList = null; this.certStore = certStore; this.keyStore = keyStore; this.checkDateValidity = checkDateValidity; } /** * Method that checks the if the certificate is in a CRL, if CRL is * available If no CRL is found, then no error is thrown If an expired CRL * is found, an error is thrown * * @throws CertPathValidatorException If CRL or CA certificate could not be * loaded from store, CRL is not valid or * expired, certificate is revoked. */ public void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException { X500Principal certIssuer = cert.getIssuerX500Principal(); X509CRLSelector crlSelector = new X509CRLSelector(); crlSelector.addIssuer(certIssuer); Collection crls; if (crlsList != null) { crls = crlsList.getCRLs(crlSelector); } else { try { crls = this.certStore.getCRLs(crlSelector); } catch (CertStoreException e) { throw new CertPathValidatorException( "Error accessing CRL from certificate store: " + e.getMessage(), e); } } if (crls.size() < 1) { return; } // Get CA certificate for these CRLs X509CertSelector certSelector = new X509CertSelector(); certSelector.setSubject(certIssuer); Collection caCerts; try { caCerts = KeyStoreUtil .getTrustedCertificates(this.keyStore, certSelector); } catch (KeyStoreException e) { throw new CertPathValidatorException( "Error accessing CA certificate from certificate store for CRL validation", e); } if (caCerts.size() < 1) { // if there is no trusted certs from that CA, then // the chain cannot contain a cert from that CA, // which implies not checking this CRL should be fine. return; } Certificate caCert = caCerts.iterator().next(); for (CRL o : crls) { X509CRL crl = (X509CRL) o; // if expired, will throw error. if (checkDateValidity) { checkCRLDateValidity(crl); } // validate CRL verifyCRL(caCert, crl); /* One would have thought that a CRL is immutable and thus * thread safe, however inside the ASN1 parse tree we find * LazyDERSequence. LazyDERSequence is parsed lazily and * does so in a non-thread safe manner. One may very well * classify this as a bouncy castle bug, but as a * workaround synchronizing on the CRL solves the problem. */ synchronized (crl) { if (crl.isRevoked(cert)) { throw new CertPathValidatorException( "Certificate " + cert.getSubjectDN() + " has been revoked"); } } } } private void verifyCRL(Certificate caCert, X509CRL crl) throws CertPathValidatorException { try { crl.verify(caCert.getPublicKey()); } catch (CRLException e) { throw new CertPathValidatorException( "Error validating CRL from CA " + crl.getIssuerDN(), e); } catch (NoSuchAlgorithmException e) { throw new CertPathValidatorException( "Error validating CRL from CA " + crl.getIssuerDN(), e); } catch (InvalidKeyException e) { throw new CertPathValidatorException( "Error validating CRL from CA " + crl.getIssuerDN(), e); } catch (NoSuchProviderException e) { throw new CertPathValidatorException( "Error validating CRL from CA " + crl.getIssuerDN(), e); } catch (SignatureException e) { throw new CertPathValidatorException( "Error validating CRL from CA " + crl.getIssuerDN(), e); } } /* * Method to check the CRL validity for current time. * * @param crl * @throws CertPathValidatorException */ protected void checkCRLDateValidity(X509CRL crl) throws CertPathValidatorException { Date now = new Date(); boolean valid = crl.getThisUpdate().before(now) && ((crl.getNextUpdate() != null) && (crl.getNextUpdate().after(now))); if (!valid) { throw new CertPathValidatorException("CRL issued by " + crl.getIssuerDN() + " has expired"); } } } CertificateChecker.java000066400000000000000000000024211241116057200345750ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import java.security.cert.CertPathValidatorException; import java.security.cert.X509Certificate; import org.globus.gsi.GSIConstants; /** * Implementations of this interface will provide some validation logic of certificates. * * @version ${version} * @since 1.0 */ public interface CertificateChecker { /** * Validate the certificate. * * @param cert The certificate to validate. * @param certType The type of certificate to validate. * @throws CertPathValidatorException If validation fails. */ void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException; } DateValidityChecker.java000066400000000000000000000034411241116057200347410ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import java.security.cert.CertPathValidatorException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import org.globus.gsi.GSIConstants; /** * Checks if the certificate has expried or is not yet valid. * * @version ${version} * @since 1.0 */ public class DateValidityChecker implements CertificateChecker { /** * Method that checks the time validity. Uses the standard Certificate.checkValidity method. * * @throws CertPathValidatorException If certificate has expired or is not yet valid. */ public void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException { try { cert.checkValidity(); } catch (CertificateExpiredException e) { throw new CertPathValidatorException( "Certificate " + cert.getSubjectDN() + " expired", e); } catch (CertificateNotYetValidException e) { throw new CertPathValidatorException( "Certificate " + cert.getSubjectDN() + " not yet valid.", e); } } } IdentityChecker.java000066400000000000000000000044021241116057200341450ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import org.globus.gsi.util.ProxyCertificateUtil; import java.security.cert.CertPathValidatorException; import java.security.cert.X509Certificate; import org.globus.gsi.GSIConstants; /** * Checks to see if a limited proxy is acceptable (if the chain has a limited proxy). * Also, sets the identity certificate in the certificate path validator. */ public class IdentityChecker implements CertificateChecker { private X509ProxyCertPathValidator proxyCertValidator; public IdentityChecker(X509ProxyCertPathValidator proxyCertPathValidator) { this.proxyCertValidator = proxyCertPathValidator; } /** * Method that sets the identity of the certificate path. Also checks if * limited proxy is acceptable. * * @throws CertPathValidatorException If limited proxies are not accepted * and the chain has a limited proxy. */ public void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException { if (proxyCertValidator.getIdentityCertificate() == null) { // check if limited if (ProxyCertificateUtil.isLimitedProxy(certType)) { proxyCertValidator.setLimited(true); if (proxyCertValidator.isRejectLimitedProxy()) { throw new CertPathValidatorException( "Limited proxy not accepted"); } } // set the identity cert if (!ProxyCertificateUtil.isImpersonationProxy(certType)) { proxyCertValidator.setIdentityCert(cert); } } } } PKITrustManager.java000066400000000000000000000127431241116057200340560ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.X509ProxyCertPathParameters; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStoreException; import java.security.cert.CertPath; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorResult; import java.security.cert.CertPathValidatorSpi; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Vector; import javax.net.ssl.X509TrustManager; /** * This is an implementation of an X509TrustManager which supports the validation of proxy certificates. * It uses the Globus CertPathValidator. *

    * JGLOBUS-97 : ability to accept anonymous connections? * * @version ${version} * @since 1.0 */ public class PKITrustManager implements X509TrustManager { private CertPathValidatorSpi validator; private X509ProxyCertPathParameters parameters; private CertPathValidatorResult result; private Log logger = LogFactory.getLog(getClass().getCanonicalName()); /** * Create a trust manager with the pre-configured cert path validator and proxy parameters. * * @param initValidator A cert path validator to be used by this trust manager. * @param initParameters The proxy cert parameters, populated with trust store, cert store, etc. */ public PKITrustManager(CertPathValidatorSpi initValidator, X509ProxyCertPathParameters initParameters) { if (initValidator == null) { throw new IllegalArgumentException("Validator cannot be null"); } if (initParameters == null) { throw new IllegalArgumentException("Parameter cannot be null"); } this.validator = initValidator; this.parameters = initParameters; } /** * Test if the client is trusted based on the certificate chain. Does not currently support anonymous clients. * * @param x509Certificates The certificate chain to test for validity. * @param authType The authentication type based on the client certificate. * @throws CertificateException If the path validation fails. */ public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException { // JGLOBUS-97 : anonymous clients? CertPath certPath = CertificateUtil.getCertPath(x509Certificates); try { this.result = this.validator.engineValidate(certPath, parameters); } catch (CertPathValidatorException exception) { throw new CertificateException("Path validation failed: " + exception.getMessage(), exception); } catch (InvalidAlgorithmParameterException exception) { throw new CertificateException("Path validation failed: " + exception.getMessage(), exception); } } /** * Test if the server is trusted based on the certificate chain. * * @param x509Certificates The certificate chain to test for validity. * @param authType The authentication type based on the server certificate. * @throws CertificateException If the path validation fails. */ public void checkServerTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException { CertPath certPath = CertificateUtil.getCertPath(x509Certificates); try { this.result = this.validator.engineValidate(certPath, parameters); } catch (CertPathValidatorException exception) { throw new CertificateException("Path validation failed. " + exception.getMessage(), exception); } catch (InvalidAlgorithmParameterException exception) { throw new CertificateException("Path validation failed. " + exception.getMessage(), exception); } } /** * Get the collection of trusted certificate issuers. * * @return The trusted certificate issuers. */ public X509Certificate[] getAcceptedIssuers() { try { Collection trusted = CertificateLoadUtil.getTrustedCertificates( this.parameters.getTrustStore(), null); return trusted.toArray(new X509Certificate[trusted.size()]); } catch (KeyStoreException e) { logger.warn("Unable to load trusted Certificates. Authentication will fail.",e); return new X509Certificate[]{}; } } /** * Return the result of the last certificate validation. * * @return The validation result. */ public CertPathValidatorResult getValidationResult() { return this.result; } } PKITrustManagerFactory.java000066400000000000000000000071321241116057200354020ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import org.globus.gsi.X509ProxyCertPathParameters; import org.globus.gsi.provider.GlobusTrustManagerFactoryParameters; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.util.ArrayList; import java.util.Collection; import javax.net.ssl.CertPathTrustManagerParameters; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactorySpi; /** * This factory creates trust managers which support the Globus SSL library. * * @version ${version} * @since 1.0 */ public class PKITrustManagerFactory extends TrustManagerFactorySpi { private Collection trustManagers = new ArrayList(); /** * Initializes this factory with a source of certificate authorities and * related trust material. * * @param keyStore * The key store or null * @throws KeyStoreException * if the initialization fails. */ @Override protected void engineInit(KeyStore keyStore) throws KeyStoreException { try { this .engineInit(new CertPathTrustManagerParameters( new X509ProxyCertPathParameters(keyStore, null, null, false))); } catch (InvalidAlgorithmParameterException e) { throw new KeyStoreException(e); } } /** * Initializes this factory with a source of provider-specific key material. * In some cases, initialization parameters other than a keystore may be * needed by a provider. Users of that particular provider are expected to * pass an implementation of the appropriate ManagerFactoryParameters as * defined by the provider. The provider can then call the specified methods * in the ManagerFactoryParameters implementation to obtain the needed * information. *

    * This implementation requires X509ProxyCertPathParameters. * * @param managerFactoryParameters * The X509ProxyCertPathParameters which are used to create * TrustManagers. * @throws InvalidAlgorithmParameterException * If the Parameters are invalid */ @Override protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws InvalidAlgorithmParameterException { if (managerFactoryParameters instanceof GlobusTrustManagerFactoryParameters) { GlobusTrustManagerFactoryParameters ptmfp = (GlobusTrustManagerFactoryParameters) managerFactoryParameters; trustManagers.add(new PKITrustManager( new X509ProxyCertPathValidator(), ptmfp .getCertPathParameters())); } else { throw new InvalidAlgorithmParameterException( "Factory cannot accept parameters of type: " + managerFactoryParameters.getClass() .getCanonicalName()); } } /** * Returns one trust manager for each type of trust material. * * @return The collection of TrustManagers */ @Override protected TrustManager[] engineGetTrustManagers() { return trustManagers.toArray(new TrustManager[trustManagers.size()]); } } SigningPolicyChecker.java000066400000000000000000000056451241116057200351440ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import org.globus.gsi.util.ProxyCertificateUtil; import org.globus.gsi.provider.SigningPolicyStore; import java.security.cert.CertPathValidatorException; import java.security.cert.CertStoreException; import java.security.cert.X509Certificate; import javax.security.auth.x500.X500Principal; import org.globus.gsi.GSIConstants; import org.globus.gsi.SigningPolicy; /** * This checks to make sure the Distinguished Name in the certificate is valid according to the signing policy. */ public class SigningPolicyChecker implements CertificateChecker { private SigningPolicyStore policyStore; public SigningPolicyChecker(SigningPolicyStore policyStore) { this.policyStore = policyStore; } /** * Validate DN against the signing policy * * @param cert The certificate to check. * @param certType The type of certificate to check. * @throws CertPathValidatorException if the certificate is invalid according to the signing policy. */ public void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException { if (!requireSigningPolicyCheck(certType)) { return; } X500Principal caPrincipal = cert.getIssuerX500Principal(); SigningPolicy policy; try { policy = this.policyStore.getSigningPolicy(caPrincipal); } catch (CertStoreException e) { throw new CertPathValidatorException(e); } if (policy == null) { throw new CertPathValidatorException("No signing policy for " + cert.getIssuerDN()); } boolean valid = policy.isValidSubject(cert.getSubjectX500Principal()); if (!valid) { throw new CertPathValidatorException("Certificate " + cert.getSubjectDN() + " violates signing policy for CA " + caPrincipal.getName()); } } /** * if a certificate is not a CA or if it is not a proxy, return true. * * @param certType The type of Certificate being queried. * @return True if the CertificateType requires a Signing Policy check. */ private boolean requireSigningPolicyCheck(GSIConstants.CertificateType certType) { return !ProxyCertificateUtil.isProxy(certType) && certType != GSIConstants.CertificateType.CA; } } TrustedCertPathFinder.java000066400000000000000000000235121241116057200353070ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.util.KeyStoreUtil; import java.util.Iterator; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Principal; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.CertPath; import java.security.cert.CertPathValidatorException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Jan 20, 2010 * Time: 4:51:38 PM * To change this template use File | Settings | File Templates. */ public final class TrustedCertPathFinder { private static Log logger = LogFactory.getLog(TrustedCertPathFinder.class.getCanonicalName()); private TrustedCertPathFinder() { //this should not be instantiated. } private static CertPath isTrustedCert(KeyStore keyStore, X509Certificate x509Certificate, List trustedCertPath) throws CertPathValidatorException { X509CertSelector certSelector = new X509CertSelector(); certSelector.setCertificate(x509Certificate); Collection caCerts; try { caCerts = KeyStoreUtil.getTrustedCertificates(keyStore, certSelector); } catch (KeyStoreException e) { throw new CertPathValidatorException( "Error accessing trusted certificate store", e); } if ((caCerts.size() > 0)&&(x509Certificate.getBasicConstraints() != -1)) { trustedCertPath.add(x509Certificate); // JGLOBUS-92 try { CertificateFactory certFac = CertificateFactory.getInstance("X.509"); return certFac.generateCertPath(trustedCertPath); } catch (CertificateException e) { throw new CertPathValidatorException( "Error generating trusted certificate path", e); } } return null; } /** * Method that validates the provided cert path to find a trusted certificate in the certificate store. *

    * For each certificate i in certPath, it is expected that the i+1 certificate is the issuer of the certificate * path. See CertPath. *

    * For each certificate i in certpath, validate signature of certificate i get issuer of certificate i get * certificate i+i ensure that the certificate i+1 is issuer of certificate i If not, throw an exception for * illegal argument validate signature of i+1 Throw exception if it does not validate check if i+1 is a trusted * certificate in the trust store. If so return certpath until i+1 If not, continue; If all certificates in the * certpath have been checked and none exisits in trust store, check if trust store has certificate of issuer of * last certificate in CertPath. If so, return certPath + trusted certificate from trust store If not, throw * an exception for lack of valid trust root. * * @param keyStore The key store containing CA trust root certificates * @param certPath The certpath from which to extract a valid cert path to a trusted certificate. * @return The valid CertPath. * @throws CertPathValidatorException If the CertPath is invalid. */ public static CertPath findTrustedCertPath(KeyStore keyStore, CertPath certPath) throws CertPathValidatorException { // This will be the cert path to return List trustedCertPath = new ArrayList(); // This is the certs to validate List certs = certPath.getCertificates(); X509Certificate x509Certificate; int index = 0; int certsSize = certs.size(); Certificate certificate = certs.get(index); if (!(certificate instanceof X509Certificate)) { throw new CertPathValidatorException("Certificate of type " + X509Certificate.class.getName() + " required"); } x509Certificate = (X509Certificate) certificate; while (index < certsSize) { CertPath finalCertPath = isTrustedCert(keyStore, x509Certificate, trustedCertPath); if (finalCertPath != null) { return finalCertPath; } if (index + 1 >= certsSize) { break; } index++; Certificate issuerCertificate = certs.get(index); x509Certificate = checkCertificate(trustedCertPath, x509Certificate, issuerCertificate); } X509CertSelector selector = new X509CertSelector(); selector.setSubject(x509Certificate.getIssuerX500Principal()); Collection caCerts; try { caCerts = KeyStoreUtil.getTrustedCertificates(keyStore, selector); } catch (KeyStoreException e) { throw new CertPathValidatorException(e); } if (caCerts.size() < 1) { throw new CertPathValidatorException("No trusted path can be constructed"); } boolean foundTrustRoot = false; for (Certificate caCert : caCerts) { if (! (caCert instanceof X509Certificate)) { logger.warn("Skipped a certificate: not an X509Certificate"); continue; } try { trustedCertPath.add(checkCertificate(trustedCertPath, x509Certificate, caCert)); // currently the caCert self-signature is not checked // to be consistent with the isTrustedCert() method foundTrustRoot = true; // we found a CA cert that signed the certificate // so we don't need to check any more break; } catch (CertPathValidatorException e) { // fine, just move on to check the next potential CA cert // after the loop we'll check whether any were successful logger.warn("Failed to validate signature of certificate with " + "subject DN '" + x509Certificate.getSubjectDN() + "' against a CA certificate with issuer DN '" + ((X509Certificate)caCert).getSubjectDN() + "'"); } } if (! foundTrustRoot) { throw new CertPathValidatorException( "No trusted path can be constructed"); } try { CertificateFactory certFac = CertificateFactory.getInstance("X.509"); return certFac.generateCertPath(trustedCertPath); } catch (CertificateException e) { throw new CertPathValidatorException("Error generating trusted certificate path", e); } } private static X509Certificate checkCertificate(List trustedCertPath, X509Certificate x509Certificate, Certificate issuerCertificate) throws CertPathValidatorException { X509Certificate x509IssuerCertificate = (X509Certificate) issuerCertificate; // check that the next one is indeed issuer, normalizing to Globus DN format String issuerDN = CertificateUtil.toGlobusID( x509Certificate.getIssuerX500Principal()); String issuerCertDN = CertificateUtil.toGlobusID( x509IssuerCertificate.getSubjectX500Principal()); if (!(issuerDN.equals(issuerCertDN))) { throw new IllegalArgumentException("Incorrect certificate path, certificate in chain can only " + "be issuer of previous certificate"); } // validate integrity of signature PublicKey publicKey = x509IssuerCertificate.getPublicKey(); try { x509Certificate.verify(publicKey); } catch (CertificateException e) { throw new CertPathValidatorException( "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); } catch (NoSuchAlgorithmException e) { throw new CertPathValidatorException( "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); } catch (InvalidKeyException e) { throw new CertPathValidatorException( "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); } catch (NoSuchProviderException e) { throw new CertPathValidatorException( "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); } catch (SignatureException e) { throw new CertPathValidatorException( "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); } trustedCertPath.add(x509Certificate); return x509IssuerCertificate; } } UnsupportedCriticalExtensionChecker.java000066400000000000000000000067561241116057200402720ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import org.globus.gsi.util.ProxyCertificateUtil; import org.globus.gsi.proxy.ext.ProxyCertInfo; import java.security.cert.CertPathValidatorException; import java.security.cert.X509Certificate; import java.util.Set; import org.globus.gsi.GSIConstants; /** * Checks if the certificate includes unsupported critical extensions. * * @version ${version} * @since 1.0 */ public class UnsupportedCriticalExtensionChecker implements CertificateChecker { /** * Method that checks if there are unsupported critical extension. Supported * ones are only BasicConstrains, KeyUsage, Proxy Certificate (old and new) * * @param cert The certificate to validate. * @param certType The type of certificate to validate. * @throws CertPathValidatorException If any critical extension that is not supported is in the certificate. * Anything other than those listed above will trigger the exception. */ public void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException { Set criticalExtensionOids = cert.getCriticalExtensionOIDs(); if (criticalExtensionOids == null) { return; } for (String criticalExtensionOid : criticalExtensionOids) { isUnsupported(certType, criticalExtensionOid); } } private void isUnsupported(GSIConstants.CertificateType certType, String criticalExtensionOid) throws CertPathValidatorException { boolean unsupportedCritExtention = criticalExtensionOid.equals(X509ProxyCertPathValidator.BASIC_CONSTRAINT_OID); unsupportedCritExtention = unsupportedCritExtention || criticalExtensionOid.equals(X509ProxyCertPathValidator.KEY_USAGE_OID); unsupportedCritExtention = unsupportedCritExtention || (criticalExtensionOid.equals(ProxyCertInfo.OID.toString()) && ProxyCertificateUtil.isGsi4Proxy(certType)); unsupportedCritExtention = unsupportedCritExtention || (criticalExtensionOid.equals(ProxyCertInfo.OLD_OID.toString()) && ProxyCertificateUtil.isGsi3Proxy(certType)); if (unsupportedCritExtention) { return; } // if (criticalExtensionOid.equals(X509ProxyCertPathValidator.BASIC_CONSTRAINT_OID) // || criticalExtensionOid.equals(X509ProxyCertPathValidator.KEY_USAGE_OID) // || (criticalExtensionOid.equals(Constants.PROXY_OID.toString()) // && ProxyCertificateUtil.isGsi4Proxy(certType)) // || (criticalExtensionOid.equals(Constants.PROXY_OLD_OID.toString()) // && ProxyCertificateUtil.isGsi3Proxy(certType))) { // return; // } throw new CertPathValidatorException("Critical extension with unsupported OID " + criticalExtensionOid); } } X509ProxyCertPathValidator.java000066400000000000000000000625561241116057200361150ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.trustmanager; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.TBSCertificateStructure; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.globus.gsi.GSIConstants; import org.globus.gsi.X509ProxyCertPathParameters; import org.globus.gsi.X509ProxyCertPathValidatorResult; import org.globus.gsi.CertificateRevocationLists; import org.globus.gsi.provider.SigningPolicyStore; import org.globus.gsi.proxy.ProxyPolicyHandler; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.globus.gsi.proxy.ext.ProxyPolicy; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.util.KeyUsage; import org.globus.gsi.util.ProxyCertificateUtil; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.cert.CertPath; import java.security.cert.CertPathParameters; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorResult; import java.security.cert.CertPathValidatorSpi; import java.security.cert.CertStore; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.EnumSet; import java.util.Enumeration; import java.util.List; import java.util.Map; /** * Implementation of the CertPathValidatorSpi and the logic for X.509 Proxy Path Validation. * * @version ${version} * @since 1.0 */ public class X509ProxyCertPathValidator extends CertPathValidatorSpi { public static final String BASIC_CONSTRAINT_OID = "2.5.29.19"; public static final String KEY_USAGE_OID = "2.5.29.15"; protected KeyStore keyStore; protected CertStore certStore; protected SigningPolicyStore policyStore; private X509Certificate identityCert; private boolean limited; private boolean rejectLimitedProxy; private Map policyHandlers; /** * Validates the specified certification path using the specified algorithm parameter set. *

    * The CertPath specified must be of a type that is supported by the validation algorithm, otherwise * an InvalidAlgorithmParameterException will be thrown. For example, a CertPathValidator * that implements the PKIX algorithm validates CertPath objects of type X.509. * * @param certPath the CertPath to be validated * @param params the algorithm parameters * @return the result of the validation algorithm * @throws java.security.cert.CertPathValidatorException * if the CertPath does not validate * @throws java.security.InvalidAlgorithmParameterException * if the specified parameters or the type of the * specified CertPath are inappropriate for this CertPathValidator */ @SuppressWarnings("unchecked") public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException { if (certPath == null) { throw new IllegalArgumentException( "Certificate path cannot be null"); } List list = certPath.getCertificates(); if (list.size() < 1) { throw new IllegalArgumentException( "Certificate path cannot be empty"); } parseParameters(params); // find the root trust anchor. Validate signatures and see if the // chain ends in one of the trust root certificates CertPath trustedCertPath = TrustedCertPathFinder.findTrustedCertPath(this.keyStore, certPath); // rest of the validation return validate(trustedCertPath); } /** * Dispose of the current validation state. */ public void clear() { this.identityCert = null; this.limited = false; } protected void parseParameters(CertPathParameters params) throws InvalidAlgorithmParameterException { if (!(params instanceof X509ProxyCertPathParameters)) { throw new IllegalArgumentException("Parameter of type " + X509ProxyCertPathParameters.class.getName() + " required"); } X509ProxyCertPathParameters parameters = (X509ProxyCertPathParameters) params; this.keyStore = parameters.getTrustStore(); this.certStore = parameters.getCrlStore(); this.policyStore = parameters.getSigningPolicyStore(); this.rejectLimitedProxy = parameters.isRejectLimitedProxy(); this.policyHandlers = parameters.getPolicyHandlers(); } /** * Validates the certificate path and does the following for each certificate in the chain: method * checkCertificate() In addition: a) Validates if the issuer type of each certificate is correct b) CA path * constraints c) Proxy path constraints *

    * If it is of type proxy, check following: a) proxy constraints b) restricted proxy else if certificate, check the * following: a) keyisage * * @param certPath The CertPath to validate. * @return The results of the validation. * @throws CertPathValidatorException If the CertPath is invalid. */ protected CertPathValidatorResult validate(CertPath certPath) throws CertPathValidatorException { List certificates = certPath.getCertificates(); if (certificates.size() == 0) { return null; } X509Certificate cert; TBSCertificateStructure tbsCert; GSIConstants.CertificateType certType; X509Certificate issuerCert; TBSCertificateStructure issuerTbsCert; GSIConstants.CertificateType issuerCertType; int proxyDepth = 0; cert = (X509Certificate) certificates.get(0); try { tbsCert = getTBSCertificateStructure(cert); certType = getCertificateType(tbsCert); // validate the first certificate in chain checkCertificate(cert, certType); boolean isProxy = ProxyCertificateUtil.isProxy(certType); if (isProxy) { proxyDepth++; } } catch (CertPathValidatorException e) { throw new CertPathValidatorException("Path validation failed for " + cert.getSubjectDN() + ": " + e.getMessage(), e, certPath, 0); } for (int i = 1; i < certificates.size(); i++) { boolean certIsProxy = ProxyCertificateUtil.isProxy(certType); issuerCert = (X509Certificate) certificates.get(i); issuerTbsCert = getTBSCertificateStructure(issuerCert); issuerCertType = getCertificateType(issuerTbsCert); proxyDepth = validateCert(cert, certType, issuerCert, issuerTbsCert, issuerCertType, proxyDepth, i, certIsProxy); if (certIsProxy) { try { checkProxyConstraints(certPath, cert, tbsCert, certType, issuerTbsCert, i); } catch (CertPathValidatorException e) { throw new CertPathValidatorException("Path validation failed for " + cert.getSubjectDN() + ": " + e.getMessage(), e, certPath, i - 1); } } else { try { checkKeyUsage(issuerTbsCert); } catch (IOException e) { throw new CertPathValidatorException("Key usage check failed on " + issuerCert.getSubjectDN() + ": " + e.getMessage(), e, certPath, i); } catch (CertPathValidatorException e) { throw new CertPathValidatorException("Path validation failed for " + issuerCert.getSubjectDN() + ": " + e.getMessage(), e, certPath, i); } } try { checkCertificate(issuerCert, issuerCertType); } catch (CertPathValidatorException e) { throw new CertPathValidatorException("Path validation failed for " + issuerCert.getSubjectDN() + ": " + e.getMessage(), e, certPath, i); } cert = issuerCert; certType = issuerCertType; tbsCert = issuerTbsCert; } return new X509ProxyCertPathValidatorResult(this.identityCert, this.limited); } private GSIConstants.CertificateType getCertificateType(TBSCertificateStructure issuerTbsCert) throws CertPathValidatorException { GSIConstants.CertificateType issuerCertType; try { issuerCertType = CertificateUtil.getCertificateType(issuerTbsCert); } catch (CertificateException e) { throw new CertPathValidatorException( "Error obtaining certificate type", e); } catch (IOException e) { throw new CertPathValidatorException( "Error obtaining certificate type", e); } return issuerCertType; } private TBSCertificateStructure getTBSCertificateStructure(X509Certificate issuerCert) throws CertPathValidatorException { TBSCertificateStructure issuerTbsCert; try { issuerTbsCert = CertificateUtil.getTBSCertificateStructure(issuerCert); } catch (CertificateException e) { throw new CertPathValidatorException("Error converting certificate", e); } catch (IOException e) { throw new CertPathValidatorException("Error converting certificate", e); } return issuerTbsCert; } private int validateCert(X509Certificate cert, GSIConstants.CertificateType certType, X509Certificate issuerCert, TBSCertificateStructure issuerTbsCert, GSIConstants.CertificateType issuerCertType, int proxyDepth, int i, boolean certIsProxy) throws CertPathValidatorException { if (issuerCertType == GSIConstants.CertificateType.CA) { validateCACert(cert, issuerCert, issuerTbsCert, proxyDepth, i, certIsProxy); } else if (ProxyCertificateUtil.isGsi3Proxy(issuerCertType) || ProxyCertificateUtil.isGsi4Proxy(issuerCertType)) { return validateGsiProxyCert(cert, certType, issuerCert, issuerTbsCert, issuerCertType, proxyDepth); } else if (ProxyCertificateUtil.isGsi2Proxy(issuerCertType)) { return validateGsi2ProxyCert(cert, certType, issuerCert, proxyDepth); } else if (issuerCertType == GSIConstants.CertificateType.EEC) { validateEECCert(cert, certType, issuerCert); } else { // this should never happen? throw new CertPathValidatorException("UNknown issuer type " + issuerCertType + " for certificate " + issuerCert.getSubjectDN()); } return proxyDepth; } private void checkProxyConstraints(CertPath certPath, X509Certificate cert, TBSCertificateStructure tbsCert, GSIConstants.CertificateType certType, TBSCertificateStructure issuerTbsCert, int i) throws CertPathValidatorException { // check all the proxy & issuer constraints if (ProxyCertificateUtil.isGsi3Proxy(certType) || ProxyCertificateUtil.isGsi4Proxy(certType)) { try { checkProxyConstraints(tbsCert, issuerTbsCert, cert); } catch (IOException e) { throw new CertPathValidatorException("Proxy constraint check failed on " + cert.getSubjectDN(), e); } if ((certType == GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY) || (certType == GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY)) { try { checkRestrictedProxy(tbsCert, certPath, i); } catch (IOException e) { throw new CertPathValidatorException("Restricted proxy check failed on " + cert.getSubjectDN(), e); } } } } private void validateEECCert(X509Certificate cert, GSIConstants.CertificateType certType, X509Certificate issuerCert) throws CertPathValidatorException { if (!ProxyCertificateUtil.isProxy(certType)) { throw new CertPathValidatorException("EEC can only sign another proxy certificate. Violated by " + issuerCert.getSubjectDN() + " issuing " + cert.getSubjectDN()); } } private int validateGsi2ProxyCert(X509Certificate cert, GSIConstants.CertificateType certType, X509Certificate issuerCert, int proxyDepth) throws CertPathValidatorException { // PC can sign EEC or another PC only if (!ProxyCertificateUtil.isGsi2Proxy(certType)) { throw new CertPathValidatorException( "Proxy certificate can only sign another proxy certificate of same type. Violated by " + issuerCert.getSubjectDN() + " issuing " + cert.getSubjectDN()); } return proxyDepth + 1; } private int validateGsiProxyCert(X509Certificate cert, GSIConstants.CertificateType certType, X509Certificate issuerCert, TBSCertificateStructure issuerTbsCert, GSIConstants.CertificateType issuerCertType, int proxyDepth) throws CertPathValidatorException { if (ProxyCertificateUtil.isGsi3Proxy(issuerCertType)) { if (!ProxyCertificateUtil.isGsi3Proxy(certType)) { throw new CertPathValidatorException( "Proxy certificate can only sign another proxy certificate of same type. Violated by " + issuerCert.getSubjectDN() + " issuing " + cert.getSubjectDN()); } } else if (ProxyCertificateUtil.isGsi4Proxy(issuerCertType) && !ProxyCertificateUtil.isGsi4Proxy(certType)) { throw new CertPathValidatorException( "Proxy certificate can only sign another proxy certificate of same type. Violated by " + issuerCert.getSubjectDN() + " issuing " + cert.getSubjectDN()); } int pathLen; try { pathLen = ProxyCertificateUtil.getProxyPathConstraint(issuerTbsCert); } catch (IOException e) { throw new CertPathValidatorException("Error obtaining proxy path constraint", e); } if (pathLen == 0) { throw new CertPathValidatorException( "Proxy path length constraint violated of certificate " + issuerCert.getSubjectDN()); } if (pathLen < Integer.MAX_VALUE && proxyDepth > pathLen) { throw new CertPathValidatorException( "Proxy path length constraint violated of certificate " + issuerCert.getSubjectDN()); } return proxyDepth + 1; } private void validateCACert( X509Certificate cert, X509Certificate issuerCert, TBSCertificateStructure issuerTbsCert, int proxyDepth, int i, boolean certIsProxy) throws CertPathValidatorException { // PC can only be signed by EEC or PC if (certIsProxy) { throw new CertPathValidatorException( "Proxy certificate can be signed only by EEC or Proxy " + "Certificate. Certificate " + cert.getSubjectDN() + " violates this."); } try { int pathLen = CertificateUtil.getCAPathConstraint(issuerTbsCert); if (pathLen < Integer.MAX_VALUE && (i - proxyDepth - 1) > pathLen) { throw new CertPathValidatorException("Path length constraint of certificate " + issuerCert.getSubjectDN() + " violated"); } } catch (IOException e) { throw new CertPathValidatorException("Error obtaining CA Path constraint", e); } } // private X509Certificate checkCertificate(List trustedCertPath, X509Certificate x509Certificate, // Certificate issuerCertificate) throws CertPathValidatorException { // X509Certificate x509IssuerCertificate = (X509Certificate) issuerCertificate; // // // check that the next one is indeed issuer // Principal issuerDN = x509Certificate.getIssuerDN(); // Principal issuerCertDN = x509IssuerCertificate.getSubjectDN(); // if (!(issuerDN.equals(issuerCertDN))) { // throw new IllegalArgumentException("Incorrect certificate path, certificate in chain can only " // + "be issuer of previous certificate"); // } // // // validate integrity of signature // PublicKey publicKey = x509IssuerCertificate.getPublicKey(); // try { // x509Certificate.verify(publicKey); // } catch (CertificateException e) { // throw new CertPathValidatorException( // "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); // } catch (NoSuchAlgorithmException e) { // throw new CertPathValidatorException( // "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); // } catch (InvalidKeyException e) { // throw new CertPathValidatorException( // "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); // } catch (NoSuchProviderException e) { // throw new CertPathValidatorException( // "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); // } catch (SignatureException e) { // throw new CertPathValidatorException( // "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e); // } // // trustedCertPath.add(x509Certificate); // return x509IssuerCertificate; // } protected void checkRestrictedProxy(TBSCertificateStructure proxy, CertPath certPath, int index) throws CertPathValidatorException, IOException { ProxyCertInfo info = ProxyCertificateUtil.getProxyCertInfo(proxy); ProxyPolicy policy = info.getProxyPolicy(); String pl = policy.getPolicyLanguage().getId(); ProxyPolicyHandler handler = null; if (this.policyHandlers != null) { handler = this.policyHandlers.get(pl); } if (handler == null) { throw new CertPathValidatorException("Unknown policy, no handler registered to validate policy " + pl); } handler.validate(info, certPath, index); } protected void checkKeyUsage(TBSCertificateStructure issuer) throws CertPathValidatorException, IOException { EnumSet issuerKeyUsage = CertificateUtil.getKeyUsage(issuer); if (issuerKeyUsage != null && !issuerKeyUsage.contains(KeyUsage.KEY_CERTSIGN)) { throw new CertPathValidatorException("Certificate " + issuer.getSubject() + " violated key usage policy."); } } // COMMENT enable the checkers again when ProxyPathValidator starts working! protected List getCertificateCheckers() { List checkers = new ArrayList(); checkers.add(new DateValidityChecker()); checkers.add(new UnsupportedCriticalExtensionChecker()); checkers.add(new IdentityChecker(this)); // NOTE: the (possible) refresh of the CRLs happens when we call getDefault. // Hence, we must recreate crlsList for each call to checkCertificate // Sadly, this also means that the amount of work necessary for checkCertificate // can be arbitrarily large (if the CRL is indeed refreshed). // // Note we DO NOT use this.certStore by default! TODO: This differs from the unit test CertificateRevocationLists crlsList = CertificateRevocationLists.getDefaultCertificateRevocationLists(); checkers.add(new CRLChecker(crlsList, this.keyStore, true)); checkers.add(new SigningPolicyChecker(this.policyStore)); return checkers; } /* * Method to check following for any given certificate * * a) Date validity, is it valid for the curent time (see DateValidityChecker) * b) Any unsupported critical extensions (see UnsupportedCriticalExtensionChecker) * c) Identity of certificate (see IdentityChecker) * d) Revocation (see CRLChecker) * e) Signing policy (see SigningPolicyChecker) * */ private void checkCertificate(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException { for (CertificateChecker checker : getCertificateCheckers()) { checker.invoke(cert, certType); } } @SuppressWarnings("unused") protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer, X509Certificate checkedProxy) throws CertPathValidatorException, IOException { X509Extensions extensions; DERObjectIdentifier oid; X509Extension proxyExtension; X509Extension proxyKeyUsage = null; extensions = proxy.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { oid = (DERObjectIdentifier) e.nextElement(); proxyExtension = extensions.getExtension(oid); if (oid.equals(X509Extension.subjectAlternativeName) || oid.equals(X509Extension.issuerAlternativeName)) { // No Alt name extensions - 3.2 & 3.5 throw new CertPathValidatorException( "Proxy violation: no Subject or Issuer Alternative Name"); } else if (oid.equals(X509Extension.basicConstraints)) { // Basic Constraint must not be true - 3.8 BasicConstraints basicExt = CertificateUtil.getBasicConstraints(proxyExtension); if (basicExt.isCA()) { throw new CertPathValidatorException( "Proxy violation: Basic Constraint CA is set to true"); } } else if (oid.equals(X509Extension.keyUsage)) { proxyKeyUsage = proxyExtension; checkKeyUsage(issuer, proxyExtension); } } } extensions = issuer.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { oid = (DERObjectIdentifier) e.nextElement(); proxyExtension = extensions.getExtension(oid); checkExtension(oid, proxyExtension, proxyKeyUsage); } } } private void checkKeyUsage(TBSCertificateStructure issuer, X509Extension proxyExtension) throws IOException, CertPathValidatorException { EnumSet keyUsage = CertificateUtil.getKeyUsage(proxyExtension); // these must not be asserted if (keyUsage.contains(KeyUsage.NON_REPUDIATION) || keyUsage.contains(KeyUsage.KEY_CERTSIGN)) { throw new CertPathValidatorException("Proxy violation: Key usage is asserted."); } } private void checkExtension(DERObjectIdentifier oid, X509Extension proxyExtension, X509Extension proxyKeyUsage) throws CertPathValidatorException { if (oid.equals(X509Extension.keyUsage)) { // If issuer has it then proxy must have it also if (proxyKeyUsage == null) { throw new CertPathValidatorException( "Proxy violation: Issuer has key usage, but proxy does not"); } // If issuer has it as critical so does the proxy if (proxyExtension.isCritical() && !proxyKeyUsage.isCritical()) { throw new CertPathValidatorException( "Proxy voilation: issuer key usage is critical, but proxy certificate's is not"); } } } public X509Certificate getIdentityCertificate() { return this.identityCert; } public void setLimited(boolean limited) { this.limited = limited; } // COMMENT: added a way to get 'limited' public boolean isLimited() { return this.limited; } public void setIdentityCert(X509Certificate identityCert) { this.identityCert = identityCert; } public boolean isRejectLimitedProxy() { return this.rejectLimitedProxy; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/000077500000000000000000000000001241116057200265445ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/CertificateIOUtil.java000066400000000000000000000133121241116057200327170ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.FileOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import javax.security.auth.x500.X500Principal; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.x509.X509Name; /** * Fill Me */ public final class CertificateIOUtil { // for PEM strings public static final int LINE_LENGTH = 64; public static final String LINE_SEP = "\n"; public static final String CERT_HEADER = "-----BEGIN CERTIFICATE-----"; public static final String CERT_FOOTER = "-----END CERTIFICATE-----"; public static final String KEY_HEADER = "-----BEGIN RSA PRIVATE KEY-----"; public static final String KEY_FOOTER = "-----END RSA PRIVATE KEY-----"; private static Log logger = LogFactory.getLog(CertificateIOUtil.class.getCanonicalName()); private static MessageDigest md5; private CertificateIOUtil() { //This should not be instantiated } private static void init() { if (md5 == null) { try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("", e); } } } /** * Returns equivalent of: * openssl x509 -in "cert-file" -hash -noout * * @param subjectDN * @return hash for certificate names */ public static String nameHash(X500Principal subjectDN) { try { return hash(encodePrincipal(subjectDN)); } catch (Exception e) { logger.error("", e); return null; } } /** * Returns equivalent of: openssl x509 -in "cert-file" -hash -noout * * @param subjectDN * @return hash for certificate names */ public static String nameHash(X509Name subjectDN) { try { return hash(encodePrincipal(subjectDN)); } catch (Exception e) { logger.error("", e); return null; } } public static byte[] encodePrincipal(X500Principal subject) throws IOException { return subject.getEncoded(); } public static byte[] encodePrincipal(X509Name subject) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DEROutputStream der = new DEROutputStream(bout); der.writeObject(subject.toASN1Primitive()); return bout.toByteArray(); } private synchronized static String hash(byte[] data) { init(); if (md5 == null) { return null; } md5.reset(); md5.update(data); byte[] md = md5.digest(); long ret = (fixByte(md[0]) | (fixByte(md[1]) << 8L)); ret = ret | fixByte(md[2]) << 16L; ret = ret | fixByte(md[3]) << 24L; ret = ret & 0xffffffffL; return Long.toHexString(ret); } private static long fixByte(byte b) { return (b < 0) ? (long) (b + 256) : (long) b; } public static void writeCertificate(X509Certificate cert, File path) throws CertificateEncodingException, IOException { FileOutputStream fos = new FileOutputStream(path); writeCertificate(fos, cert); fos.close(); } /** * Creates PEM encoded cert string with line length, header and footer. * * @param base64Data already encoded into string * @return string */ public static String certToPEMString(String base64Data) { return toStringImpl(base64Data, false); } /** * Writes certificate to the specified output stream in PEM format. */ public static void writeCertificate( OutputStream out, X509Certificate cert) throws IOException, CertificateEncodingException { PEMUtil.writeBase64(out, "-----BEGIN CERTIFICATE-----", Base64.encode(cert.getEncoded()), "-----END CERTIFICATE-----"); } private static String toStringImpl(String base64Data, boolean isKey) { int length = LINE_LENGTH; int offset = 0; final StringBuffer buf = new StringBuffer(2048); if (isKey) { buf.append(KEY_HEADER); } else { buf.append(CERT_HEADER); } buf.append(LINE_SEP); final int size = base64Data.length(); while (offset < size) { if (LINE_LENGTH > (size - offset)) { length = size - offset; } buf.append(base64Data.substring(offset, offset + length)); buf.append(LINE_SEP); offset = offset + LINE_LENGTH; } if (isKey) { buf.append(KEY_FOOTER); } else { buf.append(CERT_FOOTER); } buf.append(LINE_SEP); return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/CertificateLoadUtil.java000066400000000000000000000251621241116057200332750ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509CRL; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.Vector; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Base64; /** * Contains various security-related utility methods. */ public final class CertificateLoadUtil { static { Security.addProvider(new BouncyCastleProvider()); logger = LogFactory.getLog(CertificateLoadUtil.class.getCanonicalName()); setProvider("BC"); } private static Log logger; private static String provider; private CertificateLoadUtil() { //This should not be created. } /** * A no-op function that can be used to force the class to load and * initialize. */ public static void init() { } /** * Sets a provider name to use for loading certificates and for generating * key pairs. * * @param providerName provider name to use. */ public static void setProvider(String providerName) { provider = providerName; logger.debug("Provider set to : " + providerName); } /** * Returns appropriate CertificateFactory. If provider * was set a provider-specific CertificateFactory will be used. * Otherwise, a default CertificateFactory will be used. * * @return CertificateFactory */ protected static CertificateFactory getCertificateFactory() throws GeneralSecurityException { if (provider == null) { return CertificateFactory.getInstance("X.509"); } else { return CertificateFactory.getInstance("X.509", provider); } } /** * Loads a X509 certificate from the specified input stream. Input stream * must contain DER-encoded certificate. * * @param in the input stream to read the certificate from. * @return X509Certificate the loaded certificate. * @throws GeneralSecurityException if certificate failed to load. */ public static X509Certificate loadCertificate(InputStream in) throws GeneralSecurityException { return (X509Certificate) getCertificateFactory().generateCertificate(in); } /** * Loads an X.509 certificate from the specified file. The certificate file * must be in PEM/Base64 format and start with "BEGIN CERTIFICATE" and end * with "END CERTIFICATE" line. * * @param file the file to load the certificate from. * @return java.security.cert.X509Certificate the loaded * certificate. * @throws IOException if I/O error occurs * @throws GeneralSecurityException if security problems occurs. */ public static X509Certificate loadCertificate(String file) throws IOException, GeneralSecurityException { if (file == null) { throw new IllegalArgumentException("Certificate file is null"); //i18n // .getMessage("certFileNull")); } X509Certificate cert = null; BufferedReader reader = new BufferedReader(new FileReader(file)); try { cert = readCertificate(reader); } finally { reader.close(); } if (cert == null) { throw new GeneralSecurityException("No certificate data"); //i18n.getMessage("noCertData")); } return cert; } /** * Loads multiple X.509 certificates from the specified file. Each * certificate must be in PEM/Base64 format and start with "BEGIN * CERTIFICATE" and end with "END CERTIFICATE" line. * * @param file the certificate file to load the certificate from. * @return an array of certificates loaded from the file. * @throws IOException if I/O error occurs * @throws GeneralSecurityException if security problems occurs. */ public static X509Certificate[] loadCertificates(String file) throws IOException, GeneralSecurityException { if (file == null) { throw new IllegalArgumentException("Certificate file is null"); //i18n // .getMessage("certFileNull")); } List list = new ArrayList(); BufferedReader reader = new BufferedReader(new FileReader(file)); X509Certificate cert = readCertificate(reader); try { while (cert != null) { list.add(cert); cert = readCertificate(reader); } } finally { reader.close(); } if (list.size() == 0) { throw new GeneralSecurityException("No certificate data"); //i18n.getMessage("noCertData")); } int size = list.size(); return list.toArray(new X509Certificate[size]); } /** * Loads a X.509 certificate from the specified reader. The certificate * contents must start with "BEGIN CERTIFICATE" line and end with "END * CERTIFICATE" line, and be in PEM/Base64 format. *

    * This function does not close the input stream. * * @param reader the stream from which load the certificate. * @return the loaded certificate or null if there was no certificate in the * stream or the stream is closed. * @throws IOException if I/O error occurs * @throws GeneralSecurityException if security problems occurs. */ public static X509Certificate readCertificate(BufferedReader reader) throws IOException, GeneralSecurityException { String line; StringBuffer buff = new StringBuffer(); boolean isCert = false; boolean isKey = false; boolean notNull = false; while ((line = reader.readLine()) != null) { // Skip key info, if any if (line.indexOf("BEGIN RSA PRIVATE KEY") != -1 || line.indexOf("BEGIN PRIVATE KEY") != -1) { isKey = true; continue; } else if (isKey && (line.indexOf("END RSA PRIVATE KEY") != -1 || line.indexOf("END PRIVATE KEY") != -1)) { isKey = false; continue; } else if (isKey) continue; notNull = true; if (line.indexOf("BEGIN CERTIFICATE") != -1) { isCert = true; } else if (isCert && line.indexOf("END CERTIFICATE") != -1) { byte[] data = Base64.decode(buff.toString().getBytes()); return loadCertificate(new ByteArrayInputStream(data)); } else if (isCert) { buff.append(line); } } if (notNull && !isCert) { throw new GeneralSecurityException( "Certificate needs to start with " + " BEGIN CERTIFICATE"); } return null; } public static X509CRL loadCrl(String file) throws IOException, GeneralSecurityException { if (file == null) { throw new IllegalArgumentException("crlFileNull"); //i18n.getMessage("crlFileNull")); } boolean isCrl = false; X509CRL crl = null; BufferedReader reader; String line; StringBuffer buff = new StringBuffer(); reader = new BufferedReader(new FileReader(file)); try { while ((line = reader.readLine()) != null) { if (line.indexOf("BEGIN X509 CRL") != -1) { isCrl = true; } else if (isCrl && line.indexOf("END X509 CRL") != -1) { byte[] data = Base64.decode(buff.toString().getBytes()); crl = loadCrl(new ByteArrayInputStream(data)); } else if (isCrl) { buff.append(line); } } } finally { reader.close(); } if (crl == null) { throw new GeneralSecurityException("noCrlsData"); //i18n.getMessage("noCrlData")); } return crl; } public static X509CRL loadCrl(InputStream in) throws GeneralSecurityException { return (X509CRL) getCertificateFactory().generateCRL(in); } public static Collection getTrustedCertificates(KeyStore keyStore, X509CertSelector selector) throws KeyStoreException { Vector certificates = new Vector(); Enumeration aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { // If a specific impl of keystore requires refresh, this would be a // good place to add it. Certificate certificate = keyStore.getCertificate(alias); if (certificate instanceof X509Certificate) { X509Certificate x509Cert = (X509Certificate) certificate; if (selector == null) { certificates.add(x509Cert); } else if (selector.match(certificate)) { certificates.add(x509Cert); } } } } return certificates; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/CertificateUtil.java000066400000000000000000000631331241116057200324750ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.TBSCertificateStructure; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.globus.common.CoGProperties; import org.globus.gsi.GSIConstants; import org.globus.gsi.bc.X509NameHelper; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.globus.gsi.proxy.ext.ProxyPolicy; import javax.security.auth.x500.X500Principal; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Principal; import java.security.Provider; import java.security.Security; import java.security.cert.CertPath; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import static org.globus.gsi.util.Oid.*; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public final class CertificateUtil { private static String provider; private static Log logger; static { Security.addProvider(new BouncyCastleProvider()); setProvider("BC"); logger = LogFactory.getLog(CertificateLoadUtil.class.getCanonicalName()); installSecureRandomProvider(); } private static final Map KEYWORD_MAP = new HashMap(); private static final Map OID_MAP = new HashMap(); static { // Taken from BouncyCastle 2.46 KEYWORD_MAP.put("SN", SERIALNUMBER.oid); KEYWORD_MAP.put("E", EmailAddress.oid); KEYWORD_MAP.put("EMAIL", EmailAddress.oid); KEYWORD_MAP.put("UNSTRUCTUREDADDRESS", UnstructuredAddress.oid); KEYWORD_MAP.put("UNSTRUCTUREDNAME", UnstructuredName.oid); KEYWORD_MAP.put("UNIQUEIDENTIFIER", UNIQUE_IDENTIFIER.oid); KEYWORD_MAP.put("DN", DN_QUALIFIER.oid); KEYWORD_MAP.put("PSEUDONYM", PSEUDONYM.oid); KEYWORD_MAP.put("POSTALADDRESS", POSTAL_ADDRESS.oid); KEYWORD_MAP.put("NAMEOFBIRTH", NAME_AT_BIRTH.oid); KEYWORD_MAP.put("COUNTRYOFCITIZENSHIP", COUNTRY_OF_CITIZENSHIP.oid); KEYWORD_MAP.put("COUNTRYOFRESIDENCE", COUNTRY_OF_RESIDENCE.oid); KEYWORD_MAP.put("GENDER", GENDER.oid); KEYWORD_MAP.put("PLACEOFBIRTH", PLACE_OF_BIRTH.oid); KEYWORD_MAP.put("DATEOFBIRTH", DATE_OF_BIRTH.oid); KEYWORD_MAP.put("POSTALCODE", POSTAL_CODE.oid); KEYWORD_MAP.put("BUSINESSCATEGORY", BUSINESS_CATEGORY.oid); KEYWORD_MAP.put("TELEPHONENUMBER", TELEPHONE_NUMBER.oid); KEYWORD_MAP.put("NAME", NAME.oid); // Taken from CANL library KEYWORD_MAP.put("S", ST.oid); KEYWORD_MAP.put("DNQUALIFIER", DN_QUALIFIER.oid); KEYWORD_MAP.put("IP", IP.oid); OID_MAP.put(UnstructuredAddress.oid, "unstructuredAddress"); OID_MAP.put(UnstructuredName.oid, "unstructuredName"); OID_MAP.put(UNIQUE_IDENTIFIER.oid, "UniqueIdentifier"); OID_MAP.put(PSEUDONYM.oid, "Pseudonym"); OID_MAP.put(POSTAL_ADDRESS.oid, "PostalAddress"); OID_MAP.put(NAME_AT_BIRTH.oid, "NameAtBirth"); OID_MAP.put(COUNTRY_OF_CITIZENSHIP.oid, "CountryOfCitizenship"); OID_MAP.put(COUNTRY_OF_RESIDENCE.oid, "CountryOfResidence"); OID_MAP.put(GENDER.oid, "Fender"); OID_MAP.put(PLACE_OF_BIRTH.oid, "PlaceOfBirth"); OID_MAP.put(DATE_OF_BIRTH.oid, "DateOfBirth"); OID_MAP.put(POSTAL_CODE.oid, "PostalCode"); OID_MAP.put(BUSINESS_CATEGORY.oid, "BusinessCategory"); OID_MAP.put(TELEPHONE_NUMBER.oid, "TelephoneNumber"); OID_MAP.put(NAME.oid, "Name"); OID_MAP.put(IP.oid, "IP"); OID_MAP.put(T.oid, "T"); OID_MAP.put(DN_QUALIFIER.oid, "DNQUALIFIER"); OID_MAP.put(SURNAME.oid, "SURNAME"); OID_MAP.put(GIVENNAME.oid, "GIVENNAME"); OID_MAP.put(INITIALS.oid, "INITIALS"); OID_MAP.put(GENERATION.oid, "GENERATION"); OID_MAP.put(EmailAddress.oid, "EMAILADDRESS"); OID_MAP.put(SERIALNUMBER.oid, "SERIALNUMBER"); } private CertificateUtil() { //this should not be constructed; } /** * A no-op function that can be used to force the class * to load and initialize. */ public static void init() { CertificateLoadUtil.init(); } /** * Sets a provider name to use for loading certificates * and for generating key pairs. * * @param providerName provider name to use. */ public static void setProvider(String providerName) { provider = providerName; } /** * Installs SecureRandom provider. * This function is automatically called when this class is loaded. */ public static void installSecureRandomProvider() { CoGProperties props = CoGProperties.getDefault(); String providerName = props.getSecureRandomProvider(); try { Class providerClass = Class.forName(providerName); Security.insertProviderAt( (Provider)providerClass.newInstance(), 1 ); } catch (Exception e) { logger.debug("Unable to install PRNG. Using default PRNG.",e); } } /** * Return CA Path constraint * * @param crt * @return the CA path constraint * @throws IOException */ public static int getCAPathConstraint(TBSCertificateStructure crt) throws IOException { X509Extensions extensions = crt.getExtensions(); if (extensions == null) { return -1; } X509Extension proxyExtension = extensions.getExtension(X509Extension.basicConstraints); if (proxyExtension != null) { BasicConstraints basicExt = getBasicConstraints(proxyExtension); if (basicExt.isCA()) { BigInteger pathLen = basicExt.getPathLenConstraint(); return (pathLen == null) ? Integer.MAX_VALUE : pathLen.intValue(); } else { return -1; } } return -1; } /** * Generates a key pair of given algorithm and strength. * * @param algorithm the algorithm of the key pair. * @param bits the strength * @return KeyPair the generated key pair. * @exception GeneralSecurityException if something goes wrong. */ public static KeyPair generateKeyPair(String algorithm, int bits) throws GeneralSecurityException { KeyPairGenerator generator = null; if (provider == null) { generator = KeyPairGenerator.getInstance(algorithm); } else { generator = KeyPairGenerator.getInstance(algorithm, provider); } generator.initialize(bits); return generator.generateKeyPair(); } /** * Returns certificate type of the given TBS certificate.
    The * certificate type is {@link org.globus.gsi.GSIConstants.CertificateType#CA * GSIConstants.CertificateType.CA} only if the certificate contains a * BasicConstraints extension and it is marked as CA.
    A certificate is a * GSI-2 proxy when the subject DN of the certificate ends with * "CN=proxy" (certificate type {@link org.globus.gsi.GSIConstants.CertificateType#GSI_2_PROXY * GSIConstants.CertificateType.GSI_2_PROXY}) or "CN=limited proxy" (certificate * type {@link org.globus.gsi.GSIConstants.CertificateType#GSI_2_LIMITED_PROXY * GSIConstants.CertificateType.LIMITED_PROXY}) component and the issuer DN of the * certificate matches the subject DN without the last proxy CN * component.
    A certificate is a GSI-3 proxy when the subject DN of the * certificate ends with a CN component, the issuer DN of the * certificate matches the subject DN without the last CN component * and the certificate contains {@link ProxyCertInfo * ProxyCertInfo} critical extension. The certificate type is {@link * org.globus.gsi.GSIConstants.CertificateType#GSI_3_IMPERSONATION_PROXY * GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY} if the policy language of the * {@link ProxyCertInfo ProxyCertInfo} * extension is set to {@link ProxyPolicy#IMPERSONATION * ProxyPolicy.IMPERSONATION} OID. The certificate type is {@link * org.globus.gsi.GSIConstants.CertificateType#GSI_3_LIMITED_PROXY * GSIConstants.CertificateType.GSI_3_LIMITED_PROXY} if the policy language of the {@link * ProxyCertInfo ProxyCertInfo} extension * is set to {@link ProxyPolicy#LIMITED * ProxyPolicy.LIMITED} OID. The certificate type is {@link * org.globus.gsi.GSIConstants.CertificateType#GSI_3_INDEPENDENT_PROXY * GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY} if the policy language of the * {@link ProxyCertInfo ProxyCertInfo} * extension is set to {@link ProxyPolicy#INDEPENDENT * ProxyPolicy.INDEPENDENT} OID. The certificate type is {@link * org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} if the policy language of the * {@link ProxyCertInfo ProxyCertInfo} * extension is set to any other OID then the above.
    The certificate * type is {@link org.globus.gsi.GSIConstants.CertificateType#EEC * GSIConstants.CertificateType.EEC} if the certificate is not a CA certificate or a * GSI-2 or GSI-3 proxy. * * @param crt the TBS certificate to get the type of. * @return the certificate type. The certificate type is determined by rules * described above. * @throws java.io.IOException if something goes wrong. * @throws java.security.cert.CertificateException * for proxy certificates, if the issuer DN of * the certificate does not match the subject DN * of the certificate without the last CN * component. Also, for GSI-3 proxies when the * ProxyCertInfo extension is not * marked as critical. */ public static GSIConstants.CertificateType getCertificateType( TBSCertificateStructure crt) throws CertificateException, IOException { X509Extensions extensions = crt.getExtensions(); X509Extension ext = null; if (extensions != null) { ext = extensions.getExtension(X509Extension.basicConstraints); if (ext != null) { BasicConstraints basicExt = getBasicConstraints(ext); if (basicExt.isCA()) { return GSIConstants.CertificateType.CA; } } } GSIConstants.CertificateType type = GSIConstants.CertificateType.EEC; // does not handle multiple AVAs X500Name subject = crt.getSubject(); ASN1Set entry = X509NameHelper.getLastNameEntry(subject); ASN1Sequence ava = (ASN1Sequence) entry.getObjectAt(0); if (BCStyle.CN.equals(ava.getObjectAt(0))) { type = processCN(extensions, type, ava); } return type; } private static GSIConstants.CertificateType processCN( X509Extensions extensions, GSIConstants.CertificateType type, ASN1Sequence ava) throws CertificateException { X509Extension ext; String value = ((ASN1String) ava.getObjectAt(1)).getString(); GSIConstants.CertificateType certType = type; if (value.equalsIgnoreCase("proxy")) { certType = GSIConstants.CertificateType.GSI_2_PROXY; } else if (value.equalsIgnoreCase("limited proxy")) { certType = GSIConstants.CertificateType.GSI_2_LIMITED_PROXY; } else if (extensions != null) { boolean gsi4 = true; // GSI_4 ext = extensions.getExtension(ProxyCertInfo.OID); if (ext == null) { // GSI_3 ext = extensions.getExtension(ProxyCertInfo.OLD_OID); gsi4 = false; } if (ext != null) { if (ext.isCritical()) { certType = processCriticalExtension(ext, gsi4); } else { String err = "proxyCertCritical"; throw new CertificateException(err); } } } return certType; } private static GSIConstants.CertificateType processCriticalExtension(X509Extension ext, boolean gsi4) { GSIConstants.CertificateType type; ProxyCertInfo proxyCertExt = ProxyCertificateUtil.getProxyCertInfo(ext); ProxyPolicy proxyPolicy = proxyCertExt.getProxyPolicy(); DERObjectIdentifier oid = proxyPolicy.getPolicyLanguage(); if (ProxyPolicy.IMPERSONATION.equals(oid)) { if (gsi4) { type = GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY; } else { type = GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY; } } else if (ProxyPolicy.INDEPENDENT.equals(oid)) { if (gsi4) { type = GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY; } else { type = GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY; } } else if (ProxyPolicy.LIMITED.equals(oid)) { if (gsi4) { type = GSIConstants.CertificateType.GSI_4_LIMITED_PROXY; } else { type = GSIConstants.CertificateType.GSI_3_LIMITED_PROXY; } } else { if (gsi4) { type = GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY; } else { type = GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY; } } return type; } /** * Creates a BasicConstraints object from given extension. * * @param ext the extension. * @return the BasicConstraints object. * @throws IOException if something fails. */ public static BasicConstraints getBasicConstraints(X509Extension ext) throws IOException { ASN1Object object = X509Extension.convertValueToObject(ext); return BasicConstraints.getInstance(object); } /** * Converts the DER-encoded byte array into a DERObject. * * @param data the DER-encoded byte array to convert. * @return the DERObject. * @throws IOException if conversion fails */ public static ASN1Primitive toASN1Primitive(byte[] data) throws IOException { ByteArrayInputStream inStream = new ByteArrayInputStream(data); ASN1InputStream derInputStream = new ASN1InputStream(inStream); return derInputStream.readObject(); } /** * Extracts the TBS certificate from the given certificate. * * @param cert the X.509 certificate to extract the TBS certificate from. * @return the TBS certificate * @throws IOException if extraction fails. * @throws CertificateEncodingException if extraction fails. */ public static TBSCertificateStructure getTBSCertificateStructure( X509Certificate cert) throws CertificateEncodingException, IOException { ASN1Primitive obj = toASN1Primitive(cert.getTBSCertificate()); return TBSCertificateStructure.getInstance(obj); } public static EnumSet getKeyUsage(TBSCertificateStructure crt) throws IOException { X509Extensions extensions = crt.getExtensions(); if (extensions == null) { return null; } X509Extension extension = extensions.getExtension(X509Extension.keyUsage); return (extension != null) ? getKeyUsage(extension) : null; } /** * Gets a boolean array representing bits of the KeyUsage extension. * * @throws IOException if failed to extract the KeyUsage extension value. * @see java.security.cert.X509Certificate#getKeyUsage */ public static EnumSet getKeyUsage(X509Extension ext) throws IOException { DERBitString bits = (DERBitString) getExtensionObject(ext); EnumSet keyUsage = EnumSet.noneOf(KeyUsage.class); for (KeyUsage bit: KeyUsage.values()) { if (bit.isSet(bits)) { keyUsage.add(bit); } } return keyUsage; } /** * Extracts the value of a certificate extension. * * @param ext the certificate extension to extract the value from. * @throws IOException if extraction fails. */ public static ASN1Primitive getExtensionObject(X509Extension ext) throws IOException { return toASN1Primitive(ext.getValue().getOctets()); } /** * Converts DN of the form "CN=A, OU=B, O=C" into Globus * format "/CN=A/OU=B/O=C".
    * This function might return incorrect Globus-formatted ID when one of * the RDNs in the DN contains commas. * @see #toGlobusID(String, boolean) * * @param dn the DN to convert to Globus format. * @return the converted DN in Globus format. */ public static String toGlobusID(String dn) { return toGlobusID(dn, true); } /** * Converts DN of the form "CN=A, OU=B, O=C" into Globus * format "/CN=A/OU=B/O=C" or "/O=C/OU=B/CN=A" depending on the * noreverse option. If noreverse is true * the order of the DN components is not reveresed - "/CN=A/OU=B/O=C" is * returned. If noreverse is false, the order of the * DN components is reversed - "/O=C/OU=B/CN=A" is returned.
    * This function might return incorrect Globus-formatted ID when one of * the RDNs in the DN contains commas. * * @param dn the DN to convert to Globus format. * @param noreverse the direction of the conversion. * @return the converted DN in Globus format. */ public static String toGlobusID(String dn, boolean noreverse) { if (dn == null) { return null; } StringBuilder buf = new StringBuilder(); String[] tokens = dn.split(","); if (noreverse) { for (int i = 0; i < tokens.length; i++) { String token = tokens[i].trim(); if (!token.isEmpty()) { buf.append("/"); buf.append(token.trim()); } } } else { for (int i = tokens.length - 1; i >= 0; i--) { String token = tokens[i].trim(); if (!token.isEmpty()) { buf.append("/"); buf.append(token.trim()); } } } return buf.toString(); } /** * Converts the specified principal into Globus format. * If the principal is of unrecognized type a simple string-based * conversion is made using the {@link #toGlobusID(String) toGlobusID()} * function. * * @see #toGlobusID(String) * * @param name the principal to convert to Globus format. * @return the converted DN in Globus format. */ public static String toGlobusID(Principal name) { if (name instanceof X509Name) { return X509NameHelper.toString((X509Name)name); } else if (name instanceof X500Principal) { return CertificateUtil.toGlobusID((X500Principal) name); } else { return CertificateUtil.toGlobusID(name.getName()); } } /** * Converts DN of the form "CN=A, OU=B, O=C" into Globus format * "/O=C/OU=B/CN=A"
    This function might return incorrect * Globus-formatted ID when one of the RDNs in the DN contains commas. * * @return the converted DN in Globus format. */ public static String toGlobusID(X500Principal principal) { if (principal == null) { return null; } String dn = principal.getName(X500Principal.RFC2253, OID_MAP); StringBuilder buf = new StringBuilder(); final int IDLE = 0; final int VALUE = 1; final int KEY = 2; int state = IDLE; int cEnd = 0; char[] asChars = dn.toCharArray(); /* * walk in reverse order and merge RDN */ for (int i = asChars.length - 1; i >= 0; i--) { char c = asChars[i]; switch (state) { case KEY: if (c == ',') { String s = dn.substring(i + 1, cEnd + 1); buf.append('/').append(s); state = IDLE; } break; case VALUE: if (c == '=') { state = KEY; } break; case IDLE: default: cEnd = i; state = VALUE; } } String s = dn.substring(0, cEnd + 1); buf.append('/').append(s); // remove comma escaping as some other components may use string comparison. return buf.toString().replace("\\,", ","); } /** * Converts Globus DN format "/O=C/OU=B/CN=A" into an X500Principal * representation, which accepts RFC 2253 or 1779 formatted DN's and also * attribute types as defined in RFC 2459 (e.g. "CN=A,OU=B,O=C"). This * method should allow the forward slash, "/", to occur in attribute values * (see GFD.125 section 3.2.2 -- RFC 2252 allows "/" in PrintableStrings). * @param globusID DN in Globus format * @return the X500Principal representation of the given DN */ public static X500Principal toPrincipal(String globusID) { if (globusID == null) { return null; } String id = globusID.trim(); StringBuilder buf = new StringBuilder(id.length()); if (!id.isEmpty()) { final int IDLE = 0; final int VALUE = 1; final int KEY = 2; int state = IDLE; int cEnd = 0; char[] asChars = id.toCharArray(); /* * walk in reverse order and split into RDN */ for (int i = asChars.length - 1; i >= 0; i--) { char c = asChars[i]; switch (state) { case KEY: if (c == '/' || c == ' ') { /* handle names with comma according rfc1779 */ String s = id.substring(i + 1, cEnd + 1); int commaIndex = s.indexOf(','); if (commaIndex != -1) { s = s.substring(0, commaIndex) + "\\" + s.substring(commaIndex); } buf.append(s).append(','); state = IDLE; } break; case VALUE: if (c == '=') { state = KEY; } break; case IDLE: default: // idle if (c == '/' || c == ' ') { continue; } else { cEnd = i; state = VALUE; } } } // delete last extra comma buf.deleteCharAt(buf.length() - 1); } String dn = buf.toString(); return new X500Principal(dn, KEYWORD_MAP); } // JGLOBUS-91 public static CertPath getCertPath(X509Certificate[] certs) throws CertificateException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); return factory.generateCertPath(Arrays.asList(certs)); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/FileUtil.java000066400000000000000000000023611241116057200311260ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public final class FileUtil { private FileUtil() { //This should not be instantiated. } public static File createFile(String filename) throws IOException { File f = new File(filename); if (!f.createNewFile()) { FileUtils.forceDelete(f); if (!f.createNewFile()) { throw new SecurityException( "Failed to atomically create new file"); } } return f; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/KeyStoreFactory.java000066400000000000000000000015411241116057200325050ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Jan 21, 2010 * Time: 12:43:13 PM * To change this template use File | Settings | File Templates. */ public interface KeyStoreFactory { T createKeyStore(); } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/KeyStoreUtil.java000066400000000000000000000044231241116057200320150ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.Certificate; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Enumeration; import java.util.Vector; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public final class KeyStoreUtil { private KeyStoreUtil() { //Should not be constructed } /** * Returns the list of certificates in the KeyStore. Return object will not * be null. * * @param keyStore * @param selector * @return the list of certificates in the KeyStore * @throws KeyStoreException */ public static Collection getTrustedCertificates(KeyStore keyStore, X509CertSelector selector) throws KeyStoreException { Vector certificates = new Vector(); Enumeration aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { // If a specific impl of keystore requires refresh, this would be a // good place to add it. Certificate certificate = keyStore.getCertificate(alias); if (certificate instanceof X509Certificate) { X509Certificate x509Cert = (X509Certificate) certificate; if (selector.match(certificate)) { certificates.add(x509Cert); } } } } return certificates; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/KeyUsage.java000066400000000000000000000022751241116057200311320ustar00rootroot00000000000000/* * Copyright 2013 NORDUnet A/S * * 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 org.globus.gsi.util; import org.bouncycastle.asn1.DERBitString; public enum KeyUsage { DIGITAL_SIGNATURE(0), NON_REPUDIATION(1), KEY_ENCIPHERMENT(2), DATA_ENCIPHERMENT(3), KEY_AGREEMENT(4), KEY_CERTSIGN(5), CRL_SIGN(6), ENCIPHER_ONLY(7), DECIPHER_ONLY(8); private int bit; private KeyUsage(int bit) { this.bit = bit; } public boolean isSet(DERBitString bits) { byte[] bytes = bits.getBytes(); int length = (bytes.length * 8) - bits.getPadBits(); return (bit < length && ((bytes[bit / 8] & (0x80 >>> (bit % 8))) != 0)); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/Oid.java000066400000000000000000000106031241116057200301220ustar00rootroot00000000000000package org.globus.gsi.util; /** * Common OID values. * * Adapted from BouncyCastle BCStyle class. * * Copyright (c) 2000 - 2012 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public enum Oid { /** * country code - StringType(SIZE(2)) */ C("2.5.4.6"), /** * organization - StringType(SIZE(1..64)) */ O("2.5.4.10"), /** * organizational unit name - StringType(SIZE(1..64)) */ OU("2.5.4.11"), /** * Title */ T("2.5.4.12"), /** * common name - StringType(SIZE(1..64)) */ CN("2.5.4.3"), /** * device serial number name - StringType(SIZE(1..64)) */ SERIALNUMBER("2.5.4.5"), /** * locality name - StringType(SIZE(1..64)) */ L("2.5.4.7"), /** * state, or province name - StringType(SIZE(1..64)) */ ST("2.5.4.8"), /** * street - StringType(SIZE(1..64)) */ STREET("2.5.4.9"), /** * Naming attributes of type X520name */ SURNAME("2.5.4.4"), GIVENNAME("2.5.4.42"), INITIALS("2.5.4.43"), GENERATION("2.5.4.44"), UNIQUE_IDENTIFIER("2.5.4.45"), /** * businessCategory - DirectoryString(SIZE(1..128) */ BUSINESS_CATEGORY("2.5.4.15"), /** * postalCode - DirectoryString(SIZE(1..40) */ POSTAL_CODE("2.5.4.17"), /** * dnQualifier - DirectoryString(SIZE(1..64) */ DN_QUALIFIER("2.5.4.46"), /** * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64) */ PSEUDONYM("2.5.4.65"), /** * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z */ DATE_OF_BIRTH("1.3.6.1.5.5.7.9.1"), /** * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128) */ PLACE_OF_BIRTH("1.3.6.1.5.5.7.9.2"), /** * RFC 3039 Gender - PrintableString (SIZE(1)) -- "M", "F", "m" or "f" */ GENDER("1.3.6.1.5.5.7.9.3"), /** * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ COUNTRY_OF_CITIZENSHIP("1.3.6.1.5.5.7.9.4"), /** * RFC 3039 CountryOfResidence - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ COUNTRY_OF_RESIDENCE("1.3.6.1.5.5.7.9.5"), /** * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64) */ NAME_AT_BIRTH("1.3.36.8.3.14"), /** * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF * DirectoryString(SIZE(1..30)) */ POSTAL_ADDRESS("2.5.4.16"), /** * RFC 2256 dmdName */ DMD_NAME("2.5.4.54"), /** * id-at-telephoneNumber */ TELEPHONE_NUMBER("2.5.4.20"), /** * id-at-name */ NAME("2.5.4.41"), /** * Email address (RSA PKCS#9 extension) - IA5String. *

    Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here. */ EmailAddress("1.2.840.113549.1.9.1"), /** * more from PKCS#9 */ UnstructuredName("1.2.840.113549.1.9.2"), UnstructuredAddress("1.2.840.113549.1.9.8"), /* * others... */ DC("0.9.2342.19200300.100.1.25"), /** * LDAP User id. */ UID("0.9.2342.19200300.100.1.1"), IP("1.3.6.1.4.1.42.2.11.2.1"); public final String oid; private Oid(String value) { this.oid = value; } @Override public String toString() { return oid; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/PEMUtil.java000066400000000000000000000047701241116057200306760ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import java.io.IOException; import java.io.OutputStream; // JGLOBUS-95 : how much of this can be borrwed directly form BC? /** * Fill Me */ public final class PEMUtil { public static final String LINE_SEP; static final byte[] LINE_SEP_BYTES; static final int LINE_LENGTH = 64; private static final char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; static { LINE_SEP = System.getProperty("line.separator"); LINE_SEP_BYTES = LINE_SEP.getBytes(); } private PEMUtil() { //This should not be instantiated } public static void writeBase64( OutputStream out, String header, byte[] base64Data, String footer) throws IOException { int length = LINE_LENGTH; int offset = 0; if (header != null) { out.write(header.getBytes()); out.write(LINE_SEP_BYTES); } int size = base64Data.length; while (offset < size) { if (LINE_LENGTH > (size - offset)) { length = size - offset; } out.write(base64Data, offset, length); out.write(LINE_SEP_BYTES); offset = offset + LINE_LENGTH; } if (footer != null) { out.write(footer.getBytes()); out.write(LINE_SEP_BYTES); } } /** * Return a hexadecimal representation of a byte array * * @param b a byte array * @return String containing the hexadecimal representation */ public static String toHex(byte[] b) { char[] buf = new char[b.length * 2]; int j = 0; int k; for (byte aB : b) { k = aB; buf[j++] = HEX[(k >>> 4) & 0x0F]; buf[j++] = HEX[k & 0x0F]; } return new String(buf); } } ProxyCertificateUtil.java000066400000000000000000000170211241116057200334530ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/gsi/util/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import java.io.IOException; import org.bouncycastle.asn1.x509.TBSCertificateStructure; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.globus.gsi.GSIConstants; import org.globus.gsi.proxy.ext.ProxyCertInfo; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public final class ProxyCertificateUtil { private ProxyCertificateUtil() { //This should not be instantiated } /** * Determines if a specified certificate type indicates a GSI-2, GSI-3 or * GSI-4proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-2 or GSI-3 or GSI-4 proxy, false * otherwise. */ public static boolean isProxy(GSIConstants.CertificateType certType) { return isGsi2Proxy(certType) || isGsi3Proxy(certType) || isGsi4Proxy(certType); } /** * Determines if a specified certificate type indicates a GSI-4 proxy * certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-4 proxy, false otherwise. */ public static boolean isGsi4Proxy(GSIConstants.CertificateType certType) { return certType == GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY || certType == GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY || certType == GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY || certType == GSIConstants.CertificateType.GSI_4_LIMITED_PROXY; } /** * Determines if a specified certificate type indicates a GSI-3 proxy * certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-3 proxy, false otherwise. */ public static boolean isGsi3Proxy(GSIConstants.CertificateType certType) { return certType == GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY || certType == GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY || certType == GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY || certType == GSIConstants.CertificateType.GSI_3_LIMITED_PROXY; } /** * Determines if a specified certificate type indicates a GSI-2 proxy * certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-2 proxy, false otherwise. */ public static boolean isGsi2Proxy(GSIConstants.CertificateType certType) { return certType == GSIConstants.CertificateType.GSI_2_PROXY || certType == GSIConstants.CertificateType.GSI_2_LIMITED_PROXY; } /** * Determines if a specified certificate type indicates a GSI-2 or GSI-3 or * GSI=4 limited proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-2 or GSI-3 or GSI-4 limited proxy, * false otherwise. */ public static boolean isLimitedProxy(GSIConstants.CertificateType certType) { return certType == GSIConstants.CertificateType.GSI_3_LIMITED_PROXY || certType == GSIConstants.CertificateType.GSI_2_LIMITED_PROXY || certType == GSIConstants.CertificateType.GSI_4_LIMITED_PROXY; } /** * Determines if a specified certificate type indicates a GSI-3 or GS-4 * limited proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-3 or GSI-4 independent proxy, false * otherwise. */ public static boolean isIndependentProxy( GSIConstants.CertificateType certType) { return certType == GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY || certType == GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY; } /** * Determines if a specified certificate type indicates a GSI-2 or GSI-3 or * GSI-4 impersonation proxy certificate. * * @param certType the certificate type to check. * @return true if certType is a GSI-2 or GSI-3 or GSI-4 impersonation * proxy, false otherwise. */ public static boolean isImpersonationProxy(GSIConstants.CertificateType certType) { return certType == GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY || certType == GSIConstants.CertificateType.GSI_3_LIMITED_PROXY || certType == GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY || certType == GSIConstants.CertificateType.GSI_4_LIMITED_PROXY || certType == GSIConstants.CertificateType.GSI_2_LIMITED_PROXY || certType == GSIConstants.CertificateType.GSI_2_PROXY; } public static int getProxyPathConstraint(TBSCertificateStructure crt) throws IOException { ProxyCertInfo proxyCertExt = getProxyCertInfo(crt); return (proxyCertExt != null) ? proxyCertExt.getPathLenConstraint() : -1; } public static ProxyCertInfo getProxyCertInfo(TBSCertificateStructure crt) throws IOException { X509Extensions extensions = crt.getExtensions(); if (extensions == null) { return null; } X509Extension ext = extensions.getExtension(ProxyCertInfo.OID); if (ext == null) { ext = extensions.getExtension(ProxyCertInfo.OLD_OID); } return (ext != null) ? getProxyCertInfo(ext) : null; } public static ProxyCertInfo getProxyCertInfo(X509Extension ext) { byte[] value = ext.getValue().getOctets(); return ProxyCertInfo.getInstance(value); } /** * Returns a string description of a specified proxy * type. * * @param proxyType the proxy type to get the string * description of. * @return the string description of the proxy type. */ public static String getProxyTypeAsString(GSIConstants.CertificateType proxyType) { switch(proxyType) { case GSI_4_IMPERSONATION_PROXY: return "RFC 3820 compliant impersonation proxy"; case GSI_4_INDEPENDENT_PROXY: return "RFC 3820 compliant independent proxy"; case GSI_4_LIMITED_PROXY: return "RFC 3820 compliant limited proxy"; case GSI_4_RESTRICTED_PROXY: return "RFC 3820 compliant restricted proxy"; case GSI_3_IMPERSONATION_PROXY: return "Proxy draft compliant impersonation proxy"; case GSI_3_INDEPENDENT_PROXY: return "Proxy draft compliant independent proxy"; case GSI_3_LIMITED_PROXY: return "Proxy draft compliant limited proxy"; case GSI_3_RESTRICTED_PROXY: return "Proxy draft compliant restricted proxy"; case GSI_2_PROXY: return "full legacy globus proxy"; case GSI_2_LIMITED_PROXY: return "limited legacy globus proxy"; default: return "not a proxy"; } } }JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/000077500000000000000000000000001241116057200261455ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/CertInfo.java000066400000000000000000000135721241116057200305310ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.tools; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.util.CertificateUtil; import java.security.cert.X509Certificate; import java.util.TimeZone; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.globus.common.CoGProperties; import org.globus.common.Version; /** Returns information about the Cert *

     * Syntax: java CertInfo [-help] [-file certfile] [-all] [-subject] [...]
     * Displays certificate information. Unless the optional -file
     * argument is given, the default location of the file containing the
     * certficate is assumed:
     *   --  Config.getUserCertFile()
     * Options
     *   -help, -usage                Display usage
     *   -version                     Display version
     *   -file certfile               Use 'certfile' at non-default location
     *   -globus                      Prints information in globus format
     * Options determining what to print from certificate
     *   -all                        Whole certificate
     *   -subject                    Subject string of the cert
     *   -issuer                     Issuer
     *   -startdate                  Validity of cert: start date
     *   -enddate                    Validity of cert: end date
     * 
    */ public class CertInfo { private static final int SUBJECT = 2; private static final int ISSUER = 4; private static final int SDATE = 8; private static final int EDATE = 16; private static final int ALL = 32; private static String message = "\n" + "Syntax: java CertInfo [-help] [-file certfile] [-all] [-subject] [...]\n\n" + "\tDisplays certificate information. Unless the optional \n" + "\tfile argument is given, the default location of the file\n" + "\tcontaining the certficate is assumed:\n\n" + "\t -- " + CoGProperties.getDefault().getUserCertFile() + "\n\n" + "\tOptions\n" + "\t-help | -usage\n" + "\t\tDisplay usage.\n" + "\t-version\n" + "\t\tDisplay version.\n" + "\t-file certfile\n" + "\t\tUse 'certfile' at non-default location.\n" + "\t-globus\n" + "\t\tPrints information in globus format.\n\n" + "\tOptions determining what to print from certificate\n\n" + "\t-all\n" + "\t\tWhole certificate.\n" + "\t-subject\n" + "\t\tSubject string of the cert.\n" + "\t-issuer\n" + "\t\tIssuer.\n" + "\t-startdate\n" + "\t\tValidity of cert: start date.\n" + "\t-enddate\n" + "\t\tValidity of cert: end date.\n\n"; public static void main(String args[]) { String file = null; int options = 0; boolean error = false; boolean globusStyle = false; boolean debug = false; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-file")) { file = args[++i]; } else if (args[i].equalsIgnoreCase("-subject")) { options |= SUBJECT; } else if (args[i].equalsIgnoreCase("-issuer")) { options |= ISSUER; } else if (args[i].equalsIgnoreCase("-startdate")) { options |= SDATE; } else if (args[i].equalsIgnoreCase("-enddate")) { options |= EDATE; } else if (args[i].equalsIgnoreCase("-all")) { options |= ALL; } else if (args[i].equalsIgnoreCase("-globus")) { globusStyle = true; } else if (args[i].equalsIgnoreCase("-version")) { System.err.println(Version.getVersion()); System.exit(1); } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-usage")) { System.err.println(message); System.exit(1); } else { System.err.println("Error: argument not recognized : " + args[i]); error = true; } } if (error) { System.err.println("\nUsage: java CertInfo [-help] [-file certfile] [-all] [-subject] [...]\n"); System.err.println("Use -help to display full usage."); System.exit(1); } if (file == null) { file = CoGProperties.getDefault().getUserCertFile(); } X509Certificate cert = null; try { cert = CertificateLoadUtil.loadCertificate(file); } catch(Exception e) { System.err.println("Unable to load the certificate : " + e.getMessage()); System.exit(1); } if (options == 0) { options = SUBJECT | ISSUER | SDATE | EDATE; } if ((options & SUBJECT) != 0) { String dn = null; if (globusStyle) { dn = CertificateUtil.toGlobusID(cert.getSubjectDN()); } else { dn = cert.getSubjectDN().getName(); } System.out.println("subject : " + dn); } if ((options & ISSUER) != 0) { String dn = null; if (globusStyle) { dn = CertificateUtil.toGlobusID(cert.getIssuerDN()); } else { dn = cert.getIssuerDN().getName(); } System.out.println("issuer : " + dn); } TimeZone tz = null; DateFormat df = null; if (globusStyle) { tz = TimeZone.getTimeZone("GMT"); df = new SimpleDateFormat("MMM dd HH:mm:ss yyyy z"); df.setTimeZone(tz); } if ((options & SDATE) != 0) { String dt = null; if (globusStyle) { dt = df.format(cert.getNotBefore()); } else { dt = cert.getNotBefore().toString(); } System.out.println("start date : " + dt); } if ((options & EDATE) != 0) { String dt = null; if (globusStyle) { dt = df.format(cert.getNotAfter()); } else { dt = cert.getNotAfter().toString(); } System.out.println("end date : " + dt); } if ((options & ALL) != 0) { System.out.println("certificate :"); System.out.println(cert.toString()); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/ChangePassPhrase.java000066400000000000000000000132051241116057200321700ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.tools; import java.security.GeneralSecurityException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import org.globus.gsi.OpenSSLKey; import org.globus.gsi.CertUtil; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import org.globus.util.Util; import org.globus.common.CoGProperties; import org.globus.common.Version; /** Changes the Passphrase. *
     * Syntax: java ChangePassPhrase [-help] [-version] [-file private_key_file]
      * Changes the passphrase that protects the private key. If the -file
      * argument is not given, the default location of the file containing
      * the private key is assumed:
      *   --  Config.getUserKeyFile()
      * Options
      *   -help, -usage                Display usage
      *   -version                     Display version
      *   -file location               Change passphrase on key stored in the
      *                                file at the non-standard
      *                                location 'location';
     * 
    */ public class ChangePassPhrase { private static String message = "\n" + "Syntax: java ChangePassPhrase [-help] [-version] [-file private_key_file]\n\n" + "\tChanges the passphrase that protects the private key. If the\n" + "\t-file argument is not given, the default location of the file\n" + "\tcontaining the private key is assumed:\n\n" + "\t -- " + CoGProperties.getDefault().getUserKeyFile() + "\n\n" + "\tOptions\n" + "\t-help | -usage\n" + "\t\tDisplay usage.\n" + "\t-version\n" + "\t\tDisplay version.\n" + "\t-file location\n" + "\t\tChange passphrase on key stored in the file at\n" + "\t\tthe non-standard location 'location'.\n\n"; public static void main(String args[]) { String file = null; boolean error = false; boolean debug = false; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-file")) { file = args[++i]; } else if (args[i].equalsIgnoreCase("-version")) { System.err.println(Version.getVersion()); System.exit(1); } else if (args[i].equalsIgnoreCase("-debug")) { debug = true; } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-usage")) { System.err.println(message); System.exit(1); } else { System.err.println("Error: argument not recognized : " + args[i]); error = true; } } if (error) { System.err.println("\nUsage: java ChangePassPhrase [-help] [-version] [-file private_key_file]\n"); System.err.println("Use -help to display full usage."); System.exit(1); } CertUtil.init(); if (file == null) { file = CoGProperties.getDefault().getUserKeyFile(); } OpenSSLKey key = null; String pwd1, pwd2 = null; try { key = new BouncyCastleOpenSSLKey(file); if (key.isEncrypted()) { pwd1 = Util.getPrivateInput("Enter OLD pass phrase: "); if (pwd1 == null || pwd1.length() == 0) return; try { key.decrypt(pwd1); } catch(Exception e) { System.err.println("Error: Wrong pass phrase or key is invalid."); if (debug) { e.printStackTrace(); } System.exit(1); } } pwd1 = Util.getPrivateInput("Enter NEW pass phrase: "); if (pwd1 == null || pwd1.length() == 0) return; pwd2 = Util.getPrivateInput("Verifying password - Enter NEW pass phrase: "); if (pwd2 == null || pwd2.length() == 0) return; if (!pwd1.equals(pwd2)) { System.err.println("Error: Passwords do not match!"); System.exit(1); } key.encrypt(pwd1); File newFile = Util.createFile(file + ".new"); Util.setOwnerAccessOnly(newFile.getAbsolutePath()); File oldFile = Util.createFile(file + ".old"); Util.setOwnerAccessOnly(oldFile.getAbsolutePath()); File crFile = Util.createFile(file); Util.setOwnerAccessOnly(crFile.getAbsolutePath()); copy(crFile, oldFile); key.writeTo(newFile.getAbsolutePath()); if (!crFile.delete()) { System.err.println("Error: failed to remove " + file + " file."); System.exit(1); } if (newFile.renameTo(crFile)) { System.out.println("Pass phrase successfully changed."); } else { System.err.println("Error: failed to rename the files."); System.exit(1); } } catch(GeneralSecurityException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } catch(Exception e) { System.err.println("Unable to load the private key : " + e.getMessage()); System.exit(1); } } private static void copy(File srcFile, File dstFile) throws IOException { InputStream in = null; OutputStream out = null; byte [] buffer = new byte[1024]; int bytes = 0; try { in = new FileInputStream(srcFile); out = new FileOutputStream(dstFile); Util.setOwnerAccessOnly(dstFile.getAbsolutePath()); while( (bytes = in.read(buffer)) != -1) { out.write(buffer, 0, bytes); out.flush(); } } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch(Exception e) {} } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/GridCertRequest.java000066400000000000000000000435041241116057200320720ustar00rootroot00000000000000/** * Copyright (c) 2003, National Research Council of Canada * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to * do so, subject to the following conditions: * * The above copyright notice(s) and this licence appear in all copies of the * Software or substantial portions of the Software, and that both the above * copyright notice(s) and this license appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE * FOR ANY CLAIM, OR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL * DAMAGES, OR ANY DAMAGES WHATSOEVER (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWSOEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OF THE SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Except as contained in this notice, the name of a copyright holder shall NOT * be used in advertising or otherwise to promote the sale, use or other * dealings in this Software without specific prior written authorization. * Title to copyright in this software and any associated documentation will at * all times remain with copyright holders. */ package org.globus.tools; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.jce.PKCS10CertificationRequest; import org.bouncycastle.util.encoders.Base64; import org.globus.common.Version; import org.globus.common.CoGProperties; import org.globus.gsi.CertUtil; import org.globus.gsi.OpenSSLKey; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import org.globus.gsi.bc.X509NameHelper; import org.globus.util.PEMUtils; import org.globus.util.Util; import org.globus.util.ConfigUtil; /** * GridCertRequest Command Line Client. * * @author Jean-Claude Cote */ public final class GridCertRequest { public static final String USAGE = "\n" + "\ngrid-cert-request [-help] [ options ...]" + "\n" + "\n Example Usage:" + "\n" + "\n Creating a user certifcate:" + "\n grid-cert-request" + "\n" + "\n Creating a host or gatekeeper certifcate:" + "\n grid-cert-request -host [my.host.fqdn]" + "\n" + "\n Creating a LDAP server certificate:" + "\n grid-cert-request -service ldap -host [my.host.fqdn]" + "\n" + "\n Options:" + "\n" + "\n -version : Display version" + "\n -?, -h, -help, : Display usage" + "\n -usage" + "\n -cn , : Common name of the user" + "\n -commonname " + "\n -service : Create certificate for a service. Requires" + "\n the -host option and implies that the generated" + "\n key will not be password protected (ie implies -nopw)." + "\n -host : Create certificate for a host named " + "\n -dir : Changes the directory the private key and certificate" + "\n request will be placed in. By default user certificates" + "\n are placed in " + System.getProperty("user.home") + File.separator + ".globus" + "\n directory. On Unix machines, host certificates are" + "\n placed in /etc/grid-security directory and service" + "\n certificates are placed in /etc/grid-security/." + "\n On Windows machines they are placed in the same" + "\n location as the user certificates." + "\n -prefix : Causes the generated files to be named" + "\n cert.pem, key.pem and" + "\n cert_request.pem" + "\n -nopw, : Create certificate without a password" + "\n -nodes," + "\n -nopassphrase," + "\n -verbose : Don't clear the screen <>" + "\n -int[eractive] : Prompt user for each component of the DN" + "\n -force : Overwrites preexisting certifictes" + "\n -caEmail
    : CA email address, if request is to be mailed to CA" + "\n -orgBaseDN : The base DN of this organization (in LDAP format)"; private static final String MESSAGE = "A certificate request and private key will be created." + "\nYou will be asked to enter a PEM pass phrase." + "\nThis pass phrase is akin to your account password," + "\nand is used to protect your key file." + "\nIf you forget your pass phrase, you will need to" + "\nobtain a new certificate.\n"; private static String caEmail = null; private static String cn = null; private static boolean interactive = false; private static boolean verbose = false; private static boolean noPswd = false; private static String dir = null; private static boolean force = false; private static String prefix = null; private static boolean debug = false; public static void main(String[] args) { parseCmdLine(args); File certDir = new File(dir); // Create dir if does not exists. if (!certDir.exists()) { // if fails exit if (!certDir.mkdirs()) { exit("Unable to create " + certDir + " directory.", 1); } } // Make sure it's a directory. if (!certDir.isDirectory()) { exit("The directory " + certDir + " specified is not a directory.", 2); } // Make sure we can write to it. if (!certDir.canWrite()) { exit("Can't write to " + certDir, 3); } File certFile = new File(certDir, prefix + "cert.pem"); File keyFile = new File(certDir, prefix + "key.pem"); File certRequestFile = new File(certDir, prefix + "cert_request.pem"); // Check not to overwrite any of these files. if (!force) { boolean fileExists = false; if (keyFile.exists()) { System.err.println(keyFile + " exists"); fileExists = true; } if (certFile.exists()) { System.err.println(certFile + " exists"); fileExists = true; } if (certRequestFile.exists()) { System.err.println(certRequestFile + " exists"); fileExists = true; } if (fileExists) { exit("If you wish to overwrite, run the script again with -force.", 4); } } String password = null; if (!noPswd) { // Get password from user. int attempts = 0; boolean passOK = false; System.out.println(MESSAGE); while (attempts < 3) { password = Util.getPrivateInput("Enter PEM pass phrase: "); if (password.length() < 4) { System.out.println("Phrase is too short, needs to be at least 4 chars"); attempts++; continue; } String password2 = Util.getPrivateInput("Verifying password - Enter PEM pass phrase: "); if (password.compareTo(password2) == 0) { passOK = true; break; } else { System.out.println("Verify failure"); attempts++; } } if (!passOK) { exit("Too many attempts", 5); } } // Generate cert request. try { genCertificateRequest(cn, caEmail, password, keyFile, certFile, certRequestFile); } catch (Exception e) { System.err.println("Error generating cert request: " + e.getMessage()); if (debug) { e.printStackTrace(); } System.exit(6); } } private static void exit(String msg, int errorCode) { System.err.println("Error: " + msg); System.exit(errorCode); } private static void exit(String msg) { exit(msg, 1); } protected static void parseCmdLine(String[] args) { String hostName = null; String service = null; String orgBaseDN = null; String name = System.getProperty("user.name"); for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-version")) { System.err.println(Version.getVersion()); System.exit(1); } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("-?")) { exit(USAGE, 0); } else if (args[i].equalsIgnoreCase("-cn") || args[i].equalsIgnoreCase("-commonname")) { i++; if (i == args.length) { exit("-cn requires an argument"); } else { // common name specified name = args[i]; } } else if (args[i].equalsIgnoreCase("-service")) { i++; if (i == args.length) { exit("-service requires an argument"); } else { // user certificate directory specified service = args[i]; } } else if (args[i].equalsIgnoreCase("-host")) { i++; if (i == args.length) { exit("-host requires an argument"); } else { // host name specified hostName = args[i]; } } else if (args[i].equalsIgnoreCase("-dir")) { i++; if (i == args.length) { exit("-dir requires an argument"); } else { // user certificate directory specified dir = args[i]; } } else if (args[i].equalsIgnoreCase("-prefix")) { i++; if (i == args.length) { exit("-prefix requires an argument"); } else { prefix = args[i]; } } else if (args[i].equalsIgnoreCase("-nopw") || args[i].equalsIgnoreCase("-nodes") || args[i].equalsIgnoreCase("-nopassphrase")) { // no password noPswd = true; } else if (args[i].equalsIgnoreCase("-verbose")) { verbose = true; } else if (args[i].equalsIgnoreCase("-int") || args[i].equalsIgnoreCase("-interactive")) { // interactive mode interactive = true; } else if (args[i].equalsIgnoreCase("-force")) { // overwrite existing credentials force = true; } else if (args[i].equalsIgnoreCase("-debug")) { // overwrite existing credentials debug = true; } else if (args[i].equalsIgnoreCase("-caEmail")) { i++; if (i == args.length) { exit("-caEmail requires an argument"); } else { caEmail = args[i]; } } else if (args[i].equalsIgnoreCase("-orgBaseDN")) { i++; if (i == args.length) { exit("-orgBaseDN requires an argument"); } else { orgBaseDN = args[i]; } } else { exit("argument #" + (i+1) + "(" + args[i] + ") : unknown"); } } if (orgBaseDN == null) { CoGProperties props = CoGProperties.getDefault(); orgBaseDN = props.getProperty("orgBaseDN"); if (orgBaseDN == null) { if (interactive) { orgBaseDN = getOrgName(); } else { // just a default orgBaseDN = "O=Grid"; } } } if (service != null) { if (hostName == null) { exit("-host required"); } else { cn = orgBaseDN + ", CN=" + service + "/" + hostName; noPswd = true; if (prefix == null) { prefix = service; } if (dir == null && ConfigUtil.getOS() == ConfigUtil.UNIX_OS) { dir = "/etc/grid-security/" + service; } } } else if (hostName != null) { cn = orgBaseDN + ", CN=host/" + hostName; noPswd = true; if (prefix == null) { prefix = "host"; } if (dir == null && ConfigUtil.getOS() == ConfigUtil.UNIX_OS) { dir = "/etc/grid-security"; } } else { cn = orgBaseDN + ", CN=" + name; if (prefix == null) { prefix = "user"; } } if (dir == null) { dir = System.getProperty("user.home") + File.separator + ".globus"; } } /** * Generates a encrypted private key and certificate request. */ static public void genCertificateRequest(String dname, String emailAddressOfCA, String password, File keyFile, File certFile, File certReqFile) throws Exception { String sigAlgName = "MD5WithRSA"; String keyAlgName = "RSA"; CertUtil.init(); X509Name name = new X509Name(dname); String certSubject = X509NameHelper.toString(name); System.out.println("Generating a 1024 bit RSA private key"); // Generate a new key pair. KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName); keygen.initialize(1024); KeyPair keyPair = keygen.genKeyPair(); PrivateKey privKey = keyPair.getPrivate(); PublicKey pubKey = keyPair.getPublic(); // Generate the certificate request. DERSet derSet = new DERSet(); PKCS10CertificationRequest request = new PKCS10CertificationRequest( sigAlgName, name, pubKey, derSet, privKey); // Save the certificate request to a .pem file. byte[] data = request.getEncoded(); byte[] encodedData = Base64.encode(data); PrintStream ps = null; try { ps = new PrintStream(new FileOutputStream(certReqFile)); boolean caEmail = false; if ((emailAddressOfCA != null) && (emailAddressOfCA.length() > 0)) { caEmail = true; ps.print("\n\n" + "Please mail the following certificate request to " + emailAddressOfCA); } else { ps.print("\n\n" + "Please send the following certificate request to the Certificate Authority (CA). Refer to CA instructions for details on to send the request."); } ps.print("\n\n" + "==================================================================\n" + "\n" + "Certificate Subject:\n" + "\n" + certSubject + "\n" + "\n" + "The above string is known as your user certificate subject, and it \n" + "uniquely identifies this user.\n" + "\n" + "To install this user certificate, please save this e-mail message\n" + "into the following file.\n" + "\n" + "\n" + certReqFile.getAbsolutePath() + "\n" + "\n" + "\n" + " You need not edit this message in any way. Simply \n" + " save this e-mail message to the file.\n" + "\n" + "\n" + "If you have any questions about the certificate contact\n" + "the Certificate Authority"); if (caEmail) { ps.print("at " + emailAddressOfCA); } ps.print("\n\n"); PEMUtils.writeBase64(ps, "-----BEGIN CERTIFICATE REQUEST-----", encodedData, "-----END CERTIFICATE REQUEST-----"); } finally { if (ps != null) { ps.close(); } } // Save private key to a .pem file. OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey); if (password != null) { key.encrypt(password); } // this will set the permissions correctly already key.writeTo(keyFile.getAbsolutePath()); // Create an empty cert file. certFile.createNewFile(); System.out.println("A private key and a certificate request has been generated with the subject:"); System.out.println(); System.out.println(certSubject); System.out.println(); System.out.println("The private key is stored in " + keyFile.getAbsolutePath()); System.out.println("The request is stored in " + certReqFile.getAbsolutePath()); } private static String getOrgName() { System.out.println("-----"); System.out.println("You are about to be asked to enter information that will be incorporated"); System.out.println("into your certificate request."); System.out.println("What you are about to enter is what is called a Distinguished Name or a DN."); System.out.println("Enter organization DN by entering individual component names and their values."); System.out.println("The component name can be one of: " + X509Name.DefaultLookUp.keySet()); System.out.println("-----"); StringBuffer orgName = new StringBuffer(); String component = null; while ( (component = getComponent()) != null ) { if (orgName.length() != 0) { orgName.append(", "); } orgName.append(component); } if (orgName.length() == 0) { exit("Invalid organization DN"); } return orgName.toString(); } private static String getComponent() { String component = null; while (true) { component = Util.getInput("Enter name component: "); if (component == null || component.trim().length() == 0) { return null; } component = component.trim(); if (X509Name.DefaultLookUp.get(component.toLowerCase()) == null) { System.out.println("Invalid component name"); } else { break; } } component = component.toUpperCase(); String value = Util.getInput("Enter '" + component + "' value: "); if (value == null || value.trim().length() == 0) { return null; } return component + "=" + value.trim(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/KeyStoreConvert.java000066400000000000000000000143211241116057200321170ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.tools; import org.globus.gsi.util.CertificateLoadUtil; import java.io.File; import java.io.IOException; import java.io.FileOutputStream; import java.security.PrivateKey; import java.security.KeyStore; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import org.globus.gsi.OpenSSLKey; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import org.globus.common.Version; import org.globus.common.CoGProperties; import org.globus.util.Util; public class KeyStoreConvert { public static final String DEFAULT_ALIAS = "globus"; public static final String DEFAULT_PASSWORD = "globus"; public static final String DEFAULT_KEYSTORE_FILE = "globus.jks"; private static final String message = "\n" + "Syntax: java KeyStoreConvert [options]\n" + " java KeyStoreConvert -help\n\n" + "\tConverts Globus credentials (user key and certificate) into \n" + "\tJava keystore format (JKS format supported by Sun).\n\n" + "\tOptions\n" + "\t-help | -usage\n" + "\t\tDisplays usage.\n" + "\t-version\n" + "\t\tDisplays version.\n" + "\t-debug\n" + "\t\tEnables extra debug output.\n" + "\t-cert \n" + "\t\tNon-standard location of user certificate.\n" + "\t-key \n" + "\t\tNon-standard location of user key.\n" + "\t-alias \n" + "\t\tKeystore alias entry. Defaults to '" +DEFAULT_ALIAS + "'\n" + "\t-password \n" + "\t\tKeystore password. Defaults to '" +DEFAULT_PASSWORD + "'\n" + "\t-out \n" + "\t\tLocation of the Java keystore file. Defaults to\n" + "\t\t'" + DEFAULT_KEYSTORE_FILE + "'\n\n"; public static void main(String args[]) { CoGProperties props = CoGProperties.getDefault(); boolean error = false; boolean debug = false; String alias = DEFAULT_ALIAS; String password = DEFAULT_PASSWORD; String keyFile = props.getUserKeyFile(); String certFile = props.getUserCertFile(); String keyStoreFile = DEFAULT_KEYSTORE_FILE; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-debug")) { debug = true; } else if (args[i].equalsIgnoreCase("-out")) { keyStoreFile = args[++i]; } else if (args[i].equalsIgnoreCase("-key")) { keyFile = args[++i]; } else if (args[i].equalsIgnoreCase("-cert")) { certFile = args[++i]; } else if (args[i].equalsIgnoreCase("-alias")) { alias = args[++i]; } else if (args[i].equalsIgnoreCase("-pwd") || args[i].equalsIgnoreCase("-password")) { password = args[++i]; } else if (args[i].equalsIgnoreCase("-version")) { System.err.println(Version.getVersion()); System.exit(1); } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-usage")) { System.err.println(message); System.exit(1); } else { System.err.println("Error: Argument not recognized: " + args[i]); error = true; } } if (error) return; if (keyStoreFile == null) { System.err.println("Error: Java key store output file is not specified."); return; } if (debug) { System.out.println("### Current settings ###"); System.out.println(" Certificate file : " + certFile); System.out.println(" SSLeay key file : " + keyFile); System.out.println(" Java keystore file : " + keyStoreFile); System.out.println(" Key entry Alias : " + alias); System.out.println(" Java keystore password : " + password); } File f = new File(keyStoreFile); if (f.exists()) { System.err.println("Error: Output file (" + keyStoreFile + ") already exists."); return; } int rs = createKeyStore(certFile, keyFile, alias, password, keyStoreFile, debug); // Workaround to fix JNI bug (noticeable on some RedHat 6.1 and 7.1 systems) // for a description of the bug see http://java.sun.com/j2se/1.3/relnotes.html // and there grep for "ERROR REPORT" // gavin McCance System.exit(rs); } private static int createKeyStore(String certFile, String keyFile, String alias, String password, String keyStoreFile, boolean debug) { X509Certificate [] certs = new X509Certificate[1]; PrivateKey key = null; try { certs[0] = CertificateLoadUtil.loadCertificate(certFile); } catch(Exception e) { System.err.println("Failed to load certificate: " + e.getMessage()); return -1; } try { OpenSSLKey sslkey = new BouncyCastleOpenSSLKey(keyFile); if (sslkey.isEncrypted()) { String pwd = Util.getPrivateInput("Enter pass phrase: "); if (pwd == null) { // user canceled return -2; } sslkey.decrypt(pwd); } key = sslkey.getPrivateKey(); } catch(IOException e) { System.err.println("Failed to load key: " + e.getMessage()); return -1; } catch(GeneralSecurityException e) { System.err.println("Error: Wrong pass phrase"); if (debug) { e.printStackTrace(); } return -1; } System.out.println("Creating Java keystore..."); FileOutputStream out = null; try { KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, null); // this takes a while for some reason ks.setKeyEntry(alias, key, password.toCharArray(), certs); out = new FileOutputStream(keyStoreFile); ks.store(out, password.toCharArray()); } catch(Exception e) { System.err.println("Failed to create Java key store: " + e.getMessage()); return -1; } finally { if (out != null) { try { out.close(); } catch(IOException ee) {} } } System.out.println("Java keystore file (" + keyStoreFile + ") successfully created."); return 0; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/ProxyDestroy.java000066400000000000000000000044111241116057200315030ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.tools; import java.io.File; import org.globus.common.CoGProperties; import org.globus.util.Util; /** Destroys a proxy file. *
     * Syntax: java ProxyDestroy [-dryrun][-default] [file1...]
     *         java ProxyDestroy -help\n
     * Options
      * -help | -usage
      *     Displays usage
      * -dryrun
      *     Prints what files would have been destroyed
      * file1 file2 ...
      *     Destroys files listed
     *
    */ public class ProxyDestroy { private static final String message = "\n" + "Syntax: java ProxyDestroy [-dryrun] [file1...]\n" + " java ProxyDestroy -help\n\n" + "\tOptions\n" + "\t-help | -usage\n" + "\t\tDisplays usage\n" + "\t-dryrun\n" + "\t\tPrints what files would have been destroyed\n" + "\tfile1 file2 ...\n" + "\t\tDestroys files listed\n\n"; public static void main(String args[]) { boolean dryrun = false; boolean error = false; boolean debug = false; File file = null; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-dryrun")) { dryrun = true; } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-usage")) { System.err.println(message); System.exit(1); } else { file = new File(args[i]); if (dryrun) { System.out.println("Would remove " + file.getAbsolutePath()); continue; } Util.destroy(file); } } String fn = CoGProperties.getDefault().getProxyFile(); if (fn == null) return ; file = new File(fn); if (dryrun) { System.out.println("Would remove " + file.getAbsolutePath()); return; } Util.destroy(file); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/ProxyInfo.java000066400000000000000000000223261241116057200307520ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.tools; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.util.ProxyCertificateUtil; import org.globus.gsi.GSIConstants; import org.globus.gsi.CertUtil; import org.globus.gsi.GlobusCredential; import org.globus.util.Util; import org.globus.common.CoGProperties; import org.globus.common.Version; import java.security.cert.X509Certificate; /** Retruns information about the proxy. *
     * Syntax: java ProxyInfo [options]
     *         java ProxyInfo -help
      * Options
      * -help | -usage
      *     Displays usage
      * -f  | -file 
      *     Non-standard location of proxy
      * [printoptions]
      *     Prints information about proxy
      * -exists [options] | -e [options]
      *     Returns 0 if valid proxy exists, 1 otherwise
      * -globus
      *     Prints information in globus format
      * [printoptions]
      *     -subject              Distinguished name (DN) of subject
      *     -issuer               DN of issuer (certificate signer)
      *     -type                 Type of proxy (full or limited)
      *     -timeleft             Time (in seconds) until proxy expires
      *     -strength             Key size (in bits)
      *     -all                  All above options in a human readable format
      "
      * [options to -exists]      (if none are given, H = B = 0 are assumed)
      *     -hours H       (-h)   time requirement for proxy to be valid
      *     -bits  B       (-b)   strength requirement for proxy to be valid
      *
    */ public class ProxyInfo { private static final int SUBJECT = 2; private static final int ISSUER = 4; private static final int TYPE = 8; private static final int TIME = 16; private static final int STRENGTH = 32; private static final int TEXT = 64; private static final int IDENTITY = 128; private static final int PATH = 256; private static final int PATH_LENGTH = 512; private static final String message = "\n" + "Syntax: java ProxyInfo [options]\n" + " java ProxyInfo -help\n\n" + "\tOptions:\n" + "\t-help | usage\n" + "\t\tDisplays usage.\n" + "\t-file (-f)\n" + "\t\tNon-standard location of proxy.\n" + "\t[printoptions]\n" + "\t\tPrints information about proxy.\n" + "\t-exists [options] (-e) \n" + "\t\tReturns 0 if valid proxy exists, 1 otherwise.\n" + "\t-globus \n" + "\t\tPrints information in globus format\n\n" + "\t[printoptions]\n" + "\t-subject\n" + "\t\tDistinguished name (DN) of subject.\n" + "\t-issuer\n" + "\t\tDN of issuer (certificate signer).\n" + "\t-identity \n" + "\t\tDN of the identity represented by the proxy.\n" + "\t-type \n" + "\t\tType of proxy.\n" + "\t-timeleft\n" + "\t\tTime (in seconds) until proxy expires.\n" + "\t-strength\n" + "\t\tKey size (in bits)\n " + "\t-all\n" + "\t\tAll above options in a human readable format.\n" + "\t-text\n" + "\t\tAll of the certificate.\n" + "\t-path\n" + "\t\tPathname of proxy file.\n" + "\n" + "\t[options to -exists] (if none are given, H = B = 0 are assumed)\n" + "\t-hours H (-h) \n" + "\t\ttime requirement for proxy to be valid.\n" + "\t-bits B (-b) \n" + "\t\tstrength requirement for proxy to be valid\n" + "\t-length\n" + "\t\tpath length of the proxy\n\n"; public static void main(String args[]) { String file = null; int options = 0; int bits = 0; int hours = 0; boolean globusStyle = false; boolean exists = false; boolean debug = false; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-f") || args[i].equalsIgnoreCase("-file")) { if (i+1 >= args.length) { error("-file argument missing"); } file = args[++i]; } else if (args[i].equalsIgnoreCase("-subject")) { options |= SUBJECT; } else if (args[i].equalsIgnoreCase("-issuer")) { options |= ISSUER; } else if (args[i].equalsIgnoreCase("-identity")) { options |= IDENTITY; } else if (args[i].equalsIgnoreCase("-type")) { options |= TYPE; } else if (args[i].equalsIgnoreCase("-timeleft")) { options |= TIME; } else if (args[i].equalsIgnoreCase("-strength")) { options |= STRENGTH; } else if (args[i].equalsIgnoreCase("-text")) { options |= TEXT; } else if (args[i].equalsIgnoreCase("-path")) { options |= PATH; } else if (args[i].equalsIgnoreCase("-length")) { options |= PATH_LENGTH; } else if (args[i].equalsIgnoreCase("-all")) { options |= Integer.MAX_VALUE; options ^= TEXT; } else if (args[i].equalsIgnoreCase("-globus")) { globusStyle = true; } else if (args[i].equalsIgnoreCase("-exists")) { exists = true; } else if (args[i].equalsIgnoreCase("-bits")) { if (i+1 >= args.length) { error("-bits argument missing"); } bits = Integer.parseInt(args[++i]); } else if (args[i].equalsIgnoreCase("-hours")) { if (i+1 >= args.length) { error("-hours argument missing"); } hours = Integer.parseInt(args[++i]); } else if (args[i].equalsIgnoreCase("-version")) { System.err.println(Version.getVersion()); System.exit(1); } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-usage")) { System.err.println(message); System.exit(1); } else { error("Argument not recognized : " + args[i]); break; } } GlobusCredential proxy = null; try { if (file == null) { file = CoGProperties.getDefault().getProxyFile(); } proxy = new GlobusCredential(file); } catch(Exception e) { System.err.println("Unable to load the user proxy : " + e.getMessage()); System.exit(1); } if (exists) { if (bits > 0 && proxy.getStrength() < bits) System.exit(1); if (hours > 0 && (proxy.getTimeLeft()/3600) < hours) System.exit(1); System.exit(0); } if (options == 0) { options |= Integer.MAX_VALUE; options ^= TEXT; options ^= PATH; } if ((options & SUBJECT) != 0) { String dn = (globusStyle) ? CertificateUtil.toGlobusID(proxy.getCertificateChain()[0].getSubjectDN()) : proxy.getSubject(); System.out.println("subject : " + dn); } if ((options & ISSUER) != 0) { String dn = (globusStyle) ? CertificateUtil.toGlobusID(proxy.getCertificateChain()[0].getIssuerDN()) : proxy.getIssuer(); System.out.println("issuer : " + dn); } if ((options & IDENTITY) != 0) { String dn = null; if (globusStyle) { dn = proxy.getIdentity(); } else { X509Certificate cert = proxy.getIdentityCertificate(); dn = (cert == null) ? "failed to determine certificate identity" : cert.getSubjectDN().toString(); } System.out.println("identity : " + dn); } if ((options & TYPE) != 0) { GSIConstants.CertificateType type = GSIConstants.CertificateType.get(proxy.getProxyType()); String typeStr = (type == GSIConstants.CertificateType.UNDEFINED) ? "failed to determine certificate type" : ProxyCertificateUtil.getProxyTypeAsString(type); System.out.println("type : " + typeStr); } if ((options & STRENGTH) != 0) { System.out.println("strength : " + proxy.getStrength() + " bits"); } if ((options & PATH) != 0) { System.out.println("path : " + file); } if ((options & TIME) != 0) { String tm = (globusStyle) ? formatTimeSecGlobus(proxy.getTimeLeft()) : Util.formatTimeSec(proxy.getTimeLeft()); System.out.println("timeleft : " + tm); } if ((options & TEXT) != 0) { System.out.println(proxy.getCertificateChain()[0]); } if ((options & PATH_LENGTH) != 0) { int pathLength = proxy.getPathConstraint(); if (pathLength == Integer.MAX_VALUE) { System.out.println("path length: infinity"); } else { System.out.println("path length: " + pathLength); } } } private static void error(String error) { System.err.println("Error: " + error); System.err.println(); System.err.println("Usage: java ProxyInfo [-help][-f proxyfile][-subject]..."); System.err.println(); System.err.println("Use -help to display full usage"); System.exit(1); } private static String formatTimeSecGlobus(long time) { StringBuffer str = new StringBuffer(); long tt; tt = (time / 3600); if (tt == 0) { str.append("00"); } else { if (tt < 10) str.append("0"); str.append(tt); time -= tt*3600; } str.append(":"); tt = (time / 60); if (tt == 0) { str.append("00"); } else { if (tt < 10) str.append("0"); str.append(tt); time -= tt*60; } str.append(":"); if (tt == 0) { str.append("00"); } else { if (time < 10) str.append("0"); str.append(time); } return str.toString(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/ProxyInit.java000066400000000000000000000572421241116057200307670ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.tools; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.util.ProxyCertificateUtil; import org.globus.gsi.trustmanager.X509ProxyCertPathValidator; import org.globus.gsi.stores.ResourceSigningPolicyStore; import org.globus.gsi.stores.Stores; import org.globus.gsi.X509ProxyCertPathParameters; import org.globus.gsi.provider.GlobusProvider; import java.security.Security; import java.util.HashMap; import java.util.Map; import java.security.cert.CertStore; import java.security.KeyStore; import org.globus.gsi.X509ExtensionSet; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPath; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.EOFException; import java.io.File; import org.globus.common.CoGProperties; import org.globus.common.Version; import org.globus.gsi.OpenSSLKey; import org.globus.gsi.CertUtil; import org.globus.gsi.GlobusCredential; import org.globus.gsi.GSIConstants; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import org.globus.gsi.bc.BouncyCastleCertProcessingFactory; import org.globus.gsi.proxy.ext.ProxyPolicy; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.globus.gsi.proxy.ext.ProxyCertInfoExtension; import org.globus.gsi.proxy.ext.GlobusProxyCertInfoExtension; import org.globus.gsi.proxy.ProxyPolicyHandler; import org.globus.util.Util; /* ########################################################################### * This is a command-line tool and was specifically designed to be used as so. * Do not use it as a library. * ######################################################################## */ /** * Initializes/creates a new globus proxy. This is a command-line tool. Please * do not use it as a library. */ public abstract class ProxyInit { static { Security.addProvider(new GlobusProvider()); } public static final String GENERIC_POLICY_OID = "1.3.6.1.4.1.3536.1.1.1.8"; private static final String message = "\n" + "Syntax: java ProxyInit [options]\n" + " java ProxyInit -help\n\n" + " Options:\n" + " -help | -usage\t\tDisplays usage.\n" + " -version\t\t\tDisplays version.\n" + " -debug\t\t\tEnables extra debug output.\n" + " -verify\t\t\tPerforms proxy verification tests (default).\n" + " -pwstdin\t\t\tAllows passphrase from stdin.\n" + " -noverify\t\t\tDisables proxy verification tests.\n" + " -quiet | -q\t\t\tQuiet mode, minimal output\n" + " -limited\t\t\tCreates a limited proxy.\n" + " -independent\t\tCreates a independent globus proxy.\n" + " -old\t\t\tCreates a legacy globus proxy.\n" + " -valid \t\tProxy is valid for S seconds (default:12 " + "hours)\n" + " -valid \tProxy is valid for H hours and M \n" + " \tminutes. (default: 12 hours)\n" + " -hours \t\tProxy is valid for H hours (default:12).\n" + " -bits \t\tNumber of bits in key {512|1024|2048|4096}.\n" + " -globus\t\t\tPrints user identity in globus format.\n" + " -policy \tFile containing policy to store in the\n" + " \tProxyCertInfo extension\n" + " -pl \t\t\tOID string for the policy language.\n" + " -policy-language \tused in the policy file.\n" + " -path-length \t\tAllow a chain of at most l proxies to be \n" + " \t\tgenerated from this one\n" + " -cert \t\tNon-standard location of user certificate\n" + " -key \t\tNon-standard location of user key\n" + " -out \t\tNon-standard location of new proxy cert.\n" + " -pkcs11\t\t\tEnables the PKCS11 support module. The\n" + " \t\t\t-cert and -key arguments are used as labels\n" + " \t\t\tto find the credentials on the device.\n" + " -rfc\t\t\tCreates RFC 3820 compliant proxy. (Default)\n" + " -draft\t\t\tCreates RFC draft compliant proxy\n"; protected X509Certificate[] certificates; protected int bits = 512; protected int lifetime = 3600 * 12; protected ProxyCertInfo proxyCertInfo = null; protected GSIConstants.CertificateType proxyType; protected boolean quiet = false; protected boolean debug = false; protected boolean stdin = false; protected GlobusCredential proxy = null; public abstract void init(String [] args); public abstract void loadCertificates(String args); public abstract void loadKey(String arg); public abstract void sign(); public X509Certificate getCertificate() { return this.certificates[0]; } public void dispose() { } // verifies the proxy credential public void verify() throws Exception { Map handlers = null; if (proxyCertInfo != null) { String oid = proxyCertInfo.getProxyPolicy().getPolicyLanguage().getId(); handlers = new HashMap(); handlers.put(oid, new ProxyPolicyHandler() { public void validate(ProxyCertInfo proxyCertInfo, CertPath certPath, int index) throws CertPathValidatorException { // ignore policy - this is just for proxy init case System.out.println("Proxy verify: Ignoring proxy policy"); if (debug) { String policy = new String(proxyCertInfo.getProxyPolicy().getPolicy()); System.out.println("Policy:"); System.out.println(policy); } } }); } KeyStore keyStore = Stores.getDefaultTrustStore(); CertStore crlStore = Stores.getDefaultCRLStore(); ResourceSigningPolicyStore sigPolStore = Stores.getDefaultSigningPolicyStore(); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, crlStore, sigPolStore, false, handlers); X509ProxyCertPathValidator validator = new X509ProxyCertPathValidator(); validator.engineValidate(CertificateUtil.getCertPath(proxy.getCertificateChain()), parameters); } public void setBits(int bits) { this.bits = bits; } public void setLifetime(int lifetime) { this.lifetime = lifetime; } /** * @param proxyType * @deprecated */ public void setProxyType(int proxyType) { this.proxyType = GSIConstants.CertificateType.get(proxyType); } public void setProxyType(GSIConstants.CertificateType proxyType) { this.proxyType = proxyType; } public void setProxyCertInfo(ProxyCertInfo proxyCertInfo) { this.proxyCertInfo = proxyCertInfo; } public void setDebug(boolean debug) { this.debug = debug; } public void setQuiet(boolean quiet) { this.quiet = quiet; } public void setStdin(boolean stdin) { this.stdin = stdin; } public void createProxy(String cert, String key, boolean verify, boolean globusStyle, String proxyFile) { init(new String [] {cert, key}); loadCertificates(cert); if (!quiet) { String dn = null; if (globusStyle) { dn = CertificateUtil.toGlobusID(getCertificate().getSubjectDN()); } else { dn = getCertificate().getSubjectDN().getName(); } System.out.println("Your identity: " + dn); } loadKey(key); if (debug) { System.out.println("Using " + bits + " bits for private key"); } if (!quiet) { System.out.println("Creating proxy, please wait..."); } sign(); if (verify) { try { verify(); System.out.println("Proxy verify OK"); } catch(Exception e) { System.out.println("Proxy verify failed: " + e.getMessage()); if (debug) { e.printStackTrace(); } System.exit(-1); } } if (debug) { System.out.println("Saving proxy to: " + proxyFile); } if (!quiet) { System.out.println("Your proxy is valid until " + proxy.getCertificateChain()[0].getNotAfter()); } OutputStream out = null; try { File file = Util.createFile(proxyFile); // set read only permissions if (!Util.setOwnerAccessOnly(proxyFile)) { System.err.println("Warning: Please check file permissions for your proxy file."); } out = new FileOutputStream(file); // write the contents proxy.save(out); } catch (Exception e) { System.err.println("Failed to save proxy to a file: " + e.getMessage()); System.exit(-1); } finally { if (out != null) { try { out.close(); } catch(Exception e) {} } } dispose(); } public static void main(String args[]) { int bits = 512; int lifetime = 3600 * 12; boolean debug = false; boolean quiet = false; boolean verify = true; boolean pkcs11 = false; boolean limited = false; int pathLen = -1; GSIConstants.CertificateType proxyType = GSIConstants.CertificateType.UNDEFINED; // 0 is old, 1 is Globus (draft compliant) oid, 2 is rfc oid int oid = 2; String policyLanguage = null; String policyFile = null; boolean stdin = false; boolean independent = false; CoGProperties properties = CoGProperties.getDefault(); boolean globusStyle = false; String proxyFile = properties.getProxyFile(); String keyFile = null; String certFile = null; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-hours")) { if (i+1 >= args.length) { argError("-hours argument missing"); } lifetime = 3600 * Integer.parseInt(args[++i]); } else if (args[i].equalsIgnoreCase("-bits")) { if (i+1 >= args.length) { argError("-bits argument missing"); } bits = Integer.parseInt(args[++i]); } else if (args[i].equalsIgnoreCase("-pwstdin")) { stdin = true; } else if (args[i].equalsIgnoreCase("-limited")) { limited = true; } else if (args[i].equalsIgnoreCase("-independent")) { independent = true; } else if (args[i].equalsIgnoreCase("-old")) { oid = 0; } else if (args[i].equalsIgnoreCase("-path-length")) { if (i+1 >= args.length) { argError("-path-length argument missing"); } pathLen = Integer.parseInt(args[++i]); } else if (args[i].equalsIgnoreCase("-pl") || args[i].equalsIgnoreCase("-policy-language")) { if (i+1 >= args.length) { argError("-policy-language argument missing"); } policyLanguage = args[++i]; } else if (args[i].equalsIgnoreCase("-policy")) { if (i+1 >= args.length) { argError("-policy argument missing"); } policyFile = args[++i]; } else if (args[i].equalsIgnoreCase("-debug")) { debug = true; } else if (args[i].equalsIgnoreCase("-verify")) { verify = true; } else if (args[i].equalsIgnoreCase("-noverify")) { verify = false; } else if (args[i].equalsIgnoreCase("-out")) { if (i+1 >= args.length) { argError("-out argument missing"); } proxyFile = args[++i]; } else if (args[i].equals("-q") || args[i].equalsIgnoreCase("-quiet")) { quiet = true; } else if (args[i].equalsIgnoreCase("-globus")) { globusStyle = true; } else if (args[i].equalsIgnoreCase("-pkcs11")) { pkcs11 = true; } else if (args[i].equalsIgnoreCase("-key")) { if (i+1 >= args.length) { argError("-key argument missing"); } keyFile = args[++i]; } else if (args[i].equalsIgnoreCase("-cert")) { if (i+1 >= args.length) { argError("-cert argument missing"); } certFile = args[++i]; } else if (args[i].equalsIgnoreCase("-valid")) { String validity = args[++i]; int delimiterIndex = validity.indexOf(":"); if (delimiterIndex == -1) { lifetime = Integer.parseInt(validity); } else { String hours = validity.substring(0, delimiterIndex); String minutes = validity.substring(delimiterIndex+1, validity.length()); int hoursInt = Integer.parseInt(hours); int minsInt = Integer.parseInt(minutes); lifetime = (minsInt * 60) + (hoursInt * 60 * 60); } } else if (args[i].equalsIgnoreCase("-version")) { System.err.println(Version.getVersion()); System.exit(1); } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-usage")) { System.err.println(message); System.exit(1); } else if (args[i].equalsIgnoreCase("-draft")) { oid = 1; } else if (args[i].equalsIgnoreCase("-rfc")) { oid = 2; } else { argError("Argument not recognized: " + args[i]); break; } } if (proxyFile == null) { error("Proxy file not specified."); } boolean restricted = (policyFile != null || policyLanguage != null); if (independent) { if (oid == 0) { error("-old and -independent are exclusive"); } if (limited) { error("-limited and -independent are exclusive"); } if (restricted) { error("-indepedent and -policy or -pl are exclusive"); } if (oid == 1) { proxyType = GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY; } else { // oid has to be 2 proxyType = GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY; } } if (restricted) { if (oid == 0) { error("-old and -policy or -pl are exclusive"); } if (limited) { error("-limited and -policy or -pl are exclusive"); } // XXX: check if proxyType == -1? if (oid == 1) { proxyType = GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY; } else { // oid has to be 2 proxyType = GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY; } } if (proxyType == GSIConstants.CertificateType.UNDEFINED) { if (oid == 1) { proxyType = (limited) ? GSIConstants.CertificateType.GSI_3_LIMITED_PROXY : GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY; } else if (oid == 2) { proxyType = (limited) ? GSIConstants.CertificateType.GSI_4_LIMITED_PROXY : GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY; } else { proxyType = (limited) ? GSIConstants.CertificateType.GSI_2_LIMITED_PROXY : GSIConstants.CertificateType.GSI_2_PROXY; } } ProxyInit init = null; if (pkcs11) { if (keyFile == null) { if (certFile == null) { keyFile = certFile = properties.getDefaultPKCS11Handle(); } else { keyFile = certFile; } } else { if (certFile == null) { certFile = keyFile; } } try { Class iClass = Class.forName("org.globus.pkcs11.tools.PKCS11ProxyInit"); init = (ProxyInit)iClass.newInstance(); } catch (ClassNotFoundException e) { System.err.println("Error: Failed to load PKCS11 module."); System.exit(-1); } catch (InstantiationException e) { System.err.println("Error: Failed to instantiate PKCS11 module: " + e.getMessage()); System.exit(-1); } catch (IllegalAccessException e) { System.err.println("Error: Failed to initialize PKCS11 module: " + e.getMessage()); System.exit(-1); } } else { if (keyFile == null) { keyFile = properties.getUserKeyFile(); } if (certFile == null) { certFile = properties.getUserCertFile(); } init = new DefaultProxyInit(); } if (debug) { System.err.println("Files used: "); System.err.println(" proxy : " + ((proxyFile == null) ? "none" : proxyFile)); System.err.println(" user key : " + ((keyFile == null) ? "none" : keyFile)); System.err.println(" user cert : " + ((certFile == null) ? "none" : certFile)); } CertUtil.init(); ProxyCertInfo proxyCertInfo = null; if ((ProxyCertificateUtil.isGsi3Proxy(proxyType)) || (ProxyCertificateUtil.isGsi4Proxy(proxyType))) { ProxyPolicy policy = null; if (ProxyCertificateUtil.isLimitedProxy(proxyType)) { policy = new ProxyPolicy(ProxyPolicy.LIMITED); } else if (ProxyCertificateUtil.isIndependentProxy(proxyType)) { policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT); } else if (ProxyCertificateUtil.isImpersonationProxy(proxyType)) { // since limited has already been checked, this should work. policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION); } else if ((proxyType == GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY) || (proxyType == GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY)) { if (policyFile == null) { error("Policy file required."); } if (policyLanguage == null) { policyLanguage = GENERIC_POLICY_OID; } byte [] policyData = null; try { policyData = readPolicyFile(policyFile); } catch (IOException e) { error("Failed to load policy file: " + e.getMessage()); } policy = new ProxyPolicy(policyLanguage, policyData); } else { throw new IllegalArgumentException("Invalid proxyType"); } if (pathLen >= 0) { proxyCertInfo = new ProxyCertInfo(pathLen, policy); } else { proxyCertInfo = new ProxyCertInfo(policy); } } init.setBits(bits); init.setLifetime(lifetime); init.setProxyType(proxyType); init.setProxyCertInfo(proxyCertInfo); init.setDebug(debug); init.setQuiet(quiet); init.setStdin(stdin); init.createProxy(certFile, keyFile, verify, globusStyle, proxyFile); } private static void argError(String error) { System.err.println("Error: " + error); System.err.println(); System.err.println("Usage: java ProxyInit [-help][-limited][-hours H] ..."); System.err.println(); System.err.println("Use -help to display full usage"); System.exit(1); } protected static void error(String error) { System.err.println("Error: " + error); System.exit(1); } private static byte[] readPolicyFile(String file) throws IOException { File f = new File(file); FileInputStream in = new FileInputStream(f); byte [] data = new byte[(int)f.length()]; int left = data.length; int off = 0; int bytes = 0; try { while (left > 0) { bytes = in.read(data, off, left); if (bytes == -1) { throw new EOFException(); } off += bytes; left -= bytes; } } finally { if (in != null) { in.close(); } } return data; } } class DefaultProxyInit extends ProxyInit { private PrivateKey userKey = null; public void init(String [] args) { verify(args[1], "User key"); verify(args[0], "User certificate"); } public void verify() throws Exception { RSAPublicKey pkey = (RSAPublicKey)getCertificate().getPublicKey(); RSAPrivateKey prkey = (RSAPrivateKey)userKey; if (!pkey.getModulus().equals(prkey.getModulus())) { throw new Exception("Certificate and private key specified do not match"); } super.verify(); } private static void verify(String file, String msg) { if (file == null) error(msg + " not specified."); File f = new File(file); if (!f.exists() || f.isDirectory()) error(msg + " not found."); } public void loadCertificates(String arg) { try { certificates = CertificateLoadUtil.loadCertificates(arg); } catch(IOException e) { System.err.println("Error: Failed to load cert: " + arg); System.exit(-1); } catch(GeneralSecurityException e) { System.err.println("Error: Unable to load user certificate: " + e.getMessage()); System.exit(-1); } } public void loadKey(String arg) { try { OpenSSLKey key = new BouncyCastleOpenSSLKey(arg); if (key.isEncrypted()) { String prompt = (quiet) ? "Enter GRID pass phrase: " : "Enter GRID pass phrase for this identity: "; String pwd = (stdin) ? Util.getInput(prompt) : Util.getPrivateInput(prompt); if (pwd == null) { System.exit(1); } key.decrypt(pwd); } userKey = key.getPrivateKey(); } catch(IOException e) { System.err.println("Error: Failed to load key: " + arg); System.err.println("Error: " + e.getMessage()); System.exit(-1); } catch(GeneralSecurityException e) { System.err.println("Error: Wrong pass phrase"); System.err.println("Error: " + e.getMessage()); if (debug) { e.printStackTrace(); } System.exit(-1); } } public void sign() { try { BouncyCastleCertProcessingFactory factory = BouncyCastleCertProcessingFactory.getDefault(); X509ExtensionSet extSet = null; if (proxyCertInfo != null) { extSet = new X509ExtensionSet(); if (ProxyCertificateUtil.isGsi4Proxy(proxyType)) { // RFC compliant OID extSet.add(new ProxyCertInfoExtension(proxyCertInfo)); } else { // old OID extSet.add(new GlobusProxyCertInfoExtension(proxyCertInfo)); } } proxy = factory.createCredential(certificates, userKey, bits, lifetime, proxyType.getCode(), extSet); } catch (GeneralSecurityException e) { System.err.println("Failed to create a proxy: " + e.getMessage()); System.exit(-1); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/tools/package.html000066400000000000000000000004501241116057200304250ustar00rootroot00000000000000 Contains higher-level components which utilize the jGlobus library.

    Package Specification

    Related Documentation

    JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/000077500000000000000000000000001241116057200257625ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/CircularBuffer.java000066400000000000000000000045151241116057200315300ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; public class CircularBuffer { protected Object[] buf; protected int in = 0; protected int out= 0; protected int count= 0; protected int size; protected boolean interruptPut = false; protected boolean interruptGet = false; protected boolean closePut = false; public CircularBuffer(int size) { this.size = size; buf = new Object[size]; } public synchronized boolean isEmpty() { return (this.count == 0); } public synchronized boolean put(Object o) throws InterruptedException { if (this.interruptPut) { return false; } while (count==size) { wait(); if (this.interruptPut) { return false; } } buf[in] = o; ++count; in=(in+1) % size; notify(); return true; } public synchronized Object get() throws InterruptedException { if (this.interruptGet) { return null; } while (count==0) { if (this.closePut) { return null; } wait(); if (this.interruptGet) { return null; } } Object o =buf[out]; buf[out]=null; --count; out=(out+1) % size; notify(); return (o); } public synchronized void closePut() { this.closePut = true; notifyAll(); } public synchronized boolean isPutClosed() { return this.closePut; } public synchronized void interruptBoth() { this.interruptGet = true; this.interruptPut = true; notifyAll(); } public synchronized void interruptGet() { this.interruptGet = true; notifyAll(); } public synchronized void interruptPut() { this.interruptPut = true; notifyAll(); } public synchronized boolean isGetInterrupted() { return this.interruptGet; } public synchronized boolean isPutInterrupted() { return this.interruptPut; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/ClassLoaderUtils.java000066400000000000000000000112121241116057200320370ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import java.io.InputStream; /** * Various classloader utils. Extends the standard ways of loading classes or * resources with a fallback mechanism to the thread context classloader. */ public class ClassLoaderUtils { private static DummySecurityManager MANAGER = new DummySecurityManager(); private static class DummySecurityManager extends SecurityManager { public Class[] getClassContext() { return super.getClassContext(); } } /** * Returns the current execution stack as an array of classes. *

    * The length of the array is the number of methods on the execution stack. * The element at index 0 is the class of the currently * executing method, the element at index 1 is the class of * that method's caller, and so on. * * @return the execution stack. */ public static Class[] getClassContext() { return MANAGER.getClassContext(); } /** * Returns a class at specified depth of the current execution stack. * * @return the class at the specified depth of the current execution stack. * Migth return null if depth is out of range. */ public static Class getClassContextAt(int i) { Class[] classes = MANAGER.getClassContext(); if (classes != null && classes.length > i) { return classes[i]; } return null; } /** * Returns a classloader at specified depth of the current execution stack. * * @return the classloader at the specified depth of the current execution * stack. Migth return null if depth is out of range. */ public static ClassLoader getClassLoaderContextAt(int i) { Class[] classes = MANAGER.getClassContext(); if (classes != null && classes.length > i) { return classes[i].getClassLoader(); } return null; } /** * Gets an InputStream to a resource of a specified name. First, the * caller's classloader is used to load the resource and if it fails the * thread's context classloader is used to load the resource. */ public static InputStream getResourceAsStream(String name) { // try with caller classloader ClassLoader loader = getClassLoaderContextAt(3); InputStream in = (loader == null) ? null : loader.getResourceAsStream(name); if (in == null) { // try with context classloader if set & different ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); if (contextLoader != null && contextLoader != loader) { in = contextLoader.getResourceAsStream(name); } } return in; } /** * Loads a specified class. First, the caller's classloader is used to load * the class and if it fails the thread's context classloader is used to * load the specified class. */ public static Class forName(String name) throws ClassNotFoundException { // try with caller classloader ClassLoader loader = getClassLoaderContextAt(3); try { return Class.forName(name, true, loader); } catch (ClassNotFoundException e) { // try with context classloader if set & different ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); if (contextLoader == null || contextLoader == loader) { throw e; } else { return Class.forName(name, true, contextLoader); } } } public static Class loadClass(String className, Class callingClass) throws ClassNotFoundException { try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { return cl.loadClass(className); } } catch (ClassNotFoundException e) { // ignore } return loadClass2(className, callingClass); } private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } throw ex; } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/ConfigUtil.java000066400000000000000000000213451241116057200306750ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import java.io.IOException; import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; public class ConfigUtil { public static final int UNDEFINED_OS = -1; public static final int WINDOWS_OS = 0; public static final int UNIX_OS = 1; public static final int MAC_OS = 2; public static final int OTHER_OS = 3; private static int osType = UNDEFINED_OS; private static final String PROXY_NAME = "x509up_u"; private static final String SOLARIS_ID_EXEC = "/usr/xpg4/bin/id"; public static String globus_dir = null; static { globus_dir = System.getProperty("user.home") + File.separator + ".globus" + File.separator; } /** Returns default PKCS11 library name */ public static String discoverPKCS11LibName() { return "dspkcs"; // use the ibutton library as the default for now } /** Returns default location of user cert file */ public static String discoverUserCertLocation() { String location = null; location = globus_dir + "usercert.pem"; return location; } /** Returns default location of user key file */ public static String discoverUserKeyLocation() { String location = null; location = globus_dir + "userkey.pem"; return location; } /** * Tries to discover user proxy location. * If a UID system property is set, and running on a Unix machine it * returns /tmp/x509up_u${UID}. If any other machine then Unix, it returns * ${tempdir}/x509up_u${UID}, where tempdir is a platform-specific * temporary directory as indicated by the java.io.tmpdir system property. * If a UID system property is not set, the username will be used instead * of the UID. That is, it returns ${tempdir}/x509up_u_${username} */ public static String discoverProxyLocation() { String dir = null; if (getOS() == UNIX_OS) { dir = "/tmp/"; } else { String tmpDir = System.getProperty("java.io.tmpdir"); dir = (tmpDir == null) ? globus_dir : tmpDir; } String uid = System.getProperty("UID"); if (uid != null) { return getLocation(dir, PROXY_NAME + uid); } else if (getOS() == UNIX_OS) { try { return getLocation(dir, PROXY_NAME + getUID()); } catch (IOException e) { } } /* If all else fails use username */ String suffix = System.getProperty("user.name"); if (suffix != null) { suffix = suffix.toLowerCase(); } else { suffix = "nousername"; } return getLocation(dir, PROXY_NAME + "_" + suffix); } private static String getLocation(String dir, String file) { File f = new File(dir, file); return f.getAbsolutePath(); } /** * Returns the user id. The user id is obtained by executing 'id -u' * external program. *

    Note: * Under some circumstances, this function executes an external program; * thus, its behavior is influenced by environment variables such as the * caller's PATH and the environment variables that control dynamic * loading. Care should be used if calling this function from a program * that will be run as a Unix setuid program, or in any other manner in * which the owner of the Unix process does not completely control its * runtime environment. * * * @throws IOException if unable to determine the user id. * @return the user id */ public static String getUID() throws IOException { String exec = "id"; String osname = System.getProperty("os.name"); if (osname != null) { osname = osname.toLowerCase(); if ((osname.indexOf("solaris") != -1) || (osname.indexOf("sunos") != -1)) { if ((new File(SOLARIS_ID_EXEC).exists())) { exec = SOLARIS_ID_EXEC; } } else if (osname.indexOf("windows") != -1) { throw new IOException("Unable to determine the user id"); } } Runtime runTime = Runtime.getRuntime(); Process process = null; BufferedReader buffInReader = null; String s = null; StringBuffer output = new StringBuffer(); int exitValue = -1; try { process = runTime.exec(exec + " -u"); buffInReader = new BufferedReader ( new InputStreamReader(process.getInputStream()) ); while ((s = buffInReader.readLine()) != null) { output.append(s); } exitValue = process.waitFor(); } catch (Exception e) { throw new IOException("Unable to execute 'id -u'"); } finally { if (buffInReader != null) { try { buffInReader.close(); } catch (IOException e) {} } if (process != null) { try { process.getErrorStream().close(); } catch (IOException e) {} try { process.getOutputStream().close(); } catch (IOException e) {} } } if (exitValue != 0) { throw new IOException("Unable to perform 'id -u'"); } return output.toString().trim(); } /** * Discovers location of CA certificates directory. * First the ${user.home}/.globus/certificates directory is checked. * If the directory does not exist, and on a Unix machine, the * /etc/grid-security/certificates directory is checked next. * If that directory does not exist and GLOBUS_LOCATION * system property is set then the ${GLOBUS_LOCATION}/share/certificates * directory is checked. Otherwise, null is returned. * This indicates that the certificates directory could * not be found. */ public static String discoverCertDirLocation() { String location = null; location = getDir(globus_dir + "certificates"); if (location != null) return location; if (getOS() == UNIX_OS) { location = getDir( "/etc/grid-security/certificates"); if (location != null) return location; } String suffix = File.separator + "share" + File.separator + "certificates"; location = getDir(System.getProperty("GLOBUS_LOCATION") + suffix); if (location != null) return location; return null; } public static int getOS() { if (osType != UNDEFINED_OS) { return osType; } String osname = System.getProperty("os.name"); if (osname != null) { osname = osname.toLowerCase(); if (osname.indexOf("windows") != -1) { osType = WINDOWS_OS; } else if ( (osname.indexOf("solaris") != -1) || (osname.indexOf("sunos") != -1) || (osname.indexOf("linux") != -1) || (osname.indexOf("aix") != -1) || (osname.indexOf("hp-ux") != -1) || (osname.indexOf("compaq's digital unix") != -1) || (osname.indexOf("osf1") != -1) || (osname.indexOf("mac os x") != -1) || (osname.indexOf("netbsd") != -1) || (osname.indexOf("freebsd") != -1) || (osname.indexOf("irix") != -1) ) { osType = UNIX_OS; } else if (osname.indexOf("mac") != -1) { osType = MAC_OS; } else { osType = OTHER_OS; } } else { osType = OTHER_OS; } return osType; } private static String getDir(String directory) { if (directory == null) return null; File f = new File(directory); if (f.isDirectory() && f.canRead()) { return f.getAbsolutePath(); } else { return null; } } } GlobusPathMatchingResourcePatternResolver.java000066400000000000000000000232141241116057200370630ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/utilpackage org.globus.util; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Provides methods to resolve locationPatterns and return GlobusResource * objects which match those location patterns. Supports Ant-Style regular * expressions, where: * ** matches any number of directories * ? matches one character * * matches any number of characters * * Supports file:, classpath:, and relative paths. * Provides similar functionality to spring framework's PathMatchingResourcePatternResolver * * 3/2/2012 */ public class GlobusPathMatchingResourcePatternResolver { //Regex style pattern to match locations private Pattern locationPattern = null; /** * Path from root directory to the directory at the beginning of a classpath. * For example if a class was in a package org.globus.utils.MyClass.java, * which had an absolute path of /user/userName/project/resources/org/globus/utils/MyClass.java * the mainClassPath would be /user/userName/project/resources/ */ private String mainClassPath = ""; //Holds GlobusResource instances of all the paths which matched the locationPattern private Vector pathsMatchingLocationPattern = new Vector(); public GlobusPathMatchingResourcePatternResolver() { } /** * This method takes a location string and returns a GlobusResource of the * corresponding location. This method does not accept any patterns for the location string. * @param location An absolute or relative location in the style classpath:/folder/className.class, * file:/folder/fileName.ext, or folder/folder/fileName.ext * @return A GlobusResource type object of the corresponding location string. */ public GlobusResource getResource(String location) { GlobusResource returnResource; URL resourceURL; if (location.startsWith("classpath:")) { resourceURL = getClass().getClassLoader().getResource(location.replaceFirst("classpath:/", "")); returnResource = new GlobusResource(resourceURL.getPath()); } else if (location.startsWith("file:")) { returnResource = new GlobusResource(location.replaceFirst("file:", "")); } else returnResource = new GlobusResource(location); return returnResource; } /** * Finds all the resources that match the Ant-Style locationPattern * @param locationPattern Ant-Style location pattern which may be prefixed with * classpath:/, file:/, or describe a relative path. * @return An array of GlobusResource containing all resources whose locaiton match the locationPattern */ public GlobusResource[] getResources(String locationPattern) { String mainPath = ""; if (locationPattern.startsWith("classpath:")) { String pathUntilWildcard = getPathUntilWildcard(locationPattern.replaceFirst("classpath:/", ""), false); URL resourceURL = getClass().getClassLoader().getResource(pathUntilWildcard); this.mainClassPath = resourceURL.getPath(); this.locationPattern = Pattern.compile(antToRegexConverter(locationPattern.replaceFirst("classpath:/", "").replaceFirst(pathUntilWildcard, ""))); parseDirectoryStructure(new File(this.mainClassPath)); } else if (locationPattern.startsWith("file:")) { if ((locationPattern.replaceFirst("file:", "").compareTo(getPathUntilWildcard(locationPattern.replaceFirst("file:", ""), true))) == 0) {//Check to see if the pattern is not a pattern pathsMatchingLocationPattern.add(new GlobusResource(locationPattern.replaceFirst("file:", ""))); } else { try { URL resourceURL = new File(getPathUntilWildcard(locationPattern.replaceFirst("file:", ""), true)).toURL(); mainPath = resourceURL.getPath(); this.locationPattern = Pattern.compile(antToRegexConverter(locationPattern.replaceFirst("file:", ""))); parseDirectoryStructure(new File(mainPath)); } catch (MalformedURLException ex) { } } } else { mainPath = getPathUntilWildcard(locationPattern, true); this.locationPattern = Pattern.compile(antToRegexConverter(locationPattern)); parseDirectoryStructure(new File(mainPath)); } return pathsMatchingLocationPattern.toArray(new GlobusResource[0]); } /** * Converts an Ant-style pattern to a regex pattern by replacing (. with \\.), (? with .), * (** with .*), and (* with [^/]*). * @param antStyleLocationPattern An Ant-Stlye location pattern. * @return A regex style location pattern representation of the antStyleLocationPattern */ private String antToRegexConverter(String antStyleLocationPattern) { String regexStyleLocationPattern = antStyleLocationPattern.replace("\\", "/"); regexStyleLocationPattern = regexStyleLocationPattern.replaceAll("\\.", "\\\\."); // replace . with \\. regexStyleLocationPattern = regexStyleLocationPattern.replaceAll("//", "/");//Solution for known test cases with // issue at org.globus.gsi.proxy.ProxyPathValidatorTest line 536, Needs Review regexStyleLocationPattern = regexStyleLocationPattern.replace('?', '.'); // replace ? with . regexStyleLocationPattern = regexStyleLocationPattern.replaceAll("\\*", "[^/]*"); //replace all * with [^/]*, this will make ** become [^/]*[^/]* regexStyleLocationPattern = regexStyleLocationPattern.replaceAll("\\[\\^/\\]\\*\\[\\^/\\]\\*", ".*"); //now replace the .*.* with just .* regexStyleLocationPattern = "^" + this.mainClassPath + regexStyleLocationPattern + "$"; //add the beginning and end symbols, and mainClassPath, if the object is of the type classpath:/ return regexStyleLocationPattern; } /** * Returns a substring of the locationPattern from the beginning * to the first occurrence of * or ? * If this is unsuccessful, start at current directory ./ * @param locationPatternString The Ant-Style location pattern. * @return A substring of the locationPatternString from the beginning to the first occurrence of a wildcard character */ private String getPathUntilWildcard(String locationPatternString, boolean defaultToLocaldir) { String currentLocationPatternString; int locationPatternStringLength = locationPatternString.length(); //Find the first occurrence of * or ?, if none, set idx to locationPatternLength int startIndex, questionMarkIndex; if ((startIndex = locationPatternString.indexOf('*')) == -1) startIndex = locationPatternStringLength; if ((questionMarkIndex = locationPatternString.indexOf('?')) == -1) questionMarkIndex = locationPatternStringLength; currentLocationPatternString = locationPatternString.substring(0, Math.min(startIndex, questionMarkIndex)); if (defaultToLocaldir && !(new File(currentLocationPatternString).canRead())) currentLocationPatternString = "./"; return currentLocationPatternString; } /** * Recursive variant of parseFilesInDirectory. * @param currentDirectory The currentDirectory to explore. */ private void parseDirectoryStructure(File currentDirectory) { File[] directoryContents; if (currentDirectory.isDirectory()) { directoryContents = currentDirectory.listFiles(); //Get a list of the files and directories } else { directoryContents = new File[] { currentDirectory }; } if(directoryContents != null){ for (File currentFile : directoryContents) { if (currentFile.isFile()) { //We are only interested in files not directories String absolutePath = currentFile.getAbsolutePath().replace("\\", "/"); Matcher locationPatternMatcher = locationPattern.matcher(absolutePath); if (locationPatternMatcher.find()) { pathsMatchingLocationPattern.add(new GlobusResource(absolutePath)); } } else if (currentFile.isDirectory()) { parseDirectoryStructure(currentFile); } } } } /** * Compares every file's Absolute Path against the locationPattern, if they match * a GlobusResource is created with the file's Absolute Path and added to pathsMatchingLocationPattern. * @param currentDirectory The directory whose files to parse. */ private void parseFilesInDirectory(File currentDirectory) { File[] directoryContents = null; if (currentDirectory.isDirectory()) { directoryContents = currentDirectory.listFiles(); //Get a list of the files and directories } else { directoryContents = new File[1]; directoryContents[0] = currentDirectory; } String absolutePath = null; Matcher locationPatternMatcher = null; if(directoryContents != null){ for (File currentFile : directoryContents) { if (currentFile.isFile()) { //We are only interested in files not directories absolutePath = currentFile.getAbsolutePath(); locationPatternMatcher = locationPattern.matcher(absolutePath); if (locationPatternMatcher.find()) { pathsMatchingLocationPattern.add(new GlobusResource(absolutePath)); } } } } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/GlobusResource.java000066400000000000000000000070101241116057200315660ustar00rootroot00000000000000package org.globus.util; import java.io.File; import java.net.MalformedURLException; import java.io.InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.net.URI; import org.apache.commons.io.IOExceptionWithCause; /** * This class provides a way of managing file system resources * in a manner similar to the spring framework's Resource class. * * 3/2/2012 */ public class GlobusResource { //A file instance of the specified resourcePath private File resourceFile = null; //The path to the file private String resourcePath = null; /** * Creates a new instance of GlobusResource referencing the * specified resourcePath. * * @param resourcePath The path to the specified resource in the style * /directory/directory/fileName.ext */ public GlobusResource(String resourcePath) { this.resourcePath = resourcePath; this.resourceFile = new File(resourcePath); } /** * @return A string representation of the resource's URI */ public String toURI() { return resourceFile.toURI().toASCIIString(); } /** * @return A string representation of the resource's URL * @throws MalformedURLException */ public String toURL() throws MalformedURLException { String fileURLPathString = null; fileURLPathString = resourceFile.toURI().toURL().toString(); return fileURLPathString; } /** * @return The resource's URI(java.Net.URI) * @throws IOException */ public URI getURI() throws IOException { return resourceFile.toURI(); } /** * @return The resource's URL(java.Net.URL) * @throws MalformedURLException */ public URL getURL() throws MalformedURLException { return resourceFile.toURI().toURL(); } /** * @return A new java.io.File object referencing the resource's resourcePath * @throws IOException */ public File getFile() throws IOException { File duplicateFile = new File(this.resourceFile.getAbsolutePath()); return duplicateFile; } /** * @return True if the resource exists, and false if the resource does not exist */ public boolean exists() { return this.resourceFile.exists(); } /** * @return The time the resource was last modified * @throws IOException */ public long lastModified() throws IOException { return this.resourceFile.lastModified(); } /** * @return True if the resource is readable, false if the resource is not readable */ public boolean isReadable() { return this.resourceFile.canRead(); } /** * @return A new InputStream(java.io.InputStream) of the resource * @throws FileNotFoundException * @throws IOException */ public InputStream getInputStream() throws FileNotFoundException, IOException { InputStream fileInputStream = new FileInputStream(this.getFile()); return fileInputStream; } /** * @return The name of the resource in the style fileName.ext */ public String getFilename() { return this.resourcePath.substring(resourcePath.lastIndexOf("/") + 1, resourcePath.length()); } /** * @return A string representing resourcePath and URI of the resource */ @Override public String toString() { return String.format("resourcePath: %s\nURI: %s\n", this.resourcePath, this.toURI()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/GlobusURL.java000066400000000000000000000172131241116057200304470ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import java.net.MalformedURLException; import java.net.URL; /** * This class represents the URLs needed by various Globus services, * including: *

      *
    • GASS
    • *
    • GRAM
    • *
    • FTP
    • *
    • GSIFTP
    • *
    * * This class is not extended from URL since it is not intended to do stream * handling. Instead it is primarily for the parsing of Globus URLs and is * able to handle the extraction of user names and passwords from the URL * as well. It also can parse literal IPv6 addresses (as per RFC 2732). */ public class GlobusURL { protected String protocol = null; protected String host = null; protected String urlPath = null; protected String user = null; protected String pwd = null; protected String url = null; protected int port = -1; /** * Parses the url and extracts the url parts. * * @param url the url to parse. * @throws MalformedURLException if the url * is malformed. */ public GlobusURL(String url) throws MalformedURLException { int p1, p2; url = url.trim(); p1 = url.indexOf("://"); if (p1 == -1) { throw new MalformedURLException("Missing '[protocol]://'"); } protocol = url.substring(0, p1).toLowerCase(); p1 += 3; String base = null; p2 = url.indexOf('/', p1); if (p2 == -1) { /*throw new MalformedURLException("Missing '/' at [host]:[port]/");*/ base = url.substring(p1); urlPath = null; } else { base = url.substring(p1, p2); // this is after / p2++; if (p2 != url.length()) { urlPath = url.substring(p2); } else { urlPath = null; } } // this is [user]:[pwd]@[host]:[port] p1 = base.indexOf('@'); if (p1 == -1) { parseHostPort(base); } else { parseUserPwd( base.substring(0, p1) ); parseHostPort( base.substring(p1+1) ); } if (port == -1) { port = getPort(protocol); } if (protocol.equals("ftp") && user == null && pwd == null) { user = "anonymous"; pwd = "anon@anon.com"; } this.url = url; } /** * Creates a GlobusURL instance from URL instance. *
    Note: Not all the url parts are * copied. */ public GlobusURL(URL url) { // TODO: does not handle the password:user spec protocol = url.getProtocol(); host = url.getHost(); port = url.getPort(); urlPath = url.getFile(); } public static int getPort(String protocol) { if (protocol.equals("ftp")) { return 21; } else if (protocol.equals("gsiftp") || protocol.equals("gridftp")) { return 2811; } else if (protocol.equals("http")) { return 80; } else if (protocol.equals("https")) { return 443; } else if (protocol.equals("ldap")) { return 389; } else if (protocol.equals("ldaps")) { return 636; } else { return -1; } } private void parseHostPort(String str) throws MalformedURLException { int start = 0; if (str.length() > 0 && str.charAt(0) == '[') { start = str.indexOf(']'); if (start == -1) { throw new MalformedURLException( "Missing ']' in IPv6 address: " + str ); } } int p1 = str.indexOf(':', start); if (p1 == -1) { host = str; } else { host = str.substring(0, p1); String pp = str.substring(p1+1); try { port = Integer.parseInt(pp); } catch(NumberFormatException e) { throw new MalformedURLException("Invalid port number: " + pp); } } } private void parseUserPwd(String str) { int p1; p1 = str.indexOf(':'); if (p1 == -1) { user = Util.decode(str); } else { user = Util.decode(str.substring(0, p1)); pwd = Util.decode(str.substring(p1+1)); } } /** * Returns the string representation of * an url. * * @return the url as string. */ public String getURL() { return url; } /** * Returns the protocol of an url. * * @return the protocol part of the url. */ public String getProtocol() { return protocol; } /** * Returns the host name of an url. * * @return the host name part of the url. */ public String getHost() { return host; } /** * Returns the port number of an url. * * @return the port name of the url. -1 if * the port was not specified. */ public int getPort() { return port; } /** * Returns the url path part of an url. * * @return the url path part of the url. * Returns null if the url path is * not specified. */ public String getPath() { return urlPath; } /** * Returns the user name of an url. * * @return the user name if present in the url, * otherwise returns null. */ public String getUser() { return user; } /** * Returns the password of an url. * * @return the password if present in the url, * otherwise returns null. */ public String getPwd() { return pwd; } /** * Compares two urls. * * @param obj could be a string representation of an url * or an instance of this class. * @return true if the urls are the same, false otherwise. */ public boolean equals(Object obj) { GlobusURL cUrl = null; if (obj instanceof String) { try { cUrl = new GlobusURL((String)obj); } catch(MalformedURLException e) { return false; } } else if (obj instanceof GlobusURL) { cUrl = (GlobusURL)obj; } else { return false; } // do the comparison // compare ports if (getPort() != cUrl.getPort()) return false; if (!compare(getProtocol(), cUrl.getProtocol(), false)) return false; if (!compare(getHost(), cUrl.getHost(), false)) return false; if (!compare(urlPath, cUrl.urlPath, false)) return false; if (!compare(getUser(), cUrl.getUser(), false)) return false; if (!compare(getPwd(), cUrl.getPwd(), false)) return false; return true; } private boolean compare(String s1, String s2, boolean ignoreCase) { if (s1 == null) { return (s2 == null); } else if (s2 == null) { return false; } else { return (ignoreCase) ? s1.equalsIgnoreCase(s2) : s1.equals(s2); } } public int hashCode() { int value = this.port; if (this.protocol != null) { value += this.protocol.hashCode(); } if (this.host != null) { value += this.host.hashCode(); } if (this.urlPath != null) { value += this.urlPath.hashCode(); } if (this.user != null) { value += this.user.hashCode(); } if (this.pwd != null) { value += this.pwd.hashCode(); } return value; } public String toString() { StringBuffer info = new StringBuffer(); info.append("Protocol : " + protocol + "\n"); info.append("Host name : " + host + "\n"); info.append("Port number : " + port + "\n"); info.append("Url path : " + urlPath + "\n"); info.append("User : " + user + "\n"); info.append("Pwd : " + pwd + "\n"); return info.toString(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/I18n.java000066400000000000000000000076131241116057200273530ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import java.text.MessageFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * An utility class for internationalized message handling. * Example usage:: *
     * private static I18n i18n = I18n.getI18n("org.globus.resource");
     * ...
     * public void hello() {
     *    String filename = "file1";
     *    String msg = i18n.getMessage("noFile", new String[]{filename});
     *    ...
     * }
     * 
    */ public class I18n { private static Map mapping = new HashMap(); private ResourceBundle messages = null; protected I18n(ResourceBundle messages) { this.messages = messages; } /** * Retrieve a I18n instance by resource name. * * @param resource resource name. See {@link * ResourceBundle#getBundle(String) ResourceBundle.getBundle()} */ public static synchronized I18n getI18n(String resource) { I18n instance = (I18n)mapping.get(resource); if (instance == null) { instance = new I18n(ResourceBundle.getBundle(resource, Locale.getDefault(), getClassLoader())); mapping.put(resource, instance); } return instance; } /** * Retrieve a I18n instance by resource name * * @param resource resource name. See {@link * ResourceBundle#getBundle(String) ResourceBundle.getBundle()} * @param loader the class loader to be used to load * the resource. This parameter is only used * initially to load the actual resource. Once the resource * is loaded, this argument is ignored. */ public static synchronized I18n getI18n(String resource, ClassLoader loader) { I18n instance = (I18n)mapping.get(resource); if (instance == null) { if (loader == null) { loader = getClassLoader(); } instance = new I18n(ResourceBundle.getBundle(resource, Locale.getDefault(), loader)); mapping.put(resource, instance); } return instance; } private static ClassLoader getClassLoader() { // try to get caller's classloader otherwise use context classloader ClassLoader loader = ClassLoaderUtils.getClassLoaderContextAt(4); return (loader == null) ? Thread.currentThread().getContextClassLoader() : loader; } /** * Gets a message from resource bundle. */ public String getMessage(String key) throws MissingResourceException { return messages.getString(key); } /** * Gets a formatted message from resource bundle */ public String getMessage(String key, Object arg) throws MissingResourceException { return getMessage(key, new Object[] {arg}); } /** * Gets a formatted message from resource bundle */ public String getMessage(String key, Object[] vars) throws MissingResourceException { return MessageFormat.format(messages.getString(key), vars); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/PEMUtils.java000066400000000000000000000041121241116057200302650ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import java.io.OutputStream; import java.io.IOException; public class PEMUtils { static final int LINE_LENGTH = 64; public final static String lineSep; public final static byte[] lineSepBytes; static { lineSep = System.getProperty("line.separator"); lineSepBytes = lineSep.getBytes(); } public static void writeBase64(OutputStream out, String header, byte[] base64Data, String footer) throws IOException { int length = LINE_LENGTH; int offset = 0; if (header != null) { out.write(header.getBytes()); out.write(lineSepBytes); } int size = base64Data.length; while (offset < size) { if (LINE_LENGTH > (size - offset)) { length = size - offset; } out.write(base64Data, offset, length); out.write(lineSepBytes); offset = offset + LINE_LENGTH; } if (footer != null) { out.write(footer.getBytes()); out.write(lineSepBytes); } } /** * Return a hexadecimal representation of a byte array * @param b a byte array * @return String containing the hexadecimal representation */ public final static String toHex(byte [] b) { char[] buf = new char[b.length * 2]; int i, j, k; i = j = 0; for (; i < b.length; i++) { k = b[i]; buf[j++] = hex[(k >>> 4) & 0x0F]; buf[j++] = hex[ k & 0x0F]; } return new String(buf); } private static final char[] hex = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F'}; } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/QuotedStringTokenizer.java000066400000000000000000000042311241116057200331500ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import java.util.Enumeration; /* * This class is not thread safe. */ public class QuotedStringTokenizer implements Enumeration { private int limit; private int start; private String str; public QuotedStringTokenizer(String str) { this.str = str; start = 0; limit = str.length(); } public Object nextElement() { return nextToken(); } public String nextToken() { while ((start < limit) && Character.isWhitespace(str.charAt(start))) { start++; // eliminate leading whitespace } if (start == limit) return null; StringBuffer buf = new StringBuffer(limit-start); char ch; char quote = str.charAt(start); if (quote == '"' || quote == '\'') { start++; for (int i=start;i 0) { size = (len > CHUNK_SIZE) ? CHUNK_SIZE : (int)len; watcher.moveBuffer(buffer, size); len -= size; } } } } catch(IOException e) { _logger.debug("Unexpected error.", e); } finally { close(); } _logger.debug("[tail] done."); } private boolean isDone() throws IOException { if (!_stop) return false; Iterator iter = null; FileWatcher watcher = null; iter = list.iterator(); while(iter.hasNext()) { watcher = (FileWatcher)iter.next(); if (watcher.getDiff() > 0) return false; } return true; } private void close() { Iterator iter = null; FileWatcher watcher = null; iter = list.iterator(); while(iter.hasNext()) { watcher = (FileWatcher)iter.next(); watcher.close(); } } public void stop() { _logger.debug("[tail] stop called"); _stop = true; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/TimestampEntry.java000066400000000000000000000027051241116057200316160ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import java.io.Serializable; public class TimestampEntry implements Serializable { private Object value; private String description; private long lastModified; public TimestampEntry() { } public TimestampEntry(Object value, long lastModified) { this.value = value; this.lastModified = lastModified; } public Object getValue() { return this.value; } public void setValue(Object value) { this.value = value; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public long getLastModified() { return this.lastModified; } public void setLastModified(long lastModified) { this.lastModified = lastModified; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/Util.java000066400000000000000000000305771241116057200275560ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.UnknownHostException; import org.globus.common.CoGProperties; public class Util { private static final String CHMOD = "chmod"; private static final String DMSG = "Destroyed by Java Globus Proxy Destroy\r\n"; /** * Attempts to create a new file in an atomic way. * If the file already exists, it if first deleted. * * @param filename the name of file to create. * @return the created file. * @throws SecurityException if the existing file cannot be deleted. * @throws IOException if an I/O error occurred. */ public static File createFile(String filename) throws SecurityException, IOException { File f = new File(filename); if (!f.createNewFile()) { if (!destroy(f)) { throw new SecurityException( "Could not destroy existing file"); } if (!f.createNewFile()) { throw new SecurityException( "Failed to atomically create new file"); } } return f; } /** * Sets permissions on a given file to be only accessible by the current * user. * * @see #setFilePermissions(String, int) */ public static boolean setOwnerAccessOnly(String file) { return setFilePermissions(file, 600); } /** * Sets permissions on a given file. The permissions * are set using the chmod command and will only * work on Linux/Unix machines. Chmod command must be in the path. *

    Note: * This function executes an external program; thus, its behavior is * influenced by environment variables such as the caller's PATH and the * environment variables that control dynamic loading. Care should be * used if calling this function from a program that will be run as a * Unix setuid program, or in any other manner in which the owner of the * Unix process does not completely control its runtime environment. * * * @param file the file to set the permissions of. * @param mode the Unix style permissions. * @return true, if change was successful, otherwise false. * It can return false, in many instances, e.g. when file * does not exits, when chmod is not found, or other error * occurs. */ public static boolean setFilePermissions(String file, int mode) { // since this will not work on Windows if (ConfigUtil.getOS() == ConfigUtil.WINDOWS_OS) { return false; } Runtime runtime = Runtime.getRuntime(); String [] cmd = new String[] { CHMOD, String.valueOf(mode), file }; Process process = null; try { process = runtime.exec(cmd, null); return (process.waitFor() == 0) ? true : false; } catch(Exception e) { return false; } finally { if (process != null) { try { process.getErrorStream().close(); } catch (IOException e) {} try { process.getInputStream().close(); } catch (IOException e) {} try { process.getOutputStream().close(); } catch (IOException e) {} } } } /** * Overwrites the contents of the file with a random * string and then deletes the file. * * @param file file to remove */ public static boolean destroy(String file) { return destroy(new File(file)); } /** * Overwrites the contents of the file with a random * string and then deletes the file. * * @param file file to remove */ public static boolean destroy(File file) { if (!file.exists()) return false; RandomAccessFile f = null; long size = file.length(); try { f = new RandomAccessFile(file, "rw"); long rec = size/DMSG.length(); int left = (int)(size - rec*DMSG.length()); while(rec != 0) { f.write(DMSG.getBytes(), 0, DMSG.length()); rec--; } if (left > 0) { f.write(DMSG.getBytes(), 0, left); } } catch(Exception e) { return false; } finally { try { if (f != null) f.close(); } catch(Exception e) {} } return file.delete(); } /** * Displays a prompt and then reads in the input from System.in. * * @param prompt the prompt to be displayed * @return String the input read in (entered after the prompt) */ public static String getInput(String prompt) { System.out.print(prompt); try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); return in.readLine(); } catch(IOException e) { return null; } } /** * Displays a prompt and then reads in private input from System.in. * Characters typed by the user are replaced with a space on the screen. * * @param prompt the prompt to be displayed * @return String the input read in (entered after the prompt) */ public static String getPrivateInput(String prompt) { System.out.print(prompt); PrivateInputThread privateInput = new PrivateInputThread(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); privateInput.start(); try { return in.readLine(); } catch(Exception e) { return null; } finally { privateInput.kill(); } } /** * A helper thread to mask private user input. */ private static class PrivateInputThread extends Thread { private volatile boolean stopThread = false; public void kill() { this.stopThread = true; } public void run() { while(!this.stopThread) { System.out.print("\b "); try { sleep(1); } catch(InterruptedException e) { } } } } /** * Quotifies a specified string. * The entire string is encompassed by double quotes and each * " is replaced with \", \ is replaced with \\. * * @param str the string to quotify * @return quotified and escaped string */ public static String quote(String str) { int len = str.length(); StringBuffer buf = new StringBuffer(len+2); buf.append("\""); char c; for (int i=0;iString, each character is examined in turn: *
      *
    • The remaining characters are represented by 3-character * strings which begin with the percent sign, * "%xy", where xy is the two-digit * hexadecimal representation of the lower 8-bits of the character. *
    */ public static String decode(String s) { StringBuffer sb = new StringBuffer(); for(int i=0; iInetAddress class. In case the lookup * fails, the address 127.0.0.1 is returned. * * @return local ip address */ public static String getLocalHostAddress() { String ipAddr = CoGProperties.getDefault().getIPAddress(); if (ipAddr == null) { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { return "127.0.0.1"; } } else { return ipAddr; } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/deactivator/000077500000000000000000000000001241116057200302675ustar00rootroot00000000000000DeactivationHandler.java000066400000000000000000000013121241116057200347600ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/deactivator/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.deactivator; public interface DeactivationHandler { public void deactivate(); } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/deactivator/Deactivator.java000066400000000000000000000023011241116057200333730ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.deactivator; import java.util.*; public class Deactivator { private static Hashtable modules = new Hashtable(); public static void deactivateAll() { DeactivationHandler handler = null; Enumeration e = modules.keys(); while(e.hasMoreElements()) { handler = (DeactivationHandler)e.nextElement(); handler.deactivate(); } modules.clear(); } public static void registerDeactivation(DeactivationHandler handler) { modules.put(handler, ""); } public static void unregisterDeactivation(DeactivationHandler handler) { modules.remove(handler); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/deactivator/package.html000066400000000000000000000006171241116057200325540ustar00rootroot00000000000000 Deactivates registered resources and cleans up background processes, e.g. Gram or Gara callback handlers.

    Package Specification

    Related Documentation

    JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/000077500000000000000000000000001241116057200267415ustar00rootroot00000000000000HTTPChunkedInputStream.java000066400000000000000000000062361241116057200340110ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.http; import java.io.InputStream; import java.io.IOException; public class HTTPChunkedInputStream extends InputStream { protected byte[] _buf; protected int _index; protected int _max; protected boolean _eof; protected InputStream _in; public HTTPChunkedInputStream(InputStream in) { _in = in; // initial buf size - will adjust automatically _buf = new byte[2048]; _index = 0; _max = 0; _eof = false; } /* only called when the buffer is empty */ private void readChunk() throws IOException { String line = readLine(_in).trim(); int length = Integer.parseInt(line, 16); if (length > 0) { // make sure the chunk will fit into the buffer if (length > _buf.length) { _buf = new byte[length]; } int bytesLeft = length; int reqBytes = 0; int off = 0; int read = 0; /* multiple reads might be necessary to load the entire chunk */ while (bytesLeft != 0) { reqBytes = bytesLeft; read = _in.read(_buf, off, reqBytes); if (read == -1) break; bytesLeft -= read; off += read; } _max = off; _index = 0; } else { // end of data indicated _eof = true; } _in.read(); // skip CR _in.read(); // skip LF } /** * Read a line of text from the given Stream and return it * as a String. Assumes lines end in CRLF. */ private String readLine(InputStream in) throws IOException { StringBuffer buf = new StringBuffer(); int c, length = 0; while(true) { c = in.read(); if (c == -1 || c == '\n' || length > 512) { break; } else if (c == '\r') { in.read(); return buf.toString(); } else { buf.append((char)c); length++; } } return buf.toString(); } public int read(byte [] buffer, int off, int len) throws IOException { if (_eof) return -1; if (_max == _index) readChunk(); if (_index + len <= _max) { // that's easy System.arraycopy(_buf, _index, buffer, off, len); _index += len; return len; } else { int maximum = _max - _index; System.arraycopy(_buf, _index, buffer, off, maximum); _index += maximum; int read = read(buffer, off+maximum, len-maximum); if (read == -1) { return maximum; } else { return maximum + read; } } } public int read() throws IOException { if (_eof) return -1; if (_max == _index) readChunk(); return _buf[_index++] & 0xff; } public int available() throws IOException { return _in.available(); } public void close() throws IOException { _in.close(); } } HTTPChunkedOutputStream.java000066400000000000000000000060401241116057200342030ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.http; import java.io.OutputStream; import java.io.IOException; public class HTTPChunkedOutputStream extends OutputStream { protected boolean closed = false; protected int count; protected byte[] buf; protected OutputStream out; public HTTPChunkedOutputStream(OutputStream out) { this(out, 4096); } public HTTPChunkedOutputStream(OutputStream out, int size) { this.out = out; this.buf = new byte[size]; this.count = 0; } private void flushBuffer(boolean flush) throws IOException { String chunkLength = Integer.toString(this.count, 16); this.out.write(chunkLength.getBytes()); this.out.write(HTTPProtocol.CRLF.getBytes()); this.out.write(this.buf, 0, this.count); this.out.write(HTTPProtocol.CRLF.getBytes()); this.count = 0; if (flush) { this.out.flush(); } } private void checkNotClosed() throws IOException { if (this.closed) { throw new IOException("Already closed"); } } public synchronized void write(int b) throws IOException { checkNotClosed(); if (this.count >= this.buf.length) { flushBuffer(false); } this.buf[this.count++] = (byte)b; } public void write(byte b[]) throws IOException { write(b, 0, b.length); } public synchronized void flush() throws IOException { if (this.closed) { return; } if (this.count > 0) { flushBuffer(true); } } public synchronized void close() throws IOException { if (this.closed) { return; } flush(); // signal end of content with a zero-length chunk flushBuffer(true); this.closed = true; } public synchronized void write(byte b[], int off, int len) throws IOException { checkNotClosed(); int remaining = len; int sofar = 0; while (remaining > 0) { int roomInBuf = this.buf.length - this.count; int lenToWrite = Math.min(roomInBuf, len); System.arraycopy(b, sofar + off, buf, this.count, lenToWrite); sofar += lenToWrite; this.count += lenToWrite; remaining -= lenToWrite; if (this.count >= this.buf.length) { flushBuffer(false); } } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/HTTPParser.java000066400000000000000000000055631241116057200315510ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.http; import java.io.IOException; import java.io.InputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class HTTPParser { private static Log logger = LogFactory.getLog(HTTPParser.class.getName()); protected String _server; protected String _host; protected String _contentType; protected String _connection; protected long _contentLength; protected boolean _chunked; protected LineReader _reader; public HTTPParser(InputStream is) throws IOException { _contentLength = -1; _chunked = false; setInputStream(is); parse(); } public String getContentType() { return _contentType; } public long getContentLength() { return _contentLength; } public boolean isChunked() { return _chunked; } public LineReader getReader() { return _reader; } public void setInputStream(InputStream in) { _reader = new LineReader(in); } public abstract void parseHead(String line) throws IOException; /** * Parses the typical HTTP header. * @exception IOException if a connection fails or bad/incomplete request */ protected void parse() throws IOException { String line; line = _reader.readLine(); if (logger.isTraceEnabled()) { logger.trace(line); } parseHead(line); while ( (line = _reader.readLine()).length() != 0 ) { if (logger.isTraceEnabled()) { logger.trace(line); } if (line.startsWith(HTTPProtocol.CONNECTION)) { _connection = getRest(line, HTTPProtocol.CONNECTION.length()); } else if (line.startsWith(HTTPProtocol.SERVER)) { _server = getRest(line, HTTPProtocol.SERVER.length()); } else if (line.startsWith(HTTPProtocol.CONTENT_TYPE)) { _contentType = getRest(line, HTTPProtocol.CONTENT_TYPE.length()); } else if (line.startsWith(HTTPProtocol.CONTENT_LENGTH)) { _contentLength = Long.parseLong(getRest(line, HTTPProtocol.CONTENT_LENGTH.length())); } else if (line.startsWith(HTTPProtocol.HOST)){ _host = getRest(line, HTTPProtocol.HOST.length()); } else if (line.startsWith(HTTPProtocol.CHUNKED)) { _chunked = true; } } } protected static final String getRest(String line, int index) { return line.substring(index).trim(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/HTTPProtocol.java000066400000000000000000000111141241116057200321030ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.http; public class HTTPProtocol { public static final String CRLF = "\r\n"; public static final String HTTP_VERSION = "HTTP/1.1"; public static final String METHOD = "POST "; public static final String HOST = "Host: "; public static final String CONTENT_LENGTH = "Content-Length: "; public static final String CONTENT_TYPE = "Content-Type: "; public static final String USER_AGENT = "User-Agent: "; public static final String SERVER = "Server: "; public static final String CONNECTION = "Connection: "; public static final String LOCATION = "Location: "; public static final String CHUNKED = "Transfer-Encoding: chunked"; public static final String CONNECTION_CLOSE = "Connection: close\r\n"; public static final String CHUNKING = CHUNKED + CRLF; /* Used for GRAM and GARA messages */ protected static String createHTTPHeader(String service, String hostname, String application, StringBuffer msg) { StringBuffer head = new StringBuffer(); head.append("POST ").append(service).append(" ").append(HTTP_VERSION).append(CRLF); head.append(HOST).append(hostname).append(CRLF); head.append(CONTENT_TYPE).append(application).append(CRLF); head.append(CONTENT_LENGTH).append(String.valueOf(msg.length())).append(CRLF); head.append(CRLF); head.append(msg); return head.toString(); } /* Used for GASS GET */ public static String createGETHeader(String path, String host, String user_agent) { StringBuffer head = new StringBuffer(); head.append("GET " + path + " " + HTTP_VERSION + CRLF); head.append(HOST + host + CRLF); head.append(CONNECTION_CLOSE); head.append(USER_AGENT + user_agent + CRLF); head.append(CRLF); return head.toString(); } /* Used for GASS PUT */ public static String createPUTHeader(String path, String host, String user_agent, String type, long length, boolean append) { StringBuffer head = new StringBuffer(); if (append) { head.append("POST "); } else { head.append("PUT "); } head.append(path + " " + HTTP_VERSION + CRLF); head.append(HOST + host + CRLF); head.append(CONNECTION_CLOSE); head.append(USER_AGENT + user_agent + CRLF); head.append(CONTENT_TYPE + type + CRLF); if (length == -1) { head.append(CHUNKING); } else { head.append(CONTENT_LENGTH + length + CRLF); } head.append(CRLF); return head.toString(); } // ------ new HTTP stuff --------------------------- public static String ErrorReply(int error, String msg) { return getErrorReply(error, msg); } public static String getErrorReply(int error, String message) { StringBuffer head = new StringBuffer(); head.append(HTTP_VERSION) .append(" ") .append(String.valueOf(error)) .append(" ") .append(message) .append(CRLF) .append(CONNECTION_CLOSE) .append(CRLF); return head.toString(); } public static String getBadRequestErrorReply() { return getErrorReply(400, "BAD REQUEST"); } public static String getFileNotFoundErrorReply() { return getErrorReply(404, "FILE NOT FOUND"); } public static String getServerErrorReply() { return getErrorReply(500, "INTERAL SERVER ERROR"); } public static String getForbiddenErrorReply() { return getErrorReply(403, "FORBIDDEN"); } public static String getOKReply(String application) { return getOKReply(application, null); } public static String getOKReply(String application, String msg) { StringBuffer head = new StringBuffer(); head.append(HTTP_VERSION) .append(" 200 OK") .append(CRLF) .append(CONTENT_TYPE) .append(application) .append(CRLF) .append(CONTENT_LENGTH); if (msg == null) { head.append("0"); } else { head.append(msg.length()); } head.append(CRLF).append(CRLF); if (msg != null) { head.append(msg); } return head.toString(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/HTTPRequestParser.java000066400000000000000000000025511241116057200331140ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.http; import java.io.InputStream; import java.io.IOException; public class HTTPRequestParser extends HTTPParser { protected String _requestType; protected String _service; public HTTPRequestParser(InputStream is) throws IOException { super(is); } public String getService() { return _service; } public void setService(String service) { _service = service; } public void parseHead(String line) throws IOException { int st = line.indexOf(" "); if (st == -1) { throw new IOException("Bad HTTP header"); } _requestType = line.substring(0, st); st++; int et = line.indexOf(" ", st); if (et == -1) { throw new IOException("Bad HTTP header"); } _service = line.substring(st, et); et++; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/HTTPResponseParser.java000066400000000000000000000031031241116057200332540ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.http; import java.io.InputStream; import java.io.IOException; public class HTTPResponseParser extends HTTPParser { protected String _httpType; protected int _httpCode; protected String _httpMsg; public HTTPResponseParser(InputStream is) throws IOException { super(is); } public String getMessage() { return _httpMsg; } public int getStatusCode() { return _httpCode; } public boolean isOK() { return (_httpCode == 200); } public void parseHead(String line) throws IOException { int st = line.indexOf(" "); if (st == -1) { throw new IOException("Bad HTTP header"); } _httpType = line.substring(0, st); st++; int et = line.indexOf(" ", st); if (et == -1) { throw new IOException("Bad HTTP header"); } try { _httpCode = Integer.parseInt(line.substring(st, et).trim()); } catch(Exception e) { throw new IOException("Bad HTTP header"); } et++; _httpMsg = line.substring(et); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/HttpResponse.java000066400000000000000000000077561241116057200322610ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.http; import java.io.InputStream; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class HttpResponse { private static Log logger = LogFactory.getLog(HttpResponse.class.getName()); protected InputStream input; protected long charsRead = 0; public String httpType = null; public String httpMsg = null; public int httpCode = -1; public long contentLength = -1; public String connection = null; public String contentType = null; public String server = null; public boolean chunked = false; public String location = null; public HttpResponse(InputStream in) throws IOException { input = in; parse(); } /** * Read a line of text from the given Stream and return it * as a String. Assumes lines end in CRLF. */ protected String readLine(InputStream in) throws IOException { StringBuffer buf = new StringBuffer(); int c, length = 0; while(true) { c = in.read(); if (c == -1 || c == '\n' || length > 512) { charsRead++; break; } else if (c == '\r') { in.read(); charsRead+=2; break; } else { buf.append((char)c); length++; } } charsRead += length; return buf.toString(); } public static String getRest(String line) { int pos = line.indexOf(":"); if (pos == -1) { return null; } else return line.substring(pos+1).trim(); } public void parseHttp(String line) { int p1 = line.indexOf(" "); if (p1 == -1) { return; } httpType = line.substring(0,p1); int p2 = line.indexOf(" ",p1+1); String tmp; if (p2 == -1) { tmp = line.substring(p2); } else { tmp = line.substring(p1,p2); httpMsg = line.substring(p2).trim(); } httpCode = Integer.parseInt(tmp.trim()); } private void parse() throws IOException { String line, tmp; line = readLine(input); if (logger.isTraceEnabled()) { logger.trace(line); } parseHttp(line); while ( (line=readLine(input)).length() != 0 ) { if (logger.isTraceEnabled()) { logger.trace(line); } tmp = getRest(line); if (line.startsWith(HTTPProtocol.CONNECTION)) { connection = tmp; } else if (line.startsWith(HTTPProtocol.SERVER)) { server = tmp; } else if (line.startsWith(HTTPProtocol.CONTENT_TYPE)) { contentType = tmp; } else if (line.startsWith(HTTPProtocol.CONTENT_LENGTH)) { contentLength = Long.parseLong(tmp.trim()); } else if (line.startsWith(HTTPProtocol.CHUNKED)) { chunked = true; } else if (line.startsWith(HTTPProtocol.LOCATION)) { location = tmp; } } } /** Generates a string representation of the http header * * @return String a string representation of the http header */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("Http : " + httpType + "\n"); buf.append("Message : " + httpMsg + "\n"); buf.append("Code : " + httpCode + "\n"); if (server != null) { buf.append("Server : " + server + "\n"); } buf.append("Length : " + contentLength + "\n"); buf.append("Chunked : " + chunked + "\n"); buf.append("Type : " + contentType + "\n"); if (connection != null) { buf.append("Connection : " + connection + "\n"); } if (location != null) { buf.append("Location : " + location + "\n"); } return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/LineReader.java000066400000000000000000000035661241116057200316300ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util.http; import java.io.InputStream; import java.io.IOException; import java.io.FilterInputStream; public class LineReader extends FilterInputStream { private static final int MAX_LEN = 16* 1024; protected int _charsRead = 0; public LineReader(InputStream is) { super(is); } public InputStream getInputStream() { return in; } public int getCharsRead() { return _charsRead; } public String readLine() throws IOException { return readLine(in); } /** * Read a line of text from the given Stream and return it * as a String. Assumes lines end in CRLF. * @param in a connected stream which contains the entire * message being sen. * @exception IOException if a connection fails or abnormal connection * termination. * @return the next line read from the stream. */ protected String readLine(InputStream in) throws IOException { StringBuffer buf = new StringBuffer(); int c, length = 0; while(true) { c = in.read(); if (c == -1 || c == '\n' || length > MAX_LEN) { _charsRead++; break; } else if (c == '\r') { in.read(); _charsRead+=2; break; } else { buf.append((char)c); length++; } } _charsRead += length; return buf.toString(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/http/package.html000066400000000000000000000005411241116057200312220ustar00rootroot00000000000000 Provides low-level http handling, including message parsing.

    Package Specification

    Related Documentation

    JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/globus/util/package.html000066400000000000000000000011641241116057200302450ustar00rootroot00000000000000 org.globus.util package Provides utility classes used throughout different packages. It includes:
    • Url and HTTP classes
    • Base64 decoding/encoding classes
    • Debug support classes

    Package Specification

    Related Documentation

    For overviews, tutorials, examples, guides, and tool documentation, please see: JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/gridforum/000077500000000000000000000000001241116057200255105ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/gridforum/jgss/000077500000000000000000000000001241116057200264565ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/gridforum/jgss/ExtendedGSSContext.java000066400000000000000000000136311241116057200330070ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.gridforum.jgss; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSContext; import org.ietf.jgss.Oid; /** * Defines Java API for setting and getting context options and delegation extensions as defined in the * GSS-API Extensions document. * Some of the functions might not specify all the parameters as in the document. *

    Notes: *
      *
    • Extensions are not supported in initDelegation and acceptDelegation
    • *
    *
    * Here is a sample code showing how the delegation API might be used: *
     * ExtendedGSSContext client = ....
     * ExtendedGSSContext server = ....
     *
     * byte [] input = new byte[0];
     * byte [] output = null;
     * do {
     *	    output = client.initDelegation(null, null, 0, input, 0, input.length);
     * 	    input = server.acceptDelegation(0, output, 0, output.length);
     * } while (!client.isDelegationFinished());
     *
     * GSSCredential cred = server.getDelegatedCredential();
     * ...
     * 
    * Because delegation can be performed multiple times on the same contexts, the do { ... } while (); * block should be used to properly reset the delegation state (The state of isDelegationFinished * is reset on the initial call to initDelegation or acceptDelegation. */ public interface ExtendedGSSContext extends GSSContext { /** * Sets a context option. It can be called by context initiator or acceptor * but prior to the first call to initSecContext, acceptSecContext, initDelegation * or acceptDelegation. * * @param option * option type. * @param value * option value. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public void setOption(Oid option, Object value) throws GSSException; /** * Gets a context option. It can be called by context initiator or acceptor. * * @param option option type. * @return value option value. Maybe be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public Object getOption(Oid option) throws GSSException; /** * Initiate the delegation of a credential. * * This functions drives the initiating side of the credential * delegation process. It is expected to be called in tandem with the * acceptDelegation function. * * * @param cred * The credential to be delegated. May be null * in which case the credential associated with the security * context is used. * @param mechanism * The desired security mechanism. May be null. * @param lifetime * The requested period of validity (seconds) of the delegated * credential. * @return A token that should be passed to acceptDelegation if * isDelegationFinished returns false. May be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public byte[] initDelegation(GSSCredential cred, Oid mechanism, int lifetime, byte[] buf, int off, int len) throws GSSException; /** * Accept a delegated credential. * * This functions drives the accepting side of the credential * delegation process. It is expected to be called in tandem with the * initDelegation function. * * @param lifetime * The requested period of validity (seconds) of the delegated * credential. * @return A token that should be passed to initDelegation if * isDelegationFinished returns false. May be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public byte[] acceptDelegation(int lifetime, byte[] but, int off, int len) throws GSSException; /** * Returns the delegated credential that was delegated using * the initDelegation and acceptDelegation * functions. This is to be called on the delegation accepting * side once once isDelegationFinished returns true. * * @return The delegated credential. Might be null if credential * delegation is not finished. */ public GSSCredential getDelegatedCredential(); /** * Used during delegation to determine the state of the delegation. * * @return true if delegation was completed, false otherwise. */ public boolean isDelegationFinished(); /** * Retrieves arbitrary data about this context. * * @param oid the oid of the information desired. * @return the information desired. Might be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public Object inquireByOid(Oid oid) throws GSSException; /** * Specifies a list of ciphers that will not be used. * @param ciphers The list of banned ciphers. */ public void setBannedCiphers(String[] ciphers); } ExtendedGSSCredential.java000066400000000000000000000102411241116057200333500ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/gridforum/jgss/* * Copyright 1999-2010 University of Chicago * * 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 org.gridforum.jgss; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.Oid; /** * Defines Java API for credential export extension as defined in the * GSS-API Extensions document. * Some of the functions might not specify all the parameters as in the document. *

    Notes: *
      *
    • Protection key is currently not supported.
    • *
    */ public interface ExtendedGSSCredential extends GSSCredential { public static final int IMPEXP_OPAQUE = 0, IMPEXP_MECH_SPECIFIC = 1; /** * Exports this credential so that another process might import it. * The exported credential might be imported again using the * {@link ExtendedGSSManager#createCredential(byte[], int, int, Oid, int) * ExtendedGSSManager.createCredential} method. * * @param option * The export type. If set to {@link ExtendedGSSCredential#IMPEXP_OPAQUE * ExtendedGSSCredential.IMPEXP_OPAQUE} exported buffer is an opaque * buffer suitable for storage in memory or on disk or passing to * another process. If set to {@link ExtendedGSSCredential#IMPEXP_MECH_SPECIFIC * ExtendedGSSCredential.IMPEXP_MECH_SPECIFIC} exported buffer is a * buffer filled with mechanism-specific information that the calling * application can use to pass the credential to another process that * is not written to the GSS-API. * @return The buffer containing the credential * @exception GSSException containing the following major error codes: * GSSException.CREDENTIAL_EXPIRED, * GSSException.UNAVAILABLE, GSSException.FAILURE */ public byte[] export(int option) throws GSSException; /** * Exports this credential so that another process might import it. * The exported credential might be imported again using the * {@link ExtendedGSSManager#createCredential(byte[], int, int, Oid, int) * ExtendedGSSManager.createCredential} method. * * @param option * The export type. If set to {@link ExtendedGSSCredential#IMPEXP_OPAQUE * ExtendedGSSCredential.IMPEXP_OPAQUE} exported buffer is an opaque * buffer suitable for storage in memory or on disk or passing to * another process. If set to {@link ExtendedGSSCredential#IMPEXP_MECH_SPECIFIC * ExtendedGSSCredential.IMPEXP_MECH_SPECIFIC} exported buffer is a buffer * filled with mechanism-specific information that the calling application * can use to pass the credential to another process that is not written * to the GSS-API. * @param mech Desired mechanism for exported credential, may be null to * indicate system default. * @return The buffer containing the credential * @exception GSSException containing the following major error codes: * GSSException.CREDENTIAL_EXPIRED, * GSSException.UNAVAILABLE, GSSException.BAD_MECH, GSSException.FAILURE */ public byte[] export(int option, Oid mech) throws GSSException; /** * Retrieves arbitrary data about this credential. * * @param oid the oid of the information desired. * @return the information desired. Might be null. * @exception GSSException containing the following major error codes: * GSSException.FAILURE */ public Object inquireByOid(Oid oid) throws GSSException; } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/java/org/gridforum/jgss/ExtendedGSSManager.java000066400000000000000000000073371241116057200327430ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.gridforum.jgss; import org.ietf.jgss.GSSManager; import org.ietf.jgss.Oid; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; /** * Defines Java API for credential import extension as defined in the * GSS-API Extensions document. * Some of the functions might not specify all the parameters as in the document. *

    Notes: *
      *
    • Protection key is currently not supported.
    • *
    */ public abstract class ExtendedGSSManager extends GSSManager { private static ExtendedGSSManager gssManager; protected ExtendedGSSManager() {} /** * A factory method for creating a previously exported credential. * * @param buff * The token emitted from the {@link ExtendedGSSCredential#export(int, Oid) * ExtendedGSSCredential.export} method. * @param option * The import type. The import type must be the same as the * option used to export the buffer. * @param lifetime * The number of seconds that credentials should remain valid. Use * GSSCredential.INDEFINITE_LIFETIME to request that the credentials have * the maximum permitted lifetime. Use GSSCredential.DEFAULT_LIFETIME to request * default credential lifetime. * @param mech * The desired mechanism for the imported credential, may be null to indicate system default. * @param usage * The intended usage for this credential object. The value of this parameter must be one of: * GSSCredential.INITIATE_AND_ACCEPT, GSSCredential.ACCEPT_ONLY, and GSSCredential.INITIATE_ONLY. * @exception GSSException containing the following major error codes: GSSException.BAD_MECH, * GSSException.DEFECTIVE_TOKEN, GSSException.NO_CRED, GSSException.CREDENTIAL_EXPIRED, * GSSException.FAILURE */ public abstract GSSCredential createCredential (byte[] buff, int option, int lifetime, Oid mech, int usage) throws GSSException; public synchronized static GSSManager getInstance() { if (gssManager == null) { String className = System.getProperty("org.globus.gsi.gssapi.provider"); if (className == null) { className = "org.globus.gsi.gssapi.GlobusGSSManagerImpl"; } try { Class clazz = Class.forName(className); if (!ExtendedGSSManager.class.isAssignableFrom(clazz)) { throw new RuntimeException("Invalid ExtendedGSSManager provider class: '" + className + "'"); } gssManager = (ExtendedGSSManager)clazz.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to load '" + className + "' class: " + e.getMessage()); } catch (InstantiationException e) { throw new RuntimeException("Unable to instantiate '" + className + "' class: " + e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to instantiate '" + className + "' class: " + e.getMessage()); } } return gssManager; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/000077500000000000000000000000001241116057200240145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/log4j.properties000066400000000000000000000004221241116057200271470ustar00rootroot00000000000000log4j.rootCategory=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c{2} %x - %m%n log4j.category.COM.claymoresystems.ptls.SSLDebug=OFF JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/000077500000000000000000000000001241116057200246035ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/000077500000000000000000000000001241116057200260765ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/gsi/000077500000000000000000000000001241116057200266605ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/gsi/errors.properties000066400000000000000000000062301241116057200323130ustar00rootroot00000000000000proxyNotFound = [JGLOBUS-5] Proxy file ({0}) not found. encPrivKey = [JGLOBUS-6] Private key file must not be encrypted. ioError00 = [JGLOBUS-7] Failed to load credentials. secError00 = [JGLOBUS-8] Failed to load credentials. error00 = [JGLOBUS-9] Failed to load credentials. expired00 = [JGLOBUS-10] Expired credentials. noCerts00 = [JGLOBUS-11] No certificates loaded noKey00 = [JGLOBUS-12] No private key loaded certFileNull = [JGLOBUS-13] Certificate file is null noCertData = [JGLOBUS-14] Certificate data not found. crlFileNull = [JGLOBUS-15] CRL file is null noCrlData = [JGLOBUS-16] CRL data not found. proxyFileNull = [JGLOBUS-17] Proxy file is null credInpStreamNull = [JGLOBUS-18] Credential input stream cannot be null pemFooter = [JGLOBUS-19] PEM footer missing dataNull = [JGLOBUS-20] Data is null noPrivateKey = [JGLOBUS-21] PRIVATE KEY section not found. algNotSup = [JGLOBUS-22] Algorithm not supported. unsupEnc = [JGLOBUS-23] Unsupported encryption: \"{0}\" ivLength = [JGLOBUS-24] Expected IV length of \"{0}\" but got \"{1}\" oidNull = [JGLOBUS-25] OID is null certNull = [JGLOBUS-26] Certificate is null extensionNull = [JGLOBUS-27] Extension is null certReqVerification = [JGLOBUS-28] Certificate request verification failed restrictProxy = [JGLOBUS-29] Restricted proxy requires ProxyCertInfo extension invalidProxyType = [JGLOBUS-30] Invalid proxyType keyUsageExt = [JGLOBUS-31] KeyUsage extension present in isuer certificate, but also provided in X509Extension map. This is unsupported. unsupportedProxy = [JGLOBUS-32] Unsupported proxyType : \"{0}\" proxyCertCritical = [JGLOBUS-33] ProxyCertInfo extension must be critical proxyDNErr = [JGLOBUS-34] Issuer name + proxy CN entry is not equal to subject name certTypeErr = [JGLOBUS-35] Unexpected certificate type: \"{0}\" certChainNull = [JGLOBUS-36] Certificate chain is null octetExp = [JGLOBUS-37] Expected octet string byteArrayErr = [JGLOBUS-38] Failed to convert to byte array certVerifyError = [JGLOBUS-116] Certificate validation failed. #Signing policy errors invalidPosRights= File format is incorrect. pos_rights cannot be used here. Invalid line: \"{0}\" invalidNegRights= File format is incorrect. neg_rights cannot be used here. Invalid line: \"{0}\" invalidRestrictions= File format is incorrect. Restrictions cannot be used here. Invalid line: \"{0}\" invalidLine= File format is incorrect. Each line should start with access_id, pos_rights, neg_rights or cond_. Invalid line: \"{0}\" invalidAccessId = File format is incorrect. Expected line to start with access_id. Invalid line: \"{0}\" invalidTokens= Line format is incorrect, atleast three tokens are expected. Invalid line: \"{0}\" invalidSubjects= Line format is incorrect, subject DNs with space should be enclosed in quotes. Invalid line is: \"{0}\" emptySubjects= Line format is incorrect, subject DNs list is empty. Invalid line is: \"{0}\" unmatchedQuotes= Line format is incorrect, unmatched quotes. Invalid line is: \"{0}\" invalidCaDN = Line format is incorrect, CA DN with space should be enclosed in quotes. Invalid section of the line is: \"{0}\" invalidRestriction = Line format is incorrect, Mismatched quotations in allowed subjects. Invalid line is: \"{0}\" JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/gsi/gridmap/000077500000000000000000000000001241116057200303035ustar00rootroot00000000000000errors.properties000066400000000000000000000003031241116057200336520ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/gsi/gridmapglobusIdErr = [JGLOBUS-1] Globus ID missing: \"{0}\" userIdErr = [JGLOBUS-2] User ID mapping missing: \"{0}\" globusIdNull = [JGLOBUS-3] Globus ID is null userIdNull = [JGLOBUS-4] User ID is nullJGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/gsi/proxy/000077500000000000000000000000001241116057200300415ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/gsi/proxy/errors.properties000066400000000000000000000056071241116057200335030ustar00rootroot00000000000000proxyPolicyId = [JGLOBUS-74] Proxy Policy id is null proxyPolixyHandler = [JGLOBUS-75] Proxy Policy handler is null certsNull = [JGLOBUS-76] Certificate array is null unknownCA = [JGLOBUS-77] Unknown CA proxyErr00 = [JGLOBUS-78] CA certificate cannot sign Proxy Certificate proxyErr01 = [JGLOBUS-79] CA Certificate does not allow path length > \"{0}\" and path length is \"{1}\" proxyErr02 = [JGLOBUS-80] Proxy Certificate can only sign another proxy of the same type proxyErr03 = [JGLOBUS-81] Proxy Certificate cannot be used to sign another Proxy Certificate. Proxy path length constraint is 0. proxyErr04 = [JGLOBUS-82] Proxy Certificate does not allow path length > \"{0}\" and path length is \"{1}\" proxyErr05 = [JGLOBUS-83] End Entity Certificate can only sign Proxy Certificates proxyErr06 = [JGLOBUS-84] Unknown cert type \"{0}\" limitedProxy = [JGLOBUS-85] Limited proxies not accepted proxyErr07 = [JGLOBUS-86] Could not retreive ProxyCertInfo extension proxyErr08 = [JGLOBUS-87] Could not retreive ProxyPolicy from ProxyCertInfo extension proxyErr09 = [JGLOBUS-88] Unknown Policy \"{0}\" proxyErr10 = [JGLOBUS-89] KeyUsage extension present but keyCertSign bit not asserted proxyErr11 = [JGLOBUS-90] Proxy certificate cannot contain subject or issuer alternative name extension proxyErr12 = [JGLOBUS-91] Proxy certificate cannot have BasicConstraint CA=true proxyErr13 = [JGLOBUS-92] The keyCertSign and nonRepudiation bits must not be asserted in Proxy Certificate proxyErr14 = [JGLOBUS-93] Bad KeyUsage in Proxy Certificate proxyErr15 = [JGLOBUS-94] KeyUsage extension in Proxy Certificate is not critical proxyErr16 = [JGLOBUS-95] Unsuppored critical exception : \"{0}\" proxyErr17 = [JGLOBUS-96] Certificate \"{0}\" expired. Certificate valid till \"{1}\" and current time is \"{2}\" proxyErr18 = [JGLOBUS-97] Certificate \"{0}\" not yet valid. Certificate valid from \"{1}\" and current time is \"{2}\" proxyErr19 = [JGLOBUS-98] Trusted certificates are null, cannot verify CRLs proxyErr20 = [JGLOBUS-99] CRL verification failed proxyErr21 = [JGLOBUS-100] This certificate \"{0}\" is on a CRL proxyErr22 = [JGLOBUS-101] Extension is null proxyErr23 = [JGLOBUS-102] Oid cannot be changed proxyErr24 = [JGLOBUS-103] Critical property cannot be changed proxyErr25 = [JGLOBUS-104] Invalid sequnece proxyErr26 = [JGLOBUS-105] Unable convert byte array: proxyErr27 = [JGLOBUS-106] Unknown object in factory proxyErr28 = [JGLOBUS-107] ProxyCertInfo is null proxyErr29 = [JGLOBUS-108] Critical property cannot be changed proxyErr30 = [JGLOBUS-109] Invalid sequence proxyErr31 = [JGLOBUS-110] Policy langauge oid required proxyErr32 = [JGLOBUS-111] Constraints violation proxyErr33 = No signing policy file found for CA \"{0}\" proxyErr34 = \"{0}\" violates the signing policy defined for CA \"{1}\" in file \"{2}\" proxyErr35 = No relevant signing policy for CA \"{0}\" in file \"{1}\" proxyErr36 = CRL for CA \"{0}\" has expired. JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/gsi/ptls/000077500000000000000000000000001241116057200276425ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/main/resources/org/globus/gsi/ptls/errors.properties000066400000000000000000000003651241116057200333000ustar00rootroot00000000000000malformedName = [JGLOBUS-112] Malformed name, \"{0}\" missing in \"{1}\" invalidToken00 = [JGLOBUS-113] Token \"{0}\" does not start with '/' rdnMissing = [JGLOBUS-114] RDN \"{0}\" is missing '=' conversionFail = [JGLOBUS-115] Conversion failed.JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/000077500000000000000000000000001241116057200220355ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/000077500000000000000000000000001241116057200227565ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/000077500000000000000000000000001241116057200235455ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/000077500000000000000000000000001241116057200250405ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/common/000077500000000000000000000000001241116057200263305ustar00rootroot00000000000000ResourceManagerContactTest.java000066400000000000000000000065221241116057200343570ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/common/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.common; import junit.framework.TestCase; import org.globus.common.ResourceManagerContact; public class ResourceManagerContactTest extends TestCase { public void testBasic() throws Exception { ResourceManagerContact c = null; c = new ResourceManagerContact("pitcairn.mcs.anl.gov"); verify(c, "pitcairn.mcs.anl.gov", 2119); c = new ResourceManagerContact("pitcairn.mcs.anl.gov:123"); verify(c, "pitcairn.mcs.anl.gov", 123); c = new ResourceManagerContact("pitcairn.mcs.anl.gov:123/job"); verify(c, "pitcairn.mcs.anl.gov", 123, "/job"); c = new ResourceManagerContact("pitcairn.mcs.anl.gov/job"); verify(c, "pitcairn.mcs.anl.gov", 2119, "/job"); c = new ResourceManagerContact("pitcairn.mcs.anl.gov:/job"); verify(c, "pitcairn.mcs.anl.gov", 2119, "/job"); c = new ResourceManagerContact("pitcairn.mcs.anl.gov::cn=jarek"); verify(c, "pitcairn.mcs.anl.gov", 2119, "/jobmanager", "cn=jarek"); c = new ResourceManagerContact("pitcairn.mcs.anl.gov:123:cn=jarek"); verify(c, "pitcairn.mcs.anl.gov", 123, "/jobmanager", "cn=jarek"); c = new ResourceManagerContact("pitcairn.mcs.anl.gov:/job:cn=jarek"); verify(c, "pitcairn.mcs.anl.gov", 2119, "/job", "cn=jarek"); c = new ResourceManagerContact("pitcairn.mcs.anl.gov/job:cn=jarek"); verify(c, "pitcairn.mcs.anl.gov", 2119, "/job", "cn=jarek"); c = new ResourceManagerContact("pitcairn.mcs.anl.gov:123/job:cn=jarek"); verify(c, "pitcairn.mcs.anl.gov", 123, "/job", "cn=jarek"); } public void testBasicIPv6() throws Exception { ResourceManagerContact c = null; c = new ResourceManagerContact("[3ffe:2a00:100:7031::1]"); verify(c, "[3ffe:2a00:100:7031::1]", 2119); c = new ResourceManagerContact("[3ffe:2a00:100:7031::1]:123"); verify(c, "[3ffe:2a00:100:7031::1]", 123); c = new ResourceManagerContact("[3ffe:2a00:100:7031::1]/job"); verify(c, "[3ffe:2a00:100:7031::1]", 2119, "/job"); } private void verify(ResourceManagerContact contact, String hostname, int port) { verify(contact, hostname, port, "/jobmanager", null); } private void verify(ResourceManagerContact contact, String hostname, int port, String serviceName) { verify(contact, hostname, port, serviceName, null); } private void verify(ResourceManagerContact contact, String hostname, int port, String serviceName, String dn) { assertEquals("hostname", hostname, contact.getHostName()); assertEquals("port", port, contact.getPortNumber()); assertEquals("service", serviceName, contact.getServiceName()); assertEquals("dn", dn, contact.getGlobusDN()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/000077500000000000000000000000001241116057200256225ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/OpenSSLKeyTest.java000066400000000000000000000130641241116057200312650ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import java.security.GeneralSecurityException; import java.security.PrivateKey; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import org.globus.gsi.testutils.FileSetupUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Created by IntelliJ IDEA. User: turtlebender Date: Dec 31, 2009 Time: 9:54:25 * AM To change this template use File | Settings | File Templates. */ @Category( { SecurityTest.class }) public class OpenSSLKeyTest { static FileSetupUtil file; @BeforeClass public static void setup() throws Exception { file = new FileSetupUtil("key.pem"); file.copyFileToTemp(); file.getTempFile(); } @AfterClass public static void cleanup() throws Exception { file.deleteFile(); } @Test public void testOpenSSLKeyCreation() throws Exception { OpenSSLKey opensslkey = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); byte[] encoded = opensslkey.getEncoded(); OpenSSLKey byteStreamInit = new BouncyCastleOpenSSLKey("RSA", encoded); assertThat(opensslkey.getEncoded(), is(byteStreamInit.getEncoded())); PrivateKey privateKey = opensslkey.getPrivateKey(); OpenSSLKey privateKeyInit = new BouncyCastleOpenSSLKey(privateKey); assertThat(opensslkey.getEncoded(), is(privateKeyInit.getEncoded())); opensslkey.encrypt("password"); assertThat(opensslkey.getEncoded(), is(not(encoded))); byteStreamInit.encrypt("password"); opensslkey = new BouncyCastleOpenSSLKey(opensslkey.getPrivateKey()); opensslkey.decrypt("password"); byteStreamInit = new BouncyCastleOpenSSLKey(byteStreamInit.getPrivateKey()); byteStreamInit.decrypt("password"); assertThat(opensslkey.getEncoded(), is(byteStreamInit.getEncoded())); } @Test(expected = IllegalArgumentException.class) public void testNullByteStream() throws Exception { new BouncyCastleOpenSSLKey("RSA", null); } @Test(expected = GeneralSecurityException.class) public void testEmptyByteStream() throws Exception { new BouncyCastleOpenSSLKey("RSA", new byte[] {}); } // @Test // public void testNullAlgo() throws Exception{ // new BouncyCastleOpenSSLKey(null, new byte[]{}); // } @Test public void testEqualsNull() throws Exception { OpenSSLKey key = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); assertThat(key, not(equalTo(null))); } @Test public void testEqualsReflexive() throws Exception { OpenSSLKey key = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); assertThat(key, equalTo(key)); } @Test public void testEqualsSymmetricForEqualKeys() throws Exception { OpenSSLKey key1 = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); OpenSSLKey key2 = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); assertThat(key2, equalTo(key1)); assertThat(key1, equalTo(key2)); } @Test public void testEqualsForKeysDifferingByEncrypted() throws Exception { OpenSSLKey key1 = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); OpenSSLKey key2 = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); key2.encrypt("too many secrets"); assertThat(key2, not(equalTo(key1))); } @Test public void testSerializableUnencrypted() throws Exception { OpenSSLKey key = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); OpenSSLKey copy = serialiseAndDeserialise(key); assertThat(copy, equalTo(key)); } @Test public void testSerializableEncrypted() throws Exception { OpenSSLKey key = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); key.encrypt("too many secrets"); OpenSSLKey copy = serialiseAndDeserialise(key); assertThat(copy, equalTo(key)); } private OpenSSLKey serialiseAndDeserialise(OpenSSLKey key) throws IOException, ClassNotFoundException { ByteArrayOutputStream storage = new ByteArrayOutputStream(); new ObjectOutputStream(storage).writeObject(key); byte[] data = storage.toByteArray(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data)); return (OpenSSLKey) in.readObject(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/SecurityTest.java000066400000000000000000000000741241116057200311350ustar00rootroot00000000000000package org.globus.gsi; public interface SecurityTest { } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/SigningPolicyParserTest.java000066400000000000000000000424451241116057200332710ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.StringReader; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; import javax.security.auth.x500.X500Principal; import org.globus.gsi.SigningPolicy; import org.globus.gsi.testutils.FileSetupUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; public class SigningPolicyParserTest { FileSetupUtil successFile; FileSetupUtil singleAllowedDn; FileSetupUtil[] tabTestFiles; @Before public void setup() throws Exception { this.successFile = new FileSetupUtil( "certificateUtilTest/samplePolicy.signing_policy"); this.singleAllowedDn = new FileSetupUtil("certificateUtilTest/5aba75cb.signing_policy"); this.tabTestFiles = new FileSetupUtil[3]; this.tabTestFiles[0] = new FileSetupUtil("certificateUtilTest/afe55e66.signing_policy"); this.tabTestFiles[1] = new FileSetupUtil("certificateUtilTest/cf4ba8c8.signing_policy"); this.tabTestFiles[2] = new FileSetupUtil("certificateUtilTest/49f18420.signing_policy"); } @Test public void testPatternMatching() throws Exception { // test getPattern method // no wildcards or question marks String patternStr = "CN=abcdefgh"; String patternR = (SigningPolicyParser.getPattern(patternStr)) .pattern(); assertTrue("CN=abcdefgh".equals(patternR)); // first character wildcard and question marks String pattern1Str = "CN=*def?gh?"; Pattern pattern1 = SigningPolicyParser.getPattern(pattern1Str); String pattern1R = pattern1.pattern(); assertTrue(("CN=" + SigningPolicyParser.WILDCARD_PATTERN + "def" + SigningPolicyParser.SINGLE_PATTERN + "gh" + SigningPolicyParser.SINGLE_PATTERN).equals(pattern1R)); // only wild cards String pattern2Str = "/CN=abc*def*gh"; Pattern pattern2 = SigningPolicyParser.getPattern(pattern2Str); String pattern2R = pattern2.pattern(); assertTrue( ("/CN=abc" + SigningPolicyParser.WILDCARD_PATTERN + "def" + SigningPolicyParser.WILDCARD_PATTERN + "gh").equals( pattern2R)); // test isValidDN methods // Add patern2, wildcards in middle Vector allowed = new Vector(); allowed.add(pattern2); X500Principal fooPrincipal = new X500Principal("CN=foo"); SigningPolicy policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject21 = new X500Principal("CN=abc12DEF34defdef56gh"); assertTrue(policy.isValidSubject(subject21)); X500Principal subject22 = new X500Principal("CN=123abc12def34defdef56gh"); assertFalse(policy.isValidSubject(subject22)); X500Principal subject23 = new X500Principal("CN=abc12def34defdef56gh123"); assertFalse(policy.isValidSubject(subject23)); // wildcard as first and last character String pattern3Str = "*abc*def*gh*"; Pattern pattern3 = SigningPolicyParser.getPattern(pattern3Str); allowed.clear(); allowed.add(pattern3); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject31 = new X500Principal("CN=ABC12def34defdef56gh"); assertTrue(policy.isValidSubject(subject31)); X500Principal subject32 = new X500Principal("CN=123abc12def34defdef56gh555"); assertTrue(policy.isValidSubject(subject32)); // use of space and slashes, from old signing policy file String pattern4Str = "/C=US/O=Globus/*"; Pattern pattern4 = SigningPolicyParser.getPattern(pattern4Str); allowed.clear(); allowed.add(pattern4); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject41 = new X500Principal( "CN=Globus Certification Authority, O=Globus, C=US"); assertTrue(policy.isValidSubject(subject41)); // wildcard as first character, question mark String pattern5Str = "/*C=US/O=Globus/CN=foo-?/CN=*"; Pattern pattern5 = SigningPolicyParser.getPattern(pattern5Str); allowed.clear(); allowed.add(pattern5); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject51 = new X500Principal( "CN=Globus Certification Authority, O=Globus, O=US"); assertFalse(policy.isValidSubject(subject51)); X500Principal subject52 = new X500Principal( "CN=test space,CN=a12b,CN=foo-1,O=Globus,C=US,C=SOME"); assertTrue(policy.isValidSubject(subject52)); X500Principal subject53 = new X500Principal("CN=,CN=foo-k,O=Globus,C=US"); assertTrue(policy.isValidSubject(subject53)); X500Principal subject54 = new X500Principal("CN= , CN=foo-1, O=Globus, C=US"); assertTrue(policy.isValidSubject(subject54)); X500Principal subject55 = new X500Principal("C=US,O=Globus,CN=foo-123,CN="); assertFalse(policy.isValidSubject(subject55)); // multiple question mark with punctuation String pattern6Str = "/C=US/O=global/CN=*/CN=user-??"; Pattern pattern6 = SigningPolicyParser.getPattern(pattern6Str); allowed.clear(); allowed.add(pattern6); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject61 = new X500Principal("CN=user-12,CN=foo,O=Globus,C=US"); assertFalse(policy.isValidSubject(subject61)); X500Principal subject62 = new X500Principal("CN=user-12,CN=foo,O=Global,C=US"); assertTrue(policy.isValidSubject(subject62)); X500Principal subject63 = new X500Principal("CN=user-12,CN=bar 1,CN=foo ,O=global,C=US"); assertTrue(policy.isValidSubject(subject63)); // add multiple patterns and test validity if atleast one matches String pattern7Str = "/C=US/O=Globus/CN=*/CN=user-??"; Pattern pattern7 = SigningPolicyParser.getPattern(pattern7Str); allowed.add(pattern7); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject71 = new X500Principal("CN=user-12, CN=bar 1, CN=foo , O=Globus,C=US"); assertTrue(policy.isValidSubject(subject71)); assertTrue(policy.isValidSubject(subject63)); } // JGLOBUS-103 @Test public void testFileSuccess() throws Exception { this.successFile.copyFileToTemp(); SigningPolicyParser parser = new SigningPolicyParser(); Map map = parser.parse(this.successFile.getAbsoluteFilename()); assertTrue(map != null); SigningPolicy policy = map.get(new X500Principal( "CN=Globus Certification Authority,O=Globus,C=US")); assertTrue(policy != null); List allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); List patterns = new Vector(2); patterns.add((allowedDN.get(0)).pattern()); patterns.add((allowedDN.get(1)).pattern()); // given the getPattern method is already tested, assuming it // works here. Pattern p1 = SigningPolicyParser.getPattern("/C=us/O=Globus/*"); assertTrue(patterns.contains(p1.pattern())); p1 = SigningPolicyParser.getPattern("/C=US/O=Globus/*"); assertTrue(patterns.contains(p1.pattern())); p1 = SigningPolicyParser .getPattern("/C=us/O=National Computational Science Alliance/*"); assertFalse(patterns.contains(p1.pattern())); policy = map.get(new X500Principal( "CN=Globus Certification Authority,O=National Computational Science Alliance,C=US")); assertTrue(policy != null); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 1); patterns.clear(); patterns.add(((Pattern) allowedDN.get(0)).pattern()); p1 = SigningPolicyParser .getPattern("/C=us/O=National Computational Science Alliance/*"); assertTrue(patterns.contains(p1.pattern())); // test file with single allows DN without double quotes this.singleAllowedDn.copyFileToTemp(); map.clear(); map = parser.parse(this.singleAllowedDn.getAbsoluteFilename()); policy = map.get(new X500Principal( "OU=Certification Authority,O=National Computational Science Alliance,C=US")); assertTrue(policy != null); allowedDN.clear(); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 1); patterns = new Vector(1); patterns.add(((Pattern) allowedDN.get(0)).pattern()); p1 = SigningPolicyParser .getPattern("/C=US/O=National Computational Science Alliance/*"); assertTrue(patterns.contains(p1.pattern())); } @Test public void testFilesWithTab() throws Exception { this.tabTestFiles[0].copyFileToTemp(); SigningPolicyParser parser = new SigningPolicyParser(); Map map = parser.parse(this.tabTestFiles[0].getAbsoluteFilename()); SigningPolicy policy = map.get(new X500Principal("CN=CyGridCA,O=HPCL,O=CyGrid,C=CY")); assertTrue(policy != null); List allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 1); allowedDN.clear(); map.clear(); this.tabTestFiles[1].copyFileToTemp(); map = parser.parse(this.tabTestFiles[1].getAbsoluteFilename()); policy = map.get(new X500Principal("CN=CNRS,O=CNRS,C=FR")); assertTrue(policy != null); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); Vector patterns = new Vector(2); patterns.add(((Pattern) allowedDN.get(0)).pattern()); patterns.add(((Pattern) allowedDN.get(1)).pattern()); // given the getPattern method is already tested, assuming it // works here. Pattern p1 = SigningPolicyParser .getPattern("/C=FR/O=CNRS/CN=CNRS-Projets"); assertTrue(patterns.contains(p1.pattern())); p1 = SigningPolicyParser.getPattern("/C=FR/O=CNRS/CN=CNRS"); assertTrue(patterns.contains(p1.pattern())); allowedDN.clear(); map.clear(); this.tabTestFiles[2].copyFileToTemp(); map = parser.parse(this.tabTestFiles[2].getAbsoluteFilename()); policy = map.get( new X500Principal("CN=INFN Certification Authority,O=INFN,C=IT")); assertTrue(policy != null); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); patterns.clear(); patterns.add(((Pattern) allowedDN.get(0)).pattern()); patterns.add(((Pattern) allowedDN.get(1)).pattern()); // given the getPattern method is already tested, assuming it // works here. p1 = SigningPolicyParser.getPattern("/C=it/O=INFN/*"); assertTrue(patterns.contains(p1.pattern())); p1 = SigningPolicyParser.getPattern("/C=IT/O=INFN/*"); assertTrue(patterns.contains(p1.pattern())); } @Test(expected = SigningPolicyException.class) public void testFileFailure() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); parser.parse("Foo"); } @Test public void testParsingFailure() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); // not x509 String error1 = "access_id_CA notX509 '/C=US/O=Globus/CN=Globus " + "Certification Authority'\n pos_rights globus CA:sign\n" + " cond_subjects globus '\"/C=us/O=Globus/*\" \"/C=US/O=Globus/*\"'"; Map map = null; boolean worked = false; try { map = parser.parse(new StringReader(error1)); } catch (IllegalArgumentException e) { worked = true; } assertTrue(worked); // not globus error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus " + "Certification Authority'\n pos_rights notglobus " + "CA:sign\n cond_subjects globus '\"/C=us/O=Globus/*\" " + "\"/C=US/O=Globus/*\"'"; map = parser.parse(new StringReader(error1)); // order of rights matter, atleast one positive right implies // allowed DN error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification " + "Authority'\n pos_rights globus CA:sign\n cond_subjects" + " globus '\"/C=us/O=Globus/*\" \"/C=US/O=Globus/*\"' \n " + "neg_rights notglobus some:right"; map = parser.parse(new StringReader(error1)); SigningPolicy policy = map.get(new X500Principal( "CN=Globus Certification Authority,O=Globus,C=US")); assertTrue(policy != null); List allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); // incorrect start error1 = "X509 '/C=US/O=Globus/CN=Globus Certification Authority'\n" + " pos_rights notglobus CA:sign\n cond_subjects " + "globus \'\"/C=us/O=Globus/*\" \"/C=US/O=Globus/*\"\'"; boolean exception = false; try { map = parser.parse(new StringReader(error1)); } catch (SigningPolicyException exp) { exception = true; } assertTrue(exception); // erroneous quote error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification " + "Authority\n pos_rights notglobus CA:sign\n " + "cond_subjects globus \'\"/C=us/O=Globus/*\" " + "\"/C=US/O=Globus/*\"\'"; exception = false; try { map = parser.parse(new StringReader(error1)); } catch (SigningPolicyException exp) { if ((exp.getMessage().indexOf("invalid")) != -1) { exception = true; } } assertTrue(exception); // neg rights rather than restrictions error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus " + "Certification Authority'\n pos_rights globus " + "CA:sign\n neg_rights notglobus some:right"; exception = false; try { map = parser.parse(new StringReader(error1)); } catch (SigningPolicyException exp) { // if ((exp.getMessage().indexOf("File format is incorrect") != -1) && // (exp.getMessage(). // indexOf("neg_rights cannot be used here") != -1)) { exception = true; // } } assertTrue(exception); // first pos_rights is all that matters error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification " + "Authority'\n pos_rights globus CA:sign\n " + "cond_subjects globus '\"/C=us/O=Globus/*\" " + "\"/C=US/O=Globus/*\"' \n cond_subjects globus " + "'\"/C=us/O=Globus/*\"'"; map = parser.parse(new StringReader(error1)); policy = map.get(new X500Principal( "CN=Globus Certification Authority,O=Globus,C=US")); assertTrue(policy != null); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); } @After public void cleanUp() throws Exception { this.singleAllowedDn.deleteFile(); this.successFile.deleteFile(); this.tabTestFiles[0].deleteFile(); this.tabTestFiles[1].deleteFile(); this.tabTestFiles[2].deleteFile(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/bc/000077500000000000000000000000001241116057200262065ustar00rootroot00000000000000BouncyCastleCertProcessingFactoryTest.java000066400000000000000000000150601241116057200364320ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/bc/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.bc; import java.util.Set; import java.security.cert.X509Certificate; import org.globus.gsi.GlobusCredential; import org.globus.gsi.GSIConstants; import org.globus.gsi.X509ExtensionSet; import org.globus.gsi.X509Extension; import org.globus.gsi.bc.BouncyCastleCertProcessingFactory; import org.globus.gsi.bc.BouncyCastleX509Extension; import org.globus.gsi.proxy.ext.ProxyPolicy; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.globus.gsi.proxy.ext.ProxyCertInfoExtension; import org.bouncycastle.asn1.ASN1Boolean; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.DERBoolean; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.X509Extensions; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; public class BouncyCastleCertProcessingFactoryTest extends TestCase { private String proxyFile = "validatorTest/gsi2fullproxy.pem"; public static BouncyCastleCertProcessingFactory factory = BouncyCastleCertProcessingFactory.getDefault(); public BouncyCastleCertProcessingFactoryTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(BouncyCastleCertProcessingFactoryTest.class); } public void testResctrictedNoProxyCertInfoExt() throws Exception { ClassLoader loader = BouncyCastleCertProcessingFactoryTest.class.getClassLoader(); GlobusCredential cred = new GlobusCredential(loader.getResource(proxyFile).getPath()); try { factory.createCredential(cred.getCertificateChain(), cred.getPrivateKey(), 512, 60 * 60, GSIConstants.GSI_3_RESTRICTED_PROXY, (X509ExtensionSet)null, null); fail("Expected to fail"); } catch (IllegalArgumentException e) { // that's what we expected } } public void testResctrictedWithOtherExt() throws Exception { ClassLoader loader = BouncyCastleCertProcessingFactoryTest.class.getClassLoader(); GlobusCredential cred = new GlobusCredential(loader.getResource(proxyFile).getPath()); X509Extension ext = null; String oid = "1.2.3.4"; String expectedValue = "foo"; boolean critical = false; String policyOid = "1.2.3.4.5.6.7.8.9"; String policyValue = "bar"; X509ExtensionSet extSet = new X509ExtensionSet(); ext = new X509Extension(oid, critical, expectedValue.getBytes()); extSet.add(ext); DERSequence seq = new DERSequence(new ASN1Encodable[] { DERBoolean.FALSE, new ASN1Integer(15) }); BasicConstraints constraints = BasicConstraints.getInstance(seq); ext = new BouncyCastleX509Extension(org.bouncycastle.asn1.x509.X509Extension.basicConstraints.getId(), false, constraints); extSet.add(ext); ProxyPolicy policy = new ProxyPolicy(policyOid, policyValue.getBytes()); ext = new ProxyCertInfoExtension(new ProxyCertInfo(policy)); extSet.add(ext); GlobusCredential newCred = factory.createCredential(cred.getCertificateChain(), cred.getPrivateKey(), 512, 60 * 60, GSIConstants.GSI_3_RESTRICTED_PROXY, extSet, null); X509Certificate newCert = newCred.getCertificateChain()[0]; verifyExtension(newCert, oid, expectedValue, critical); byte [] realValue = BouncyCastleUtil.getExtensionValue(newCert, ProxyCertInfo.OID.getId()); assertTrue(realValue != null && realValue.length > 0); ProxyCertInfo proxyCertInfo = ProxyCertInfo.getInstance(realValue); assertTrue(proxyCertInfo != null); assertTrue(proxyCertInfo.getProxyPolicy() != null); assertEquals(policyOid, proxyCertInfo.getProxyPolicy().getPolicyLanguage().getId()); assertEquals(policyValue, proxyCertInfo.getProxyPolicy().getPolicyAsString()); } public void testExtensions() throws Exception { ClassLoader loader = BouncyCastleCertProcessingFactoryTest.class.getClassLoader(); GlobusCredential cred = new GlobusCredential(loader.getResource(proxyFile).getPath()); X509Extension ext = null; String oid1 = "1.2.3.4"; String expectedValue1 = "foo"; boolean critical1 = false; // COMMENT Used to be 5.6.7.8. Didn't work with newer bouncy castle version String oid2 = "1.2.3.5"; String expectedValue2 = "bar"; boolean critical2 = true; X509ExtensionSet extSet = new X509ExtensionSet(); ext = new X509Extension(oid1, critical1, expectedValue1.getBytes()); extSet.add(ext); ext = new X509Extension(oid2, critical2, expectedValue2.getBytes()); extSet.add(ext); GlobusCredential newCred = factory.createCredential(cred.getCertificateChain(), cred.getPrivateKey(), 512, 60 * 60, GSIConstants.GSI_3_IMPERSONATION_PROXY, extSet, null); X509Certificate newCert = newCred.getCertificateChain()[0]; verifyExtension(newCert, oid1, expectedValue1, critical1); verifyExtension(newCert, oid2, expectedValue2, critical2); } private void verifyExtension(X509Certificate cert, String oid, String expectedValue, boolean critical) throws Exception { byte [] realValue = BouncyCastleUtil.getExtensionValue(cert, oid); assertTrue(realValue != null && realValue.length > 0); assertEquals(expectedValue, new String(realValue)); Set exts = null; if (critical) { exts = cert.getCriticalExtensionOIDs(); } else { exts = cert.getNonCriticalExtensionOIDs(); } assertTrue(exts.contains(oid)); } } BouncyCastleOpenSSLKeyTest.java000066400000000000000000000070271241116057200341100ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/bc/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.bc; import org.globus.gsi.CertUtil; import java.security.Provider; import java.security.Security; import org.globus.common.CoGProperties; import java.security.KeyPairGenerator; import java.security.KeyPair; import java.io.StringWriter; import java.io.ByteArrayInputStream; import org.globus.gsi.OpenSSLKey; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class BouncyCastleOpenSSLKeyTest extends TestCase { private static final String pwd = "testpwd"; private Log logger = LogFactory.getLog(BouncyCastleOpenSSLKeyTest.class); private KeyPair getKeyPair() throws Exception { CertUtil.init(); int bits = 512; KeyPairGenerator keyGen = null; keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(bits); return keyGen.genKeyPair(); } public void testEncrypt() throws Exception { KeyPair keyPair = getKeyPair(); OpenSSLKey key = new BouncyCastleOpenSSLKey(keyPair.getPrivate()); assertTrue(!key.isEncrypted()); key.encrypt(pwd); assertTrue(key.isEncrypted()); } public void testEncryptAES() throws Exception { KeyPair keyPair = getKeyPair(); OpenSSLKey key = new BouncyCastleOpenSSLKey(keyPair.getPrivate()); assertTrue(!key.isEncrypted()); key.setEncryptionAlgorithm("AES-128-CBC"); key.encrypt(pwd); assertTrue(key.isEncrypted()); } private String toString(OpenSSLKey key) throws Exception { StringWriter writer = new StringWriter(); key.writeTo(writer); writer.close(); String s = writer.toString(); logger.debug(s); return s; } public void testDecryptedToString() throws Exception { KeyPair keyPair = getKeyPair(); OpenSSLKey inKey = new BouncyCastleOpenSSLKey(keyPair.getPrivate()); assertTrue(!inKey.isEncrypted()); ByteArrayInputStream in = null; in = new ByteArrayInputStream(toString(inKey).getBytes()); OpenSSLKey outKey = new BouncyCastleOpenSSLKey(in); assertTrue(!outKey.isEncrypted()); in = new ByteArrayInputStream(toString(outKey).getBytes()); OpenSSLKey outKey2 = new BouncyCastleOpenSSLKey(in); assertTrue(!outKey2.isEncrypted()); } public void testEcryptedToString() throws Exception { KeyPair keyPair = getKeyPair(); OpenSSLKey inKey = new BouncyCastleOpenSSLKey(keyPair.getPrivate()); assertTrue(!inKey.isEncrypted()); inKey.encrypt(pwd); assertTrue(inKey.isEncrypted()); ByteArrayInputStream in = null; in = new ByteArrayInputStream(toString(inKey).getBytes()); OpenSSLKey outKey = new BouncyCastleOpenSSLKey(in); assertTrue(outKey.isEncrypted()); in = new ByteArrayInputStream(toString(outKey).getBytes()); OpenSSLKey outKey2 = new BouncyCastleOpenSSLKey(in); assertTrue(outKey2.isEncrypted()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/bc/BouncyCastleUtilTest.java000066400000000000000000000130571241116057200331500ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.bc; import org.globus.gsi.util.CertificateLoadUtil; import java.io.InputStream; import org.globus.gsi.proxy.ProxyPathValidatorTest; import java.io.ByteArrayInputStream; import java.security.cert.X509Certificate; import java.security.cert.CertificateException; import org.globus.gsi.GSIConstants; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.bc.BouncyCastleUtil; import junit.framework.TestCase; public class BouncyCastleUtilTest extends TestCase { static String [] badCerts = ProxyPathValidatorTest.badCerts; private X509Certificate getCertificate(int i) throws Exception { ClassLoader loader = ProxyPathValidatorTest.class.getClassLoader(); String name = ProxyPathValidatorTest.BASE + ProxyPathValidatorTest.certs[i][1]; InputStream in = loader.getResourceAsStream(name); if (in == null) { throw new Exception("Unable to load: " + name); } return CertificateLoadUtil.loadCertificate(in); } public void testGetCertificateType() throws Exception { for (int i=0;i policies = filePolicy.getSigningPolicies(); assert (policies != null); assert (policies.size() == 2); // assert policy values here assertFalse(filePolicy.hasChanged()); policies = filePolicy.getSigningPolicies(); assert (policies != null); assertFalse(filePolicy.hasChanged()); testPolicy1.modifyFile(); policies = filePolicy.getSigningPolicies(); assert (policies != null); assertTrue(filePolicy.hasChanged()); } // @Test // public void testPolicyFilter() { // // FilenameFilter filter = new SigningPolicyFilter(); // // // Null checks // boolean worked = false; // try { // filter.accept(null, null); // } catch (IllegalArgumentException e) { // worked = true; // } // assert worked; // // // null dir name // assert (filter.accept(null, "foo.signing_policy")); // // // dir name ignored // assert (filter.accept(new File("bar"), "foo.signing_policy")); // // assertFalse(filter.accept(null, "foo.r")); // // assertFalse(filter.accept(null, "foo.SIGNING_POLICY")); // // assertFalse(filter.accept(null, "foo.signing")); // // } @After public void tearDown() throws Exception { this.testPolicy1.deleteFile(); } } TestFileBasedTrustAnchor.java000066400000000000000000000072031241116057200352570ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/filestore/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.filestore; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.globus.gsi.stores.ResourceTrustAnchor; import org.globus.gsi.testutils.FileSetupUtil; import java.io.File; import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import org.globus.common.CoGProperties; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class TestFileBasedTrustAnchor { FileSetupUtil testCert1; @Before public void setUp() throws Exception { CoGProperties.getDefault().setProperty(CoGProperties.CRL_CACHE_LIFETIME, "1"); CoGProperties.getDefault().setProperty(CoGProperties.CERT_CACHE_LIFETIME, "1"); this.testCert1 = new FileSetupUtil("certificateUtilTest/1c3f2ca8.0"); } @Test public void testGetTrustAnchor() throws Exception { this.testCert1.copyFileToTemp(); String tempFileURL = this.testCert1.getURL().toExternalForm(); ResourceTrustAnchor fileAnchor = new ResourceTrustAnchor("classpath:/certificateUtilTest/1c3f2ca8.0"); // assert (fileAnchor != null); TrustAnchor anchor = fileAnchor.getSecurityObject(); assert (anchor != null); X509Certificate cert = anchor.getTrustedCert(); assert (cert != null); assertFalse(fileAnchor.hasChanged()); anchor = fileAnchor.getSecurityObject(); assert (anchor != null); assertFalse(fileAnchor.hasChanged()); fileAnchor = new ResourceTrustAnchor(tempFileURL); this.testCert1.modifyFile(); anchor = fileAnchor.getSecurityObject(); assert (anchor != null); assertTrue(fileAnchor.hasChanged()); } // @Test // public void testGetTrustAnchorFilter() { // // FilenameFilter filter = new TrustAnchorFilter(); // // // Null checks // boolean worked = false; // try { // filter.accept(null, null); // } catch (IllegalArgumentException e) { // worked = true; // } // assert worked; // // // null dir name // assert (filter.accept(null, "foo.1")); // // // dir name ignored // assert (filter.accept(new File("bar"), "foo.9")); // // // only single digit at end // assertFalse(filter.accept(null, "foo.10")); // // // only single digit at end // assertFalse(filter.accept(null, "foo.bar")); // // // the most common usage. *.0 // assertTrue(filter.accept(null, "foo.0")); // // } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] dirContent = dir.list(); for (int i=0; i trustAnchors; @BeforeClass public static void setUp() throws Exception { // JGLOBUS-103 dir = new DirSetupUtil(new String[] { "testTrustStore/1c3f2ca8.0", "testTrustStore/b38b4d8c.0", "testTrustStore/d1b603c3.0", "testTrustStore/1c3f2ca8.r0", "testTrustStore/d1b603c3.r0", "testTrustStore/1c3f2ca8.signing_policy", "testTrustStore/b38b4d8c.signing_policy", "testTrustStore/d1b603c3.signing_policy" }); dir.createTempDirectory(); dir.copy(); parameters = new ResourceCertStoreParameters("classpath:/testTrustStore/*.0,classpath:/testTrustStore/*.9", null); crlParameters = new ResourceCertStoreParameters(null, "classpath:/testTrustStore/*.r*"); policyParameters = new ResourceSigningPolicyStoreParameters("classpath:/testTrustStore/*.signing_policy"); directoryParameters = new ResourceCertStoreParameters("file:" + dir.getTempDirectory().getAbsolutePath() + "/*.0", null); Security.addProvider(new GlobusProvider()); } @Test public void testEngineGetCertificates() throws Exception { certStore = CertStore.getInstance("PEMFilebasedCertStore", parameters); assert certStore != null; trustAnchors = certStore.getCertificates(new X509CertSelector()); assert trustAnchors != null; assertTrue(trustAnchors.size() > 0); // assert caFiles != null; assertThat(trustAnchors.size(), is(3)); for (Certificate trustAnchor : trustAnchors) { assert (trustAnchor instanceof X509Certificate); } // JGLOBUS-103 } @Test public void testEngineGetCertificatesDirectory() throws Exception { File tempDir = this.dir.getTempDirectory(); // number of CA files // String[] caFiles = tempDir.list(new TrustAnchorFilter()); this.certStore = CertStore.getInstance("PEMFilebasedCertStore", directoryParameters); assert certStore != null; this.trustAnchors = certStore.getCertificates(new X509CertSelector()); assert trustAnchors != null; assertTrue(trustAnchors.size() > 0); // assert caFiles != null; assertTrue(trustAnchors.size() == 3); for (Certificate trustAnchor : trustAnchors) { assertThat(trustAnchor, instanceOf(X509Certificate.class)); } } public static class CrlFilter implements FilenameFilter { public boolean accept(File dir, String file) { if (file == null) { throw new IllegalArgumentException(); } int length = file.length(); return length > 3 && file.charAt(length - 3) == '.' && file.charAt(length - 2) == 'r' && file.charAt(length - 1) >= '0' && file.charAt(length - 1) <= '9'; } } @Test public void testEngineGetCRLs() throws Exception { File tempDir = dir.getTempDirectory(); // number of CRL files String[] crlFiles = tempDir.list(new CrlFilter()); // Get comparison parameters certStore = CertStore.getInstance("PEMFilebasedCertStore", crlParameters); assert certStore != null; Collection crls = certStore.getCRLs(null); assertThat(crls, not(nullValue())); assertTrue(crls.size() > 0); assert crlFiles != null; assertThat(crls.size(), is(crlFiles.length)); for (CRL crl : crls) { assertThat(crl, instanceOf(X509CRL.class)); } // JGLOBUS-103 } @Test public void testGetSigningPolicies() throws Exception { SigningPolicyStore store = new ResourceSigningPolicyStore(policyParameters); SigningPolicy policy = store.getSigningPolicy(null); assert (policy == null); policy = store.getSigningPolicy(new X500Principal("C=US, CN=Foo")); assert (policy == null); for (Certificate trustAnchor : trustAnchors) { X509Certificate certificate = (X509Certificate) trustAnchor; X500Principal principal = certificate.getIssuerX500Principal(); policy = store.getSigningPolicy(principal); assert (policy != null); assert (policy.getAllowedDNs() != null); } // JGLOBUS-103 } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] dirContent = dir.list(); for (int i=0; i 2 && file.charAt(length - 2) == '.' && file.charAt(length - 1) >= '0' && file.charAt(length - 1) <= '9'; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/gridmap/000077500000000000000000000000001241116057200272455ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/gridmap/GridMapTest.java000066400000000000000000000226261241116057200323030ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.gridmap; import org.globus.gsi.gridmap.GridMap; import org.globus.gsi.gridmap.GridMapLocal; import java.io.ByteArrayInputStream; import java.io.IOException; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class GridMapTest extends TestCase { private Log logger = LogFactory.getLog(GridMapTest.class); private static final String GRIDMAP_1 = "\"/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Katarzyna (Kate) Keahey\" keahey,kate\r\n" + "# this is a comment\r\n" + " \r\n" + "\"/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak\" dvorak2\r\n" + "\"/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak\" dvorak\n" + "\"/DC=org/DC=doe grids/OU=People/UID=32845324/Email=john@doe.com/E=john@doe.com\" jdoe,doej\n" + "\"/DC=org/DC=doe grids/OU=People/UID=3284532/USERID=7878/UID=8989/E=john@doe.com\" john_doe\n" + "\"/DC=org/DC=doe grids/OU=People/UID=32845/Email=john@doe.com/Email=another@doe.edu\" doe\n" + "\"/DC=org/DC=doegrids/OU=Services/Email=admin@mcs/CN=host/effable.mcs.anl.gov\" host\n" + "user1DN user1\n" + "\ttestDN\tuser1\n"; private static final String GRIDMAP_2 = "\"/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Katarzyna (Kate) Keahey\"\r\n" + "# this is a comment\r\n" + " \r\n" + "\"/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak\" dvorak\r\n" + "dvorak\n"; private static final String GRIDMAP_3 = "\"/O=myCA/CN=\\\"Foo Bar\\\"\" account\r\n"; private static final String GRIDMAP_4 = "/C=DE/ST=Baden-Württemberg/O=University of Stuttgart/OU=HLRS/CN=Oliver Mangold/E=o.mangold@gmx.de test1"; public void test1() { GridMap map = new GridMap(); try { map.load(new ByteArrayInputStream(GRIDMAP_4.getBytes())); logger.debug("Test 1 " + map.getUserID("test1")); assertTrue(map.load(new ByteArrayInputStream(GRIDMAP_1.getBytes()))); } catch (IOException e) { fail(e.getMessage()); return; } assertEquals("user1", map.getUserID("user1DN")); assertEquals("user1", map.getUserID("testDN")); assertEquals("keahey", map.getUserID("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Katarzyna (Kate) Keahey")); assertEquals("dvorak2", map.getUserID("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak")); assertEquals(null, map.getUserID("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Jarek Gawor")); assertEquals("jdoe", map .getUserID("/DC=org/DC=doe grids/OU=People/UID=32845324/Email=john@doe.com/E=john@doe.com")); assertEquals("jdoe", map .getUserID("/DC=org/DC=doe grids/OU=People/USERID=32845324/Email=john@doe.com/E=john@doe.com")); assertEquals("john_doe", map .getUserID("/DC=org/DC=doe grids/OU=People/UID=3284532/USERID=7878/UID=8989/E=john@doe.com")); assertEquals("john_doe", map .getUserID("/DC=org/DC=doe grids/OU=People/UID=3284532/UID=7878/UID=8989/E=john@doe.com")); assertEquals("john_doe", map .getUserID("/DC=org/DC=doe grids/OU=People/UID=3284532/USERID=7878/UID=8989/EMAIL=john@doe.com")); assertEquals("doe", map .getUserID("/DC=org/DC=doe grids/OU=People/UID=32845/Email=john@doe.com/e=another@doe.edu")); assertEquals("doe", map .getUserID("/DC=org/DC=doe grids/OU=People/UID=32845/e=john@doe.com/Email=another@doe.edu")); assertEquals("host", map .getUserID("/DC=org/DC=doegrids/OU=Services/Email=admin@mcs/CN=host/effable.mcs.anl.gov")); String[] rs = null; String[] expected = null; rs = map.getUserIDs("/DC=org/DC=doe grids/OU=People/UID=32845324/Email=john@doe.com/E=john@doe.com"); expected = new String[] { "jdoe", "doej" }; assertEquals(expected.length, rs.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], rs[i]); } rs = map.getUserIDs("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Katarzyna (Kate) Keahey"); expected = new String[] { "keahey", "kate" }; assertEquals(expected.length, rs.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], rs[i]); } rs = map.getUserIDs("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak"); expected = new String[] { "dvorak2", "dvorak" }; assertEquals(expected.length, rs.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], rs[i]); } } public void testLocalLookup() { GridMap map = new GridMapLocal(); String username = System.getProperty("user.name"); assertEquals(username, map.getUserID("whatever")); System.setProperty("user.name", "ROot"); assertEquals(null, map.getUserID("whatever")); System.setProperty("user.name", "AdminISTRATOR"); assertEquals(null, map.getUserID("whatever")); System.setProperty("user.name", username); assertEquals(username, map.getUserID("whatever2")); } public void test3() { GridMap map = new GridMap(); try { map.load(new ByteArrayInputStream(GRIDMAP_1.getBytes())); } catch (IOException e) { fail(e.getMessage()); return; } assertEquals(true, map.checkUser("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Katarzyna (Kate) Keahey", "keahey")); assertEquals(true, map.checkUser("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Katarzyna (Kate) Keahey", "kate")); assertEquals(true, map.checkUser("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak", "dvorak")); assertEquals(false, map.checkUser("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak", "dvorakkkkk")); assertEquals(false, map.checkUser("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorakkkk", "dvorak")); assertEquals(false, map.checkUser("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Jarek Gawor", "gawor")); } public void test4() { GridMap map = new GridMap(); try { map.load(new ByteArrayInputStream(GRIDMAP_1.getBytes())); } catch (IOException e) { fail(e.getMessage()); return; } assertEquals("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak", map.getGlobusID("dvorak")); assertEquals("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Katarzyna (Kate) Keahey", map.getGlobusID("keahey")); assertEquals("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Katarzyna (Kate) Keahey", map.getGlobusID("kate")); assertEquals(null, map.getGlobusID("gawor")); } public void test5() { GridMap map = new GridMap(); try { map.load(new ByteArrayInputStream(GRIDMAP_1.getBytes())); } catch (IOException e) { fail(e.getMessage()); return; } map.map("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Jarek Gawor", "gawor"); assertEquals("gawor", map.getUserID("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Jarek Gawor")); map.map("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak", "dvorak2"); assertEquals(true, map.checkUser("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak", "dvorak")); assertEquals(true, map.checkUser("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak", "dvorak2")); } public void testIgnoreErrors() { GridMap map = new GridMap(); try { map.load(new ByteArrayInputStream(GRIDMAP_2.getBytes())); fail("did not throw exception"); } catch (IOException e) { } assertTrue(map.getUserID("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak") == null); map.setIgnoreErrors(false); try { map.load(new ByteArrayInputStream(GRIDMAP_2.getBytes())); fail("did not throw exception"); } catch (IOException e) { } assertTrue(map.getUserID("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak") == null); map.setIgnoreErrors(true); try { assertFalse(map.load(new ByteArrayInputStream(GRIDMAP_2.getBytes()))); } catch (IOException e) { e.printStackTrace(); fail("Unexpected error"); } assertEquals("dvorak", map.getUserID("/O=Grid/O=Globus/OU=mcs.anl.gov/CN=Michael Dvorak")); } public void test6() throws Exception { GridMap map = new GridMap(); try { map.load(new ByteArrayInputStream(GRIDMAP_3.getBytes())); } catch (IOException e) { fail(e.getMessage()); return; } assertTrue((map.getAllGlobusID("account").length) == 1); String[] globusId = map.getAllGlobusID("account"); logger.debug("** " + globusId[0]); assertEquals("account", map.getUserID("/O=myCA/CN=\"Foo Bar\"")); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/000077500000000000000000000000001241116057200274545ustar00rootroot00000000000000FileBasedKeyStoreTest.java000066400000000000000000000043371241116057200344130ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import org.globus.gsi.stores.PEMKeyStore; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; import org.globus.util.GlobusPathMatchingResourcePatternResolver; import org.junit.Test; /** * Created by IntelliJ IDEA. * User: turtlebender * Date: Dec 30, 2009 * Time: 1:01:14 PM * To change this template use File | Settings | File Templates. */ public class FileBasedKeyStoreTest { private PEMKeyStore keystore = new PEMKeyStore(); private GlobusPathMatchingResourcePatternResolver globusResolver = new GlobusPathMatchingResourcePatternResolver(); private Log logger = LogFactory.getLog(FileBasedKeyStoreTest.class.getCanonicalName()); @Test public void testIO() throws Exception { InputStream is; ByteArrayOutputStream os; Properties props = new Properties(); props.put(PEMKeyStore.KEY_FILENAME, "classpath:/key.pem"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); props.store(baos, "sample"); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); keystore.engineLoad(bais, null); Enumeration en = keystore.engineAliases(); while (en.hasMoreElements()) { logger.debug("en.nextElement().toString() = " + en.nextElement().toString()); } os = new ByteArrayOutputStream(); // keystore.engineStore(os, null); // keystore.engineStore(os, password); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/MockCertStore.java000066400000000000000000000134451241116057200330520ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import java.security.InvalidAlgorithmParameterException; import java.security.cert.CRL; import java.security.cert.CRLSelector; import java.security.cert.CertSelector; import java.security.cert.CertStoreException; import java.security.cert.CertStoreParameters; import java.security.cert.CertStoreSpi; import java.security.cert.Certificate; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.List; import java.util.Vector; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class MockCertStore extends CertStoreSpi { private Vector certificate = new Vector(); private Vector crl = new Vector(); public MockCertStore(CertStoreParameters param) throws InvalidAlgorithmParameterException { super(param); if (param != null) { if (param instanceof TestProxyPathValidator.TestCertParameters) { TestProxyPathValidator.TestCertParameters parameters = (TestProxyPathValidator.TestCertParameters) param; X509Certificate[] certs = parameters.getCertificates(); if (certs != null) { for (int i = 0; i < certs.length; i++) { this.certificate.add(certs[i]); } } X509CRL[] crls = parameters.getCRLs(); if (crls != null) { for (int i = 0; i < crls.length; i++) { this.crl.add(crls[i]); } } } } } /** * Returns a Collection of Certificates that match * the specified selector. If no Certificates match the * selector, an empty Collection will be returned. *

    * For some CertStore types, the resulting * Collection may not contain all of the * Certificates that match the selector. For instance, an LDAP * CertStore may not search all entries in the directory. * Instead, it may just search entries that are likely to contain the * Certificates it is looking for. *

    * Some CertStore implementations (especially LDAP * CertStores) may throw a CertStoreException * unless a non-null CertSelector is provided that includes * specific criteria that can be used to find the certificates. Issuer * and/or subject names are especially useful criteria. * * @param selector A CertSelector used to select which * Certificates should be returned. Specify * null to return all Certificates * (if supported). * @return A Collection of Certificates that match * the specified selector (never null) * @throws java.security.cert.CertStoreException * if an exception occurs */ public Collection engineGetCertificates( CertSelector selector) throws CertStoreException { // For test, unsupported throw new UnsupportedOperationException(); } /** * Returns a Collection of CRLs that match the * specified selector. If no CRLs match the selector, an empty * Collection will be returned. *

    * For some CertStore types, the resulting * Collection may not contain all of the * CRLs that match the selector. For instance, an LDAP * CertStore may not search all entries in the directory. * Instead, it may just search entries that are likely to contain the * CRLs it is looking for. *

    * Some CertStore implementations (especially LDAP * CertStores) may throw a CertStoreException * unless a non-null CRLSelector is provided that includes * specific criteria that can be used to find the CRLs. Issuer names and/or * the certificate to be checked are especially useful. * * @param selector A CRLSelector used to select which * CRLs should be returned. Specify * null to return all CRLs (if * supported). * @return A Collection of CRLs that match the * specified selector (never null) * @throws java.security.cert.CertStoreException * if an exception occurs */ public Collection engineGetCRLs(CRLSelector selector) throws CertStoreException { if (selector == null) { return this.crl; } List crlList = new Vector(); for (X509CRL aCrl : this.crl) { if (selector.match(aCrl)) { crlList.add(aCrl); } } return crlList; } }MockGlobusProvider.java000066400000000000000000000020171241116057200340200ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import java.security.Provider; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class MockGlobusProvider extends Provider { public MockGlobusProvider() { super("GlobusTest", 1.0, "Globus Security Providers"); put("CertStore.MockCertStore", MockCertStore.class.getCanonicalName()); put("KeyStore.MockKeyStore", MockKeyStore.class.getCanonicalName()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/MockKeyStore.java000066400000000000000000000327741241116057200327130ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.Key; import java.security.KeyStoreException; import java.security.KeyStoreSpi; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class MockKeyStore extends KeyStoreSpi { private Hashtable certificateMap = new Hashtable(); /** * Returns the key associated with the given alias, using the given password * to recover it. The key must have been associated with the alias by a * call to setKeyEntry, or by a call to setEntry * with a PrivateKeyEntry or SecretKeyEntry. * * @param alias the alias name * @param password the password for recovering the key * @return the requested key, or null if the given alias does not exist or * does not identify a key-related entry. * @throws java.security.NoSuchAlgorithmException * if the algorithm for recovering the key cannot be found * @throws java.security.UnrecoverableKeyException * if the key cannot be recovered (e.g., the given password is * wrong). */ public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { throw new UnsupportedOperationException(); } /** * Returns the certificate chain associated with the given alias. The * certificate chain must have been associated with the alias by a call to * setKeyEntry, or by a call to setEntry with a * PrivateKeyEntry. * * @param alias the alias name * @return the certificate chain (ordered with the user's certificate first * and the root certificate authority last), or null if the given * alias does not exist or does not contain a certificate chain */ public Certificate[] engineGetCertificateChain(String alias) { throw new UnsupportedOperationException(); } /** * Returns the certificate associated with the given alias. *

    *

    If the given alias name identifies an entry created by a call to * setCertificateEntry, or created by a call to * setEntry with a TrustedCertificateEntry, then * the trusted certificate contained in that entry is returned. *

    *

    If the given alias name identifies an entry created by a call to * setKeyEntry, or created by a call to setEntry * with a PrivateKeyEntry, then the first element of the * certificate chain in that entry (if a chain exists) is returned. * * @param alias the alias name * @return the certificate, or null if the given alias does not exist or * does not contain a certificate. */ public Certificate engineGetCertificate(String alias) { return this.certificateMap.get(alias); } /** * Returns the creation date of the entry identified by the given alias. * * @param alias the alias name * @return the creation date of this entry, or null if the given alias does * not exist */ public Date engineGetCreationDate(String alias) { throw new UnsupportedOperationException(); } /** * Assigns the given key to the given alias, protecting it with the given * password. *

    *

    If the given key is of type java.security.PrivateKey, it * must be accompanied by a certificate chain certifying the corresponding * public key. *

    *

    If the given alias already exists, the keystore information associated * with it is overridden by the given key (and possibly certificate chain). * * @param alias the alias name * @param key the key to be associated with the alias * @param password the password to protect the key * @param chain the certificate chain for the corresponding public key * (only required if the given key is of type * java.security.PrivateKey). * @throws java.security.KeyStoreException * if the given key cannot be protected, or this operation fails * for some other reason */ public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException { throw new UnsupportedOperationException(); } /** * Assigns the given key (that has already been protected) to the given * alias. *

    *

    If the protected key is of type java.security.PrivateKey, * it must be accompanied by a certificate chain certifying the * corresponding public key. *

    *

    If the given alias already exists, the keystore information associated * with it is overridden by the given key (and possibly certificate chain). * * @param alias the alias name * @param key the key (in protected format) to be associated with the * alias * @param chain the certificate chain for the corresponding public key (only * useful if the protected key is of type java.security.PrivateKey). * @throws java.security.KeyStoreException * if this operation fails. */ public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { throw new UnsupportedOperationException(); } /** * Assigns the given certificate to the given alias. *

    *

    If the given alias identifies an existing entry created by a call to * setCertificateEntry, or created by a call to * setEntry with a TrustedCertificateEntry, the * trusted certificate in the existing entry is overridden by the given * certificate. * * @param alias the alias name * @param cert the certificate * @throws java.security.KeyStoreException * if the given alias already exists and does not identify an entry * containing a trusted certificate, or this operation fails for * some other reason. */ public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { if (cert == null) { return; } if (cert instanceof X509Certificate) { this.certificateMap.put(alias, (X509Certificate) cert); } else { throw new IllegalArgumentException( "Certificate should be X509Cert"); } } /** * Deletes the entry identified by the given alias from this keystore. * * @param alias the alias name * @throws java.security.KeyStoreException * if the entry cannot be removed. */ public void engineDeleteEntry(String alias) throws KeyStoreException { this.certificateMap.remove(alias); } /** * Lists all the alias names of this keystore. * * @return enumeration of the alias names */ public Enumeration engineAliases() { return this.certificateMap.keys(); } /** * Checks if the given alias exists in this keystore. * * @param alias the alias name * @return true if the alias exists, false otherwise */ public boolean engineContainsAlias(String alias) { if (this.certificateMap.containsKey(alias)) { return true; } return false; } /** * Retrieves the number of entries in this keystore. * * @return the number of entries in this keystore */ public int engineSize() { return this.certificateMap.size(); } /** * Returns true if the entry identified by the given alias was created by a * call to setKeyEntry, or created by a call to * setEntry with a PrivateKeyEntry or a * SecretKeyEntry. * * @param alias the alias for the keystore entry to be checked * @return true if the entry identified by the given alias is a key-related, * false otherwise. */ public boolean engineIsKeyEntry(String alias) { return false; //CHANGEME To change body of implemented methods use File | Settings | File Templates. } /** * Returns true if the entry identified by the given alias was created by a * call to setCertificateEntry, or created by a call to * setEntry with a TrustedCertificateEntry. * * @param alias the alias for the keystore entry to be checked * @return true if the entry identified by the given alias contains a * trusted certificate, false otherwise. */ public boolean engineIsCertificateEntry(String alias) { if (engineContainsAlias(alias)) { return true; } return false; } /** * Returns the (alias) name of the first keystore entry whose certificate * matches the given certificate. *

    *

    This method attempts to match the given certificate with each keystore * entry. If the entry being considered was created by a call to * setCertificateEntry, or created by a call to * setEntry with a TrustedCertificateEntry, then * the given certificate is compared to that entry's certificate. *

    *

    If the entry being considered was created by a call to * setKeyEntry, or created by a call to setEntry * with a PrivateKeyEntry, then the given certificate is * compared to the first element of that entry's certificate chain. * * @param cert the certificate to match with. * @return the alias name of the first entry with matching certificate, or * null if no such entry exists in this keystore. */ public String engineGetCertificateAlias(Certificate cert) { throw new UnsupportedOperationException(); } /** * Stores this keystore to the given output stream, and protects its * integrity with the given password. * * @param stream the output stream to which this keystore is written. * @param password the password to generate the keystore integrity check * @throws java.io.IOException if there was an I/O problem with data * @throws java.security.NoSuchAlgorithmException * if the appropriate data integrity algorithm * could not be found * @throws java.security.cert.CertificateException * if any of the certificates included in the * keystore data could not be stored */ public void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { throw new UnsupportedOperationException(); } /** * Loads the keystore from the given input stream. *

    *

    A password may be given to unlock the keystore (e.g. the keystore * resides on a hardware token device), or to check the integrity of the * keystore data. If a password is not given for integrity checking, then * integrity checking is not performed. * * @param stream the input stream from which the keystore is loaded, or * null * @param password the password used to check the integrity of the keystore, * the password used to unlock the keystore, or * null * @throws java.io.IOException if there is an I/O or format problem with the * keystore data, if a password is required but * not given, or if the given password was * incorrect * @throws java.security.NoSuchAlgorithmException * if the algorithm used to check the integrity * of the keystore cannot be found * @throws java.security.cert.CertificateException * if any of the certificates in the keystore * could not be loaded */ public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { // To force keystore initialization // empty impl. } }TestPEMFileBasedKeyStore.java000066400000000000000000000406151241116057200347540ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.apache.commons.io.FileUtils; import org.globus.gsi.testutils.DirSetupUtil; import org.globus.gsi.testutils.FileSetupUtil; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.stores.PEMKeyStore; //import org.globus.gsi.stores.PEMKeyStoreParameters; import org.globus.gsi.X509Credential; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.provider.KeyStoreParametersFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.PrivateKey; import java.security.Security; import java.security.UnrecoverableKeyException; import java.security.KeyStore.LoadStoreParameter; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Vector; import org.globus.util.GlobusResource; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class TestPEMFileBasedKeyStore { DirSetupUtil trustedDirectory; DirSetupUtil defaultTrustedDirectory; Vector testTrustedCertificates = new Vector(); FileSetupUtil proxyFile1; FileSetupUtil proxyFile2; FileSetupUtil certFile; FileSetupUtil keyFile; FileSetupUtil keyEncFile; Map trustedCertificates = new HashMap(); Map proxyCertificates = new HashMap(); @Before public void setUp() throws Exception { ClassLoader loader = TestPEMFileBasedKeyStore.class.getClassLoader(); String[] trustedCertFilenames = new String[]{"testTrustStore/1c3f2ca8.0", "testTrustStore/b38b4d8c.0"}; this.trustedDirectory = new DirSetupUtil(trustedCertFilenames); this.trustedDirectory.createTempDirectory(); this.trustedDirectory.copy(); for (String trustedCertFilename : trustedCertFilenames) { InputStream in = null; try { in = loader.getResourceAsStream(trustedCertFilename); if (in == null) { throw new Exception("Unable to load: " + trustedCertFilename); } this.trustedCertificates.put(this.trustedDirectory.getFileSetupUtil(trustedCertFilename), CertificateLoadUtil.loadCertificate(in)); } finally { if (in != null) { in.close(); } } } String[] defaultTrustedCert = new String[]{"testTrustStore/d1b603c3.0"}; this.defaultTrustedDirectory = new DirSetupUtil(defaultTrustedCert); this.defaultTrustedDirectory.createTempDirectory(); this.defaultTrustedDirectory.copy(); for (String aDefaultTrustedCert : defaultTrustedCert) { InputStream in = null; try { in = loader.getResourceAsStream(aDefaultTrustedCert); if (in == null) { throw new Exception("Unable to load: " + aDefaultTrustedCert); } this.trustedCertificates.put( this.defaultTrustedDirectory.getFileSetupUtil(aDefaultTrustedCert), CertificateLoadUtil.loadCertificate(in)); } finally { if (in != null) { in.close(); } } } // String proxyFilename1 = "validatorTest/gsi2fullproxy.pem"; String proxyFilename1 = "validatorTest/gsi3independentFromLimitedProxy.pem"; this.proxyFile1 = new FileSetupUtil(proxyFilename1); this.proxyFile1.copyFileToTemp(); this.proxyCertificates.put(this.proxyFile1, new X509Credential(loader.getResourceAsStream(proxyFilename1), loader.getResourceAsStream(proxyFilename1))); String proxyFilename2 = "validatorTest/gsi3FromPathOneProxy.pem"; this.proxyFile2 = new FileSetupUtil(proxyFilename2); this.proxyFile2.copyFileToTemp(); this.proxyCertificates.put(this.proxyFile2, new X509Credential(loader.getResourceAsStream(proxyFilename2), loader.getResourceAsStream(proxyFilename2))); String certFilename = "validatorTest/testeec2.pem"; this.certFile = new FileSetupUtil(certFilename); this.certFile.copyFileToTemp(); String keyFilename = "validatorTest/testeec2-private.pem"; this.keyFile = new FileSetupUtil(keyFilename); this.keyFile.copyFileToTemp(); String keyEncFilename = "validatorTest/testeec2-private-enc.pem"; this.keyEncFile = new FileSetupUtil(keyEncFilename); this.keyEncFile.copyFileToTemp(); Security.addProvider(new GlobusProvider()); } @Test public void testCreationDate() throws Exception { KeyStore store = KeyStore.getInstance("PEMFilebasedKeyStore", "Globus"); // Parameters in properties file Properties properties = new Properties(); properties.setProperty(PEMKeyStore.DEFAULT_DIRECTORY_KEY, "file:"+ this.defaultTrustedDirectory.getTempDirectoryName()); properties.setProperty(PEMKeyStore.DIRECTORY_LIST_KEY, "file:" + this.trustedDirectory.getTempDirectoryName() + "/*.0"); InputStream ins = null; try { ins = getProperties(properties); store.load(ins, null); } finally { if (ins != null) { ins.close(); } } Enumeration aliases = store.aliases(); if (aliases.hasMoreElements()) { String alias = aliases.nextElement(); assertNotNull(store.getCreationDate(alias)); } assertNull(store.getCreationDate("FakeAlias")); } @Test public void testTrustedCerts() throws Exception { PEMKeyStore store = new PEMKeyStore(); // Parameters in properties file Properties properties = new Properties(); properties.setProperty(PEMKeyStore.DEFAULT_DIRECTORY_KEY, "file:" + this.defaultTrustedDirectory.getTempDirectoryName()); properties.setProperty(PEMKeyStore.DIRECTORY_LIST_KEY, "file:" + this.trustedDirectory.getTempDirectoryName() + "/*.0"); InputStream ins = null; try { ins = getProperties(properties); store.engineLoad(ins, null); } finally { if (ins != null) { ins.close(); } } testLoadedStore(store); Iterator iterator = this.trustedCertificates.keySet().iterator(); FileSetupUtil util = iterator.next(); testDelete(store, util.getTempFilename(), util); } @Test public void testParameterLoad() throws Exception { PEMKeyStore keystore = loadFromParameters(); testLoadedStore(keystore); } private PEMKeyStore loadFromParameters() throws Exception { LoadStoreParameter params = KeyStoreParametersFactory.createTrustStoreParameters( "file:" + this.trustedDirectory.getTempDirectoryName(), "file:" + this.defaultTrustedDirectory.getTempDirectoryName() ); PEMKeyStore keystore = new PEMKeyStore(); keystore.engineLoad(params); return keystore; } private void testLoadedStore(PEMKeyStore store) throws KeyStoreException { Enumeration aliases = store.engineAliases(); assertTrue(aliases.hasMoreElements()); // alias to certificate test to be added. Iterator iterator = this.trustedCertificates.keySet().iterator(); String alias; FileSetupUtil util; while (iterator.hasNext()) { util = iterator.next(); alias = util.getTempFile().toURI().toASCIIString(); assertTrue(store.engineIsCertificateEntry(alias)); Certificate certificate = store.engineGetCertificate(alias); assertNotNull(certificate); assertEquals(certificate, this.trustedCertificates.get(util)); String storeAlias = store.engineGetCertificateAlias(certificate); assertEquals(alias, storeAlias); } assertFalse(store.engineIsCertificateEntry("FakeCert")); } private void testDelete(PEMKeyStore store, String alias, FileSetupUtil util) throws Exception { // test delete store.engineDeleteEntry(alias); assertNull(store.engineGetCertificate(alias)); assertNotNull(util); File tempFile = util.getTempFile(); assertNotNull(tempFile); } @Test public void testProxyCerts() throws Exception { PEMKeyStore store = new PEMKeyStore(); // Parameters in properties file Properties properties = new Properties(); properties.setProperty(PEMKeyStore.PROXY_FILENAME, "file:"+ this.proxyFile1.getAbsoluteFilename()); InputStream ins = null; try { ins = getProperties(properties); store.engineLoad(ins, null); } finally { if (ins != null) { ins.close(); } } Enumeration aliases = store.engineAliases(); assert (aliases.hasMoreElements()); // proxy file 1 String proxyId1 = new GlobusResource(this.proxyFile1.getTempFile().getAbsolutePath()).getFile().toString();//getURL().toExternalForm(); Key key = store.engineGetKey("file:"+ this.proxyFile1.getAbsoluteFilename(), null); assertTrue(store.engineIsKeyEntry("file:"+ this.proxyFile1.getAbsoluteFilename())); assertNotNull(key != null); assertTrue(key instanceof PrivateKey); Certificate[] certificates = store.engineGetCertificateChain(this.proxyFile1.getURL().toExternalForm()); assertNotNull(certificates != null); assertTrue(certificates instanceof X509Certificate[]); key = null; // assert (this.proxyCertificates.get(this.proxyFile1.getAbsoluteFilename()).equals(certificates[0])); properties.setProperty(PEMKeyStore.PROXY_FILENAME, "file:" + this.proxyFile2.getAbsoluteFilename()); ins = null; try { ins = getProperties(properties); store.engineLoad(ins, null); } finally { if (ins != null) { ins.close(); } } // proxy file 2 String proxyId2 = new GlobusResource(this.proxyFile2.getTempFile().getAbsolutePath()).getURL().toExternalForm(); key = store.engineGetKey("file:" + this.proxyFile2.getAbsoluteFilename(), null); assertTrue(store.engineIsKeyEntry("file:" + this.proxyFile2.getAbsoluteFilename())); assertNotNull(key); assertTrue(key instanceof PrivateKey); certificates = store.engineGetCertificateChain(proxyId1); assertNotNull(certificates != null); assertTrue(certificates instanceof X509Certificate[]); // assert (this.proxyCertificates.get(this.proxyFile2.getTempFilename()).equals(certificates[0])); // test delete store.engineDeleteEntry(proxyId1); certificates = store.engineGetCertificateChain(proxyId1); assertEquals(0, certificates.length); assertFalse((new File("file:"+ this.proxyFile1.getAbsoluteFilename())).exists()); assertFalse(store.engineIsKeyEntry(proxyId1)); } @Test public void testUserCerts() throws Exception { PEMKeyStore store = new PEMKeyStore(); // Parameters in properties file Properties properties = new Properties(); properties.setProperty(PEMKeyStore.CERTIFICATE_FILENAME, new GlobusResource( this.certFile.getTempFile().getAbsolutePath()).getURL().toExternalForm()); properties.setProperty(PEMKeyStore.KEY_FILENAME, new GlobusResource(this.keyFile.getTempFile().getAbsolutePath()) .getURL().toExternalForm()); InputStream ins = null; try { ins = getProperties(properties); store.engineLoad(ins, null); } finally { if (ins != null) { ins.close(); } } Enumeration aliases = store.engineAliases(); assertTrue(aliases.hasMoreElements()); String alias = (String) aliases.nextElement(); Key key = store.engineGetKey(alias, null); assertNotNull(key); assertTrue(key instanceof PrivateKey); Certificate[] chain = store.engineGetCertificateChain(alias); assertNotNull(chain); Certificate certificate = store.engineGetCertificate(alias); assertNull(certificate); X509Credential x509Credential = new X509Credential(new FileInputStream(this.certFile.getAbsoluteFilename()), new FileInputStream(this.keyFile.getAbsoluteFilename())); assertEquals(key, x509Credential.getPrivateKey()); Certificate[] x509CredentialChain = x509Credential.getCertificateChain(); assertEquals(chain.length, x509CredentialChain.length); for (int i = 0; i < chain.length; i++) { assert (chain[i].equals(x509CredentialChain[i])); } store = new PEMKeyStore(); properties.setProperty(PEMKeyStore.CERTIFICATE_FILENAME, new GlobusResource(this.certFile.getTempFile().getAbsolutePath()).getURL().toExternalForm()); properties.setProperty(PEMKeyStore.KEY_FILENAME, new GlobusResource(this.keyEncFile.getTempFile().getAbsolutePath()).getURL().toExternalForm()); try { ins = getProperties(properties); store.engineLoad(ins, null); } finally { if (ins != null) { ins.close(); } } aliases = store.engineAliases(); assert (aliases.hasMoreElements()); alias = (String) aliases.nextElement(); try { store.engineGetKey(alias, null); fail(); } catch (UnrecoverableKeyException e) { //this had better fail } key = store.engineGetKey(alias, "test".toCharArray()); assertNotNull(key); assertTrue(key instanceof PrivateKey); chain = store.engineGetCertificateChain(alias); assertNotNull(chain); } private InputStream getProperties(Properties properties) throws Exception { ByteArrayOutputStream stream = null; ByteArrayInputStream ins = null; try { stream = new ByteArrayOutputStream(); properties.store(stream, "Test Properties"); // load all the CA files ins = new ByteArrayInputStream(stream.toByteArray()); } finally { if (stream != null) { stream.close(); } } return ins; } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] dirContent = dir.list(); for (int i=0; i certList = Arrays.asList(chainCerts); validateChain(certList, keyStore, certStore, policyStore, expectedIdentity, expectedLimited); } private void validateChain(List certList, KeyStore keyStore, CertStore certStore, SigningPolicyStore policyStore, X509Certificate expectedIdentity, boolean expectedLimited) throws Exception { CertPath certPath = factory.generateCertPath(certList); validateChain(certPath, keyStore, certStore, policyStore, expectedIdentity, expectedLimited); } private void validateChain(CertPath chain, KeyStore keyStore, CertStore certStore, SigningPolicyStore policyStore, X509Certificate expectedIdentity, boolean expectedLimited) throws Exception { MockProxyCertPathValidator validator = new MockProxyCertPathValidator(false, false, false, false); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, false); X509ProxyCertPathValidatorResult result = (X509ProxyCertPathValidatorResult) validator .engineValidate(chain, parameters ); assert (expectedLimited == result.isLimited()); assert (expectedIdentity.equals(result.getIdentityCertificate())); } private void validateChainBuiltin(X509Certificate[] chainCerts, KeyStore keyStore, CertStore certStore, SigningPolicyStore policyStore) throws Exception { List certList = Arrays.asList(chainCerts); CertPath certPath = factory.generateCertPath(certList); MockProxyCertPathValidator validator = new MockProxyCertPathValidator(false, false, false, true); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, false); X509ProxyCertPathValidatorResult result = (X509ProxyCertPathValidatorResult) validator .engineValidate(certPath, parameters ); } private void validateError(X509Certificate[] certChain, KeyStore keyStore, CertStore certStore, SigningPolicyStore policyStore, String error) throws Exception { List certList = Arrays.asList(certChain); CertPath chain = factory.generateCertPath(certList); MockProxyCertPathValidator validator = new MockProxyCertPathValidator(false, false, false, false); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, false); boolean exception = false; try { X509ProxyCertPathValidatorResult result = (X509ProxyCertPathValidatorResult) validator .engineValidate(chain, parameters ); } catch (IllegalArgumentException e) { if (e.getMessage().indexOf(error) != -1) { exception = true; } } catch (CertPathValidatorException e) { if (e.getMessage().indexOf(error) != -1) { exception = true; } } assert (exception); } private void validateErrorBuiltin(X509Certificate[] certChain, KeyStore keyStore, CertStore certStore, SigningPolicyStore policyStore, String error) throws Exception { List certList = Arrays.asList(certChain); CertPath chain = factory.generateCertPath(certList); MockProxyCertPathValidator validator = new MockProxyCertPathValidator(false, false, false, true); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, false); boolean exception = false; try { X509ProxyCertPathValidatorResult result = (X509ProxyCertPathValidatorResult) validator .engineValidate(chain, parameters ); } catch (IllegalArgumentException e) { if (e.getMessage().indexOf(error) != -1) { exception = true; } } catch (CertPathValidatorException e) { if (e.getMessage().indexOf(error) != -1) { exception = true; } } assert (exception); } private void validateChainWithPolicy(X509Certificate[] chainCerts, KeyStore keyStore, CertStore certStore, SigningPolicyStore policyStore, boolean error) throws Exception { List certList = Arrays.asList(chainCerts); CertPath certPath = factory.generateCertPath(certList); MockProxyCertPathValidator validator = new MockProxyCertPathValidator(false, false, true, false); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, false); boolean exception = false; try { X509ProxyCertPathValidatorResult result = (X509ProxyCertPathValidatorResult) validator.engineValidate(certPath, parameters); } catch (CertPathValidatorException exp) { exception = true; } assert (error == exception); } protected KeyStore getKeyStore(X509Certificate[] certificates) throws Exception { KeyStore keyStore = KeyStore.getInstance("MockKeyStore"); keyStore.load(null, null); if (certificates != null) { for (X509Certificate certificate : certificates) { keyStore.setCertificateEntry(certificate.getSubjectDN().getName(), certificate); } } return keyStore; } @Test public void validateGsi2PathGood() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]}); TestCertParameters parameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", parameters); TestPolicyStore policyStore = new TestPolicyStore(null); // EEC, CA List tmpCerts = new Vector(); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); CertPath certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], false); // proxy, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[2]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], false); // limited proxy, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[3]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], true); // double limited proxy, limited proxy, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[4]); tmpCerts.add(goodCertsArr[3]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], true); } @Test public void validateRejectLimitedCheck() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]}); TestCertParameters certStoreParameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", certStoreParameters); TestPolicyStore policyStore = new TestPolicyStore(null); // limited proxy, EEC, CA List tmpCerts = new Vector(); tmpCerts.add(goodCertsArr[3]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); CertPath certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], true); MockProxyCertPathValidator validator = new MockProxyCertPathValidator(false, false, false, false); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, true); boolean expected = false; try { X509ProxyCertPathValidatorResult result = (X509ProxyCertPathValidatorResult) validator.engineValidate(certPath, parameters); } catch (CertPathValidatorException exp) { if ((exp.getMessage().indexOf("Limited") != -1)) { expected = true; } } assert (expected); parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, false); X509ProxyCertPathValidatorResult result = (X509ProxyCertPathValidatorResult) validator.engineValidate(certPath, parameters); assertTrue(result.isLimited()); validator.clear(); // a proxy chain with no limited proxy tmpCerts.clear(); tmpCerts.add(goodCertsArr[2]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, true); result = (X509ProxyCertPathValidatorResult) validator.engineValidate(certPath, parameters); assertFalse(result.isLimited()); } @Test public void validateGsi3PathGood() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]}); TestCertParameters certStoreParameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", certStoreParameters); TestPolicyStore policyStore = new TestPolicyStore(null); // GSI 3 PC impersonation, EEC, CA List tmpCerts = new Vector(); tmpCerts.add(goodCertsArr[5]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); CertPath certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], false); // GSI 3 PC independent, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[6]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[6], false); // GSI 3 PC imperson limited, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[7]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], true); // GSI 3 PC impersonation, GSI 3 PC limited impersonation, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[30]); tmpCerts.add(goodCertsArr[7]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], true); // GSI 3 PC impersonation, GSI 3 PC impersonation, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[9]); tmpCerts.add(goodCertsArr[5]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[1], false); // GSI 3 PC indepedent, GSI 3 PC independent, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[10]); tmpCerts.add(goodCertsArr[6]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); certPath = factory.generateCertPath(tmpCerts); validateChain(certPath, keyStore, certStore, policyStore, goodCertsArr[10], false); // GSI 3 PC impersonation, GSI 3 PC independent, EEC, CA tmpCerts.clear(); tmpCerts.add(goodCertsArr[31]); tmpCerts.add(goodCertsArr[6]); tmpCerts.add(goodCertsArr[1]); tmpCerts.add(goodCertsArr[0]); validateChain(tmpCerts, keyStore, certStore, policyStore, goodCertsArr[6], false); // GSI 3 PC indepedent, GSI 3 PC limited impersonation, EEC, CA X509Certificate[] chain = new X509Certificate[]{goodCertsArr[29], goodCertsArr[7], goodCertsArr[1], goodCertsArr[0]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[29], false); } @Test public void validatePathWithRestrictedProxy() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]}); TestCertParameters certStoreParameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", certStoreParameters); TestPolicyStore policyStore = new TestPolicyStore(null); X509Certificate[] chain; // GSI 3 PC restricted, EEC, CA chain = new X509Certificate[]{goodCertsArr[8], goodCertsArr[1], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Unknown policy"); // test proxy handler String policyId = "1.3.6.1.4.1.3536.1.1.1.8"; Map map = new HashMap(); map.put(policyId, new ProxyPolicyHandler() { public void validate(ProxyCertInfo info, CertPath path, int index) throws CertPathValidatorException { ProxyPolicy policy = info.getProxyPolicy(); String pol = policy.getPolicyAsString(); assertEquals("\n\n", pol); } }); chain = new X509Certificate[]{goodCertsArr[8], goodCertsArr[1], goodCertsArr[0]}; List certList = new Vector(); certList.add(chain[0]); certList.add(chain[1]); certList.add(chain[2]); CertPath path = factory.generateCertPath(certList); MockProxyCertPathValidator validator = new MockProxyCertPathValidator(false, false, false, false); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, false, map); X509ProxyCertPathValidatorResult result = (X509ProxyCertPathValidatorResult) validator.engineValidate(path, parameters); // JGLOBUS-103 } @Test public void validatePathBad() throws Exception { KeyStore keyStore = getKeyStore(null); X509Certificate[] chain; CertStore certStore = CertStore.getInstance("MockCertStore", null); TestPolicyStore policyStore = new TestPolicyStore(null); // proxy, CA chain = new X509Certificate[]{goodCertsArr[5], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path"); // user, proxy, CA chain = new X509Certificate[]{goodCertsArr[1], goodCertsArr[2], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path"); // user, user, CA chain = new X509Certificate[]{goodCertsArr[1], goodCertsArr[1], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path"); // user, CA, user chain = new X509Certificate[]{goodCertsArr[1], goodCertsArr[0], goodCertsArr[1]}; validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path"); } @Test public void validatePathMixedProxy() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]}); X509Certificate[] chain; TestCertParameters certStoreParameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", certStoreParameters); TestPolicyStore policyStore = new TestPolicyStore(null); // GSI 3 PC, GSI 2 PC, EEC, CA chain = new X509Certificate[]{goodCertsArr[36], goodCertsArr[2], goodCertsArr[1], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Proxy certificate can only sign another proxy certificate of same type"); // GSI 2 PC, GSI 3 PC, EEC, CA chain = new X509Certificate[]{goodCertsArr[35], goodCertsArr[5], goodCertsArr[1], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Proxy certificate can only sign another proxy certificate of same type"); } @Test public void validatePathProxyPathConstraint() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]}); X509Certificate[] chain; TestCertParameters certStoreParameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", certStoreParameters); TestPolicyStore policyStore = new TestPolicyStore(null); // GSI 3 PC pathlen=0, GSI 3 PC, EEC, CA chain = new X509Certificate[]{goodCertsArr[11], goodCertsArr[1], goodCertsArr[0]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[1], false); // GSI 3 PC, GSI 3 PC pathlen=0, EEC, CA chain = new X509Certificate[]{goodCertsArr[32], goodCertsArr[11], goodCertsArr[1], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Proxy path length constraint violated"); // GSI 3 PC, GSI 3 independent PC pathlen=1, EEC, CA chain = new X509Certificate[]{goodCertsArr[33], goodCertsArr[12], goodCertsArr[1], goodCertsArr[0]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[12], false); // GSI 3 PC, GSI 3 PC, GSI 3 PC pathlen=1, EEC, CA chain = new X509Certificate[]{goodCertsArr[34], goodCertsArr[33], goodCertsArr[12], goodCertsArr[1], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Proxy path length constraint violated"); } @Test public void validatePathCAPathConstraint() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[16]}); X509Certificate[] chain; TestCertParameters certStoreParameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", certStoreParameters); TestPolicyStore policyStore = new TestPolicyStore(null); // EEC, CA (pathlen=0) chain = new X509Certificate[]{goodCertsArr[15], goodCertsArr[16]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[15], false); // GSI 2 limited PC, EEC, CA (pathlen=0) , 3 not issued by this! // chain = new X509Certificate[]{goodCertsArr[3], goodCertsArr[15], // goodCertsArr[16]}; // validateChain(chain, certStore, policyStore, goodCertsArr[15], true); // GSI 3 PC, EEC, CA (pathlen=0) chain = new X509Certificate[]{goodCertsArr[17], goodCertsArr[15], goodCertsArr[16]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[15], false); // GSI 3 PC, EEC, CA (pathlen=0), CA (pathlen=2), CA (pathlen=2) chain = new X509Certificate[]{goodCertsArr[17], goodCertsArr[15], goodCertsArr[16], goodCertsArr[13], goodCertsArr[13]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[15], false); // these should fail // EEC, CA (pathlen=0), CA (pathlen=0) // JGLOBUS-103 why should these fail, the CA is not subordinate. To really // test this we might need CA certificates with subordinates and some // certificates issued incorrectly. // chain = new X509Certificate[]{goodCertsArr[15], goodCertsArr[16], // goodCertsArr[16]}; // validateError(chain, certStore, policyStore, // "ProxyPathValidatorException.PATH_LENGTH_EXCEEDED"); // // GSI 2 limited PC, EEC, CA (pathlen=0), CA (pathlen=2), CA (pathlen=2), CA (pathlen=2) // chain = new X509Certificate[]{goodCertsArr[3], goodCertsArr[15], // goodCertsArr[16], goodCertsArr[13], // goodCertsArr[13], goodCertsArr[13]}; // validateError(chain, certStore, policyStore, // "ProxyPathValidatorException.PATH_LENGTH_EXCEEDED"); // // GSI 3 PC, GSI 3 PC pathlen=1, EEC, CA // chain = new X509Certificate[]{goodCertsArr[10], goodCertsArr[12], // goodCertsArr[1], goodCertsArr[13]}; // validateChain(chain, certStore, policyStore, goodCertsArr[10], false); // // // GSI 3 PC, GSI 3 PC, GSI 3 PC pathlen=1, EEC, CA // chain = new X509Certificate[]{goodCertsArr[10], goodCertsArr[10], // goodCertsArr[12], // goodCertsArr[1], goodCertsArr[13]}; // validateError(chain, certStore, policyStore, // "ProxyPathValidatorException.PATH_LENGTH_EXCEEDED"); // // // GSI 3 PC, GSI 3 PC pathlen=0, EEC, CA // chain = new X509Certificate[]{goodCertsArr[10], // goodCertsArr[11], // goodCertsArr[1], // goodCertsArr[13]}; // validateError(chain, certStore, policyStore, // "ProxyPathValidatorException.FAILURE"); } @Test public void testKeyUsage() throws Exception { X509Certificate[] certsArr = new X509Certificate[testCerts.length]; for (int i = 0; i < certsArr.length; i++) { certsArr[i] = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(testCerts[i].getBytes())); } KeyStore keyStore = getKeyStore(new X509Certificate[]{certsArr[2]}); TestCertParameters certStoreParameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", certStoreParameters); TestPolicyStore policyStore = new TestPolicyStore(null); X509Certificate[] chain; // certArr[1] - has key usage but certSign is off - but it sings proxy // certArr[2] - has key usage and certSing is on chain = new X509Certificate[]{certsArr[0], certsArr[1], certsArr[2]}; validateChain(chain, keyStore, certStore, policyStore, certsArr[1], false); } @Test public void testNoBasicConstraintsExtension() throws Exception { KeyStore keyStore = getKeyStore(null); X509Certificate[] chain; CertStore certStore = CertStore.getInstance("MockCertStore", null); TestPolicyStore policyStore = new TestPolicyStore(null); // EEC, EEC, CA - that should fail chain = new X509Certificate[]{goodCertsArr[1], goodCertsArr[1], goodCertsArr[0]}; validateError(chain, keyStore, certStore, policyStore, "Incorrect certificate path"); keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[1]}); TestCertParameters parameters = new TestCertParameters(null, null); // this makes the PathValidator think the chain is: // CA, CA, CA - which is ok. /*certStore = CertStore.getInstance("MockCertStore", parameters); validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[1], false);*/ } @Test public void testCrlsChecks() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[1], goodCertsArr[16], goodCertsArr[25], goodCertsArr[21]}); TestCertParameters parameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", parameters); TestPolicyStore policyStore = new TestPolicyStore(null); // ca1 ca1user1 good chain X509Certificate[] chain = new X509Certificate[]{goodCertsArr[22], goodCertsArr[21]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[22], false); // ca1 ca1user2 good chain chain = new X509Certificate[]{goodCertsArr[23], goodCertsArr[21]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[23], false); // ca2 user1 bad chain chain = new X509Certificate[]{goodCertsArr[26], goodCertsArr[25]}; validateError(chain, keyStore, certStore, policyStore, "revoked"); // ca2 user2 bad chain chain = new X509Certificate[]{goodCertsArr[27], goodCertsArr[25]}; validateError(chain, keyStore, certStore, policyStore, "revoked"); // ca2 user3 good chain chain = new X509Certificate[]{goodCertsArr[28], goodCertsArr[25]}; validateChain(chain, keyStore, certStore, policyStore, goodCertsArr[28], false); // ca2 user2 revoked CRL // The sleep statements here are to force a CRL refresh. chain = new X509Certificate[]{goodCertsArr[27], goodCertsArr[25]}; String caCertLocations = CoGProperties.getDefault().getCaCertLocations(); System.setProperty("X509_CERT_DIR", crlDir); Thread.sleep(100); validateErrorBuiltin(chain, keyStore, certStore, policyStore, "revoked"); Thread.sleep(100); System.setProperty("X509_CERT_DIR", caCertLocations); validateChainBuiltin(chain, keyStore, certStore, policyStore); } @Test public void testSigningPolicy() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]}); TestCertParameters parameters = new TestCertParameters(null, null); CertStore certStore = CertStore.getInstance("MockCertStore", parameters); X509Certificate[] chain; SigningPolicyParser parser = new SigningPolicyParser(); Reader reader = new StringReader(signingPolicy); Map map = parser.parse(reader); TestPolicyStore policyStore = new TestPolicyStore(map); chain = new X509Certificate[]{goodCertsArr[1], goodCertsArr[0]}; validateChainWithPolicy(chain, keyStore, certStore, policyStore, false); reader = new StringReader(signingPolicyViolation); map = parser.parse(reader); policyStore = new TestPolicyStore(map); validateChainWithPolicy(chain, keyStore, certStore, policyStore, true); } // for testing only to disable validity checking public class MockProxyCertPathValidator extends X509ProxyCertPathValidator { boolean checkCertificateDateValidity; boolean checkCRLDateValidity; boolean checkSigningPolicy; boolean useBuiltinCRL; private CertificateChecker dateChecker = new DateValidityChecker(); public MockProxyCertPathValidator(boolean checkCertificateDateValidity_, boolean checkCRLDateValidity_, boolean checkSigningPolicy_, boolean useBuiltinCRL_) { this.checkCertificateDateValidity = checkCertificateDateValidity_; this.checkCRLDateValidity = checkCRLDateValidity_; this.checkSigningPolicy = checkSigningPolicy_; this.useBuiltinCRL = useBuiltinCRL_; } @Override protected List getCertificateCheckers() { List checkers = new ArrayList(); if (checkCertificateDateValidity) { checkers.add(dateChecker); } checkers.add(new UnsupportedCriticalExtensionChecker()); checkers.add(new IdentityChecker(this)); if (useBuiltinCRL) { CertificateRevocationLists crls = CertificateRevocationLists.getDefaultCertificateRevocationLists(); checkers.add(new CRLChecker(crls, this.keyStore, this.checkCertificateDateValidity)); } else { checkers.add(new CRLChecker(this.certStore, this.keyStore, this.checkCertificateDateValidity)); } if (this.checkSigningPolicy) { checkers.add(new SigningPolicyChecker(this.policyStore)); } return checkers; } } public class TestPolicyStore implements SigningPolicyStore { Map policies; public TestPolicyStore(Map policies_) throws InvalidAlgorithmParameterException { this.policies = policies_; } public SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException { return this.policies.get(caPrincipal); } } public class TestCertParameters implements CertStoreParameters { X509Certificate[] certificates; X509CRL[] crls; public TestCertParameters(X509Certificate[] certificates_, X509CRL[] crls_) { this.certificates = certificates_; this.crls = crls_; } public X509Certificate[] getCertificates() { return certificates; } public X509CRL[] getCRLs() { return this.crls; } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.getLocalizedMessage()); } } } } TestTrustManager.java000066400000000000000000000100741241116057200335160ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.provider; import org.globus.gsi.trustmanager.PKITrustManager; import org.globus.gsi.X509ProxyCertPathParameters; import org.globus.gsi.X509ProxyCertPathValidatorResult; import java.security.KeyStore; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorResult; import java.security.cert.CertStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import org.junit.Before; import org.junit.Test; /** * FILL ME *

    * // JGLOBUS-103 separate this from proxy path validator test class. * * @author ranantha@mcs.anl.gov */ public class TestTrustManager extends TestProxyPathValidator { @Before public void setup() throws Exception { super.setup(); } @Test public void validationTest() throws Exception { KeyStore keyStore = getKeyStore(new X509Certificate[]{goodCertsArr[0]}); TestCertParameters parameters = new TestCertParameters(null, this.crls); CertStore certStore = CertStore.getInstance("MockCertStore", parameters); TestPolicyStore policyStore = new TestPolicyStore(null); X509ProxyCertPathParameters validatorParam = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, false, null); PKITrustManager manager = new PKITrustManager( new MockProxyCertPathValidator(false, false, false, false), validatorParam); X509Certificate[] certChain = new X509Certificate[]{goodCertsArr[5], goodCertsArr[1], goodCertsArr[0]}; manager.checkClientTrusted(certChain, "RSA"); manager.checkServerTrusted(certChain, "RSA"); CertPathValidatorResult result = manager.getValidationResult(); assert (result != null); assert (result instanceof X509ProxyCertPathValidatorResult); assert (!((X509ProxyCertPathValidatorResult) result).isLimited()); X509Certificate[] acceptedIssuers = manager.getAcceptedIssuers(); assert (acceptedIssuers != null); assert (acceptedIssuers.length == 1); assert (acceptedIssuers[0].equals(goodCertsArr[0])); // Fail because of reject limited proxy validatorParam = new X509ProxyCertPathParameters(keyStore, certStore, policyStore, true, null); manager = new PKITrustManager(new MockProxyCertPathValidator(false, false, false, false), validatorParam); certChain = new X509Certificate[]{goodCertsArr[3], goodCertsArr[1], goodCertsArr[0]}; boolean exception = false; try { manager.checkClientTrusted(certChain, "RSA"); } catch (CertificateException e) { Throwable cause = e.getCause(); if (cause instanceof CertPathValidatorException) { if (cause.getMessage().indexOf("Limited") != -1) { exception = true; } } } assert (exception); exception = false; try { manager.checkServerTrusted(certChain, "RSA"); } catch (CertificateException e) { Throwable cause = e.getCause(); if (cause instanceof CertPathValidatorException) { if (cause.getMessage().indexOf("Limited") != -1) { exception = true; } } } assert (exception); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/simple/000077500000000000000000000000001241116057200307455ustar00rootroot00000000000000SimpleMemoryCertStoreTest.java000066400000000000000000000063561241116057200366600ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import org.globus.gsi.provider.simple.SimpleMemoryCertStore; import org.globus.gsi.provider.simple.SimpleMemoryCertStoreParams; import java.security.cert.X509CRLSelector; import java.security.cert.X509CertSelector; import org.junit.AfterClass; import org.globus.util.GlobusPathMatchingResourcePatternResolver; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.security.cert.CertificateFactory; import java.security.Security; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class SimpleMemoryCertStoreTest { private static X509Certificate cert; private static X509CRL crl; private SimpleMemoryCertStore store; @BeforeClass public static void loadBouncyCastleProvider() throws Exception { Security.addProvider(new BouncyCastleProvider()); CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate) factory.generateCertificate( new GlobusPathMatchingResourcePatternResolver().getResource("classpath:/validatorTest/usercert.pem").getInputStream()); crl = (X509CRL) factory.generateCRL( new GlobusPathMatchingResourcePatternResolver().getResource("classpath:/validatorTest/ca2crl.r0").getInputStream()); } @Test public void testEngineGetCRLsCRLSelector() throws Exception { SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(null, null); store = new SimpleMemoryCertStore(params); assertEquals(0, store.engineGetCRLs(new X509CRLSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); assertEquals(1, store.engineGetCRLs(new X509CRLSelector()).size()); X509CRLSelector crlSelector = new X509CRLSelector(); crlSelector.addIssuerName("CN=non-existent"); assertEquals(0, store.engineGetCRLs(crlSelector).size()); } @Test public void testEngineGetCertificatesCertSelector() throws Exception { SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(null, null); store = new SimpleMemoryCertStore(params); assertEquals(0, store.engineGetCertificates(new X509CertSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); assertEquals(1, store.engineGetCertificates(new X509CertSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); X509CertSelector selector = new X509CertSelector(); // with BC as provider for the factory, this fails if i do getSubjectDN().toString() selector.setSubject(cert.getSubjectX500Principal()); assertEquals(1, store.engineGetCertificates(selector).size()); X509CertSelector certSelector = new X509CertSelector(); certSelector.setSubject("CN=non-existent"); assertEquals(0, store.engineGetCertificates(certSelector).size()); } } SimpleMemoryKeyStoreTest.java000066400000000000000000000122551241116057200365060ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import org.globus.gsi.provider.simple.SimpleMemoryKeyStore; import org.globus.gsi.provider.simple.SimpleMemoryKeyStoreLoadStoreParameter; import org.junit.Before; import java.util.Enumeration; import org.globus.util.GlobusPathMatchingResourcePatternResolver; import java.security.cert.CertificateFactory; import org.junit.AfterClass; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.security.Security; import org.junit.BeforeClass; import java.security.cert.X509Certificate; import org.junit.Test; import static org.junit.Assert.*; public class SimpleMemoryKeyStoreTest { private static X509Certificate cert; private SimpleMemoryKeyStore store; @BeforeClass public static void loadBouncyCastleProvider() throws Exception { Security.addProvider(new BouncyCastleProvider()); CertificateFactory factory = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) factory.generateCertificate( new GlobusPathMatchingResourcePatternResolver().getResource("classpath:/validatorTest/testca.pem").getInputStream()); } @Before public void setUp() throws Exception { SimpleMemoryKeyStoreLoadStoreParameter params = new SimpleMemoryKeyStoreLoadStoreParameter(); this.store = new SimpleMemoryKeyStore(); this.store.engineLoad(params); } @Test public void testEngineSize() throws Exception { assertEquals(0, store.engineSize()); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); assertEquals(1, store.engineSize()); } @Test public void testEngineAliases() throws Exception { assertFalse(store.engineAliases().hasMoreElements()); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); Enumeration e = store.engineAliases(); assertEquals(cert.getSubjectDN().getName(), e.nextElement()); assertFalse(e.hasMoreElements()); } @Test public void testEngineContainsAliasString() throws Exception { assertFalse(store.engineContainsAlias(cert.getSubjectDN().getName())); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); store.engineSetCertificateEntry("test", cert); assertTrue(store.engineContainsAlias(cert.getSubjectDN().getName())); assertTrue(store.engineContainsAlias("test")); } @Test public void testEngineDeleteEntryString() throws Exception { assertEquals(0, store.engineSize()); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); assertEquals(1, store.engineSize()); store.engineDeleteEntry(cert.getSubjectDN().getName()); assertEquals(0, store.engineSize()); } @Test public void testEngineGetCertificateString() throws Exception { assertNull(store.engineGetCertificate(cert.getSubjectDN().getName())); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); assertEquals(cert, store.engineGetCertificate(cert.getSubjectDN().getName())); } @Test public void testEngineIsCertificateEntryString() throws Exception { assertFalse(store.engineIsCertificateEntry(cert.getSubjectDN().getName())); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); assertTrue(store.engineIsCertificateEntry(cert.getSubjectDN().getName())); } @Test public void testEngineIsKeyEntryString() throws Exception { assertFalse(null, store.engineIsCertificateEntry(cert.getSubjectDN().getName())); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); assertFalse(store.engineIsKeyEntry(cert.getSubjectDN().getName())); } @Test(expected = UnsupportedOperationException.class) public void testEngineStoreOutputStreamCharArray() throws Exception { store.engineStore(null); } @Test(expected = UnsupportedOperationException.class) public void testEngineSetKeyEntryStringByteArrayCertificateArray() throws Exception { store.engineSetKeyEntry(null,null,null); } @Test(expected = UnsupportedOperationException.class) public void testEngineSetKeyEntryStringKeyCharArrayCertificateArray() throws Exception { store.engineSetKeyEntry(null, null, null); } @Test(expected = UnsupportedOperationException.class) public void testEngineLoadInputStreamCharArray() throws Exception { store.engineLoad(null,new char[3]); } @Test(expected = UnsupportedOperationException.class) public void testEngineGetCertificateAliasCertificate() throws Exception { store.engineGetCertificateAlias(cert); } @Test(expected = UnsupportedOperationException.class) public void testEngineGetCertificateChainString() throws Exception { store.engineGetCertificateChain("test"); } @Test(expected = UnsupportedOperationException.class) public void testEngineGetCreationDateString() throws Exception { store.engineGetCreationDate("test"); } @Test(expected = UnsupportedOperationException.class) public void testEngineGetKeyStringCharArray() throws Exception { store.engineGetKey("test", new char[] {'t'}); } } SimpleMemorySigningPolicyStoreTest.java000066400000000000000000000022331241116057200405270ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/provider/simplepackage org.globus.gsi.provider.simple; import org.globus.gsi.provider.simple.SimpleMemorySigningPolicyStore; import org.globus.util.GlobusPathMatchingResourcePatternResolver; import java.io.InputStreamReader; import org.globus.gsi.SigningPolicy; import java.util.Map; import javax.security.auth.x500.X500Principal; import org.globus.gsi.SigningPolicyParser; import org.junit.Test; import static org.junit.Assert.*; public class SimpleMemorySigningPolicyStoreTest { @Test public void testGetSigningPolicy() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); Map policies; policies = parser.parse(new InputStreamReader(new GlobusPathMatchingResourcePatternResolver().getResource("classpath:/org/globus/gsi/test/49f18420.signing_policy").getInputStream())); assertNotNull(policies); assertFalse(policies.isEmpty()); SimpleMemorySigningPolicyStore store = new SimpleMemorySigningPolicyStore(policies.values().toArray(new SigningPolicy[1])); for (X500Principal p : policies.keySet()) { assertNotNull(store.getSigningPolicy(p)); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/proxy/000077500000000000000000000000001241116057200270035ustar00rootroot00000000000000ProxyPathValidatorTest.java000066400000000000000000001136231241116057200342410ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/proxy/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy; import org.globus.common.CoGProperties; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.gsi.trustmanager.CRLChecker; import org.globus.gsi.trustmanager.CertificateChecker; import org.globus.gsi.trustmanager.DateValidityChecker; import org.globus.gsi.trustmanager.IdentityChecker; import org.globus.gsi.trustmanager.SigningPolicyChecker; import org.globus.gsi.trustmanager.UnsupportedCriticalExtensionChecker; import org.globus.gsi.trustmanager.X509ProxyCertPathValidator; import org.globus.gsi.X509Credential; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Map; import javax.security.auth.x500.X500Principal; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPath; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringReader; import java.security.cert.X509Certificate; import java.security.cert.X509CRL; import org.globus.gsi.GSIConstants; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.SigningPolicy; import org.globus.gsi.SigningPolicyParser; import org.globus.gsi.CertificateRevocationLists; import org.globus.gsi.proxy.ProxyPolicyHandler; import org.globus.gsi.proxy.ProxyPathValidator; import org.globus.gsi.proxy.ProxyPathValidatorException; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.globus.gsi.proxy.ext.ProxyPolicy; import junit.framework.TestCase; public class ProxyPathValidatorTest extends TestCase { private static Log log = LogFactory.getLog(ProxyPathValidatorTest.class); public static final String BASE = "validatorTest/"; public static String[] crlNames = { "ca2crl.r0", "testca3.r0" }; public static String[][] certs = { {GSIConstants.CertificateType.CA.name(), "TestCA1.pem"}, {GSIConstants.CertificateType.EEC.name(), "eecFromTestCA1.pem"}, {GSIConstants.CertificateType.GSI_2_PROXY.name(), "gsi2fullproxy.pem"}, {GSIConstants.CertificateType.GSI_2_LIMITED_PROXY.name(), "gsi2limitedproxy.pem"}, // 4, double GSIConstants.CertificateType.GSI_2_LIMITED_PROXY), gsi2limited2xproxy.pem (issued by // 3) {GSIConstants.CertificateType.GSI_2_LIMITED_PROXY.name(), "gsi2limited2xproxy.pem"}, // 5, GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY), gsi3impersonationproxy.pem {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3impersonationproxy.pem"}, // 6, GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY), gsi3independentproxy.pem {GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY.name(), "gsi3independentproxy.pem"}, // 7, GSIConstants.CertificateType.GSI_3_LIMITED_PROXY), gsi3limitedproxy.pem {GSIConstants.CertificateType.GSI_3_LIMITED_PROXY.name(), "gsi3limitedproxy.pem"}, // 8, GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY), gsi3restrictedproxy.pem {GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY.name(), "gsi3restrictedproxy.pem"}, // double // 9, GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY), gsi3impersonation2xproxy.pem {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3impersonation2xproxy.pem"}, // 10, GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY), gsi3independent2xproxy.pem {GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY.name(), "gsi3independent2xproxy.pem"}, // pathLen = 0 // 11, GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY), gsi3impersonationp0proxy.pem {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3impersonationp0proxy.pem"}, // pathLen = 1 // 12, GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY), gsi2independentp1proxy.pem {GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY.name(), "gsi3independentp1proxy.pem"}, // pathLen = 2 // 13, GSIConstants.CertificateType.CA), {GSIConstants.CertificateType.CA.name(), "testca.pem"}, // 14, GSIConstants.CertificateType.EEC) {GSIConstants.CertificateType.EEC.name(), "testeec1.pem"}, // 15, GSIConstants.CertificateType.EEC) {GSIConstants.CertificateType.EEC.name(), "testeec2.pem"}, // pathLen = 1 // 16, GSIConstants.CertificateType.CA) {GSIConstants.CertificateType.CA.name(), "testca2.pem"}, // crl for this, 16 // 17, GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY), {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "testgsi3proxy.pem"}, // for CRL test // 18, GSIConstants.CertificateType.CA), {GSIConstants.CertificateType.CA.name(), "testca3.pem"}, // 19, GSIConstants.CertificateType.EEC), {GSIConstants.CertificateType.EEC.name(), "crl_usercert.pem"}, // 20, GSIConstants.CertificateType.GSI_2_PROXY), {GSIConstants.CertificateType.GSI_2_PROXY.name(), "crl_proxy.pem"}, // 21 (all good) // GSIConstants.CertificateType.CA) {GSIConstants.CertificateType.CA.name(), "ca1cert.pem"}, // 22, GSIConstants.CertificateType.EEC {GSIConstants.CertificateType.EEC.name(), "user1ca1.pem"}, // 23, GSIConstants.CertificateType.EEC) {GSIConstants.CertificateType.EEC.name(), "user2ca1.pem"}, // 24, GSIConstants.CertificateType.EEC) {GSIConstants.CertificateType.EEC.name(), "user3ca1.pem"}, // 25 // GSIConstants.CertificateType.CA) {GSIConstants.CertificateType.CA.name(), "ca2cert.pem"}, // crl 25 // must be revoked (in ca2crl.r0) // 26, GSIConstants.CertificateType.EEC) {GSIConstants.CertificateType.EEC.name(), "user1ca2.pem"}, // must be revoked (in ca2crl.r0) // 27, GSIConstants.CertificateType.EEC), {GSIConstants.CertificateType.EEC.name(), "user2ca2.pem"}, // 28, GSIConstants.CertificateType.EEC) {GSIConstants.CertificateType.EEC.name(), "user3ca2.pem"}, // 29 // gsi3 limited impersonation signs a gsi3 independent {GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY.name(), "gsi3independentFromLimitedProxy.pem"}, // 30 // gsi3 limited impersonation signs a gsi3 impersonation {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3limitedimpersonation2xproxy.pem"}, // 31 // gsi3 independent signs a gsi3 impersonation {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3impersonationFromIndependentProxy.pem"}, // 32 // gsi3 pathlength 0 impersonatipon proxy signs proxy {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3FromPathZeroProxy.pem"}, // 33 // gsi3 path length 1 independent proxy signs proxy {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3FromPathOneProxy.pem"}, // 34 // gsi3FrompathOneProxy signs proxy {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3FromPathOneIssuedProxy.pem"}, // 35 // gsi2 proxy generated from gsi3impersonationProxy {GSIConstants.CertificateType.GSI_2_PROXY.name(), "gsi2proxyFromgsi3.pem"}, // 36 // gsi3 proxy generated from gsi2fullproxy {GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY.name(), "gsi3proxyFromgsi2.pem" }}; public static String[] badCerts = { "-----BEGIN CERTIFICATE-----\n" + "MIICFTCCAX6gAwIBAgIDClb3MA0GCSqGSIb3DQEBBAUAMGIxCzAJBgNVBAYTAlVT\n" + "MQ8wDQYDVQQKEwZHbG9idXMxJDAiBgNVBAoTG0FyZ29ubmUgTmF0aW9uYWwgTGFi\n" + "b3JhdG9yeTEMMAoGA1UECxMDTUNTMQ4wDAYDVQQDEwVnYXdvcjAeFw0wMjEyMTgw\n" + "NzEzNDhaFw0wMjEyMTgxOTE4NDhaMIGCMQswCQYDVQQGEwJVUzEPMA0GA1UEChMG\n" + "R2xvYnVzMSQwIgYDVQQKExtBcmdvbm5lIE5hdGlvbmFsIExhYm9yYXRvcnkxDDAK\n" + "BgNVBAsTA01DUzEOMAwGA1UEAxMFZ2F3b3IxDjAMBgNVBAMTBXByb3h5MQ4wDAYD\n" + "VQQDEwVwcm94eTBaMA0GCSqGSIb3DQEBAQUAA0kAMEYCQQCplfu3OZH5AfYgoYKi\n" + "KFmGZnbj3+ZwJm45B6Ef7qwW7Le7FP4eirljObqijgn8ao0gGqy38LYbaTntToqX\n" + "iy5fAgERMA0GCSqGSIb3DQEBBAUAA4GBAKnNy0VPDzzD6++7i9a/yegPX2+OVI6C\n" + "7oss1/4sSw2gfn/q8qNiGdt1kr4W3JJACdjgnik8fokNS7pDMdXKi3Wx6E0HhgKz\n" + "eRIm5r6Vj7nshVBAv60Xmfju3yaOZsDnj8p0t8Fjc8ekeZowLEdRn7PCEQPylMOp\n" + "2puR03MaPiFj\n" + "-----END CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\n" + "MIICBDCCAW2gAwIBAgIDAx4rMA0GCSqGSIb3DQEBBAUAMGIxCzAJBgNVBAYTAlVT\n" + "MQ8wDQYDVQQKEwZHbG9idXMxJDAiBgNVBAoTG0FyZ29ubmUgTmF0aW9uYWwgTGFi\n" + "b3JhdG9yeTEMMAoGA1UECxMDTUNTMQ4wDAYDVQQDEwVnYXZvcjAeFw0wMjEyMTgw\n" + "NzIxMThaFw0wMjEyMTgxOTI2MThaMHIxCzAJBgNVBAYTAlVTMQ8wDQYDVQQKEwZH\n" + "bG9idXMxJDAiBgNVBAoTG0FyZ29ubmUgTmF0aW9uYWwgTGFib3JhdG9yeTEMMAoG\n" + "A1UECxMDTUNTMQ4wDAYDVQQDEwVnYXdvcjEOMAwGA1UEAxMFcHJveHkwWjANBgkq\n" + "hkiG9w0BAQEFAANJADBGAkEAx2fp80b+Yo0zCwjYJdIjzn0N3ezzcD2h2bAr/Nop\n" + "w/H6JB4heiVGMeydMlSJHyI7J/s5l8k39G/KVrBGT9tRJwIBETANBgkqhkiG9w0B\n" + "AQQFAAOBgQCRRvTdW6Ddn1curWm515l/GoAoJ76XBFJWfusIZ9TdwE8hlkRpK9Bd\n" + "Rrao4Z2YO+e3UItn45Hs+8gzx+jBB1AduTUor603Z8AXaNbF/c+gz62lBWlcmZ2Y\n" + "LzuUWgwZLd9HdA2YBgCcT3B9VFmBxcnPjGOwWT29ZUtyy2GXFtzcDw==\n" + "-----END CERTIFICATE-----" }; public static String[] testCerts = { "-----BEGIN CERTIFICATE-----\n" + "MIIB7zCCAVigAwIBAgICAbowDQYJKoZIhvcNAQEEBQAwVzEbMBkGA1UEChMSZG9l\n" + "c2NpZW5jZWdyaWQub3JnMQ8wDQYDVQQLEwZQZW9wbGUxJzAlBgNVBAMTHlZpamF5\n" + "YSBMYWtzaG1pIE5hdGFyYWphbiAxNzkwODAeFw0wMzAxMTcyMjExMjJaFw0wMzAx\n" + "MTgxMDE2MjJaMGcxGzAZBgNVBAoTEmRvZXNjaWVuY2VncmlkLm9yZzEPMA0GA1UE\n" + "CxMGUGVvcGxlMScwJQYDVQQDEx5WaWpheWEgTGFrc2htaSBOYXRhcmFqYW4gMTc5\n" + "MDgxDjAMBgNVBAMTBXByb3h5MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANGP+xct\n" + "lDYMPm11QKnACvqs95fbPRehvUi6/dizZ+VrDOU1OTUoXA0t6HRgtmJ8XthEUKxU\n" + "MVsxjXtoZOzfuFECAwEAATANBgkqhkiG9w0BAQQFAAOBgQBqFTcN/qqvTnyI4z26\n" + "lv1lMTuRIjL9l6Ug/Kwxuzjpl088INky1myFPjKsWMYzh9nXIQg9gg2dJTno5JHB\n" + "++u0Fw2iNrTjswu4hvqYZn+LoSGchH2XyCUssuOWCbW4IkN8/Xzfre2oC2EieECC\n" + "w+jjGhcqPrxvkHh8xXYroqA0Sg==\n" + "-----END CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\n" + "MIIDLDCCAhSgAwIBAgICAbowDQYJKoZIhvcNAQEFBQAwdTETMBEGCgmSJomT8ixk\n" + "ARkWA25ldDESMBAGCgmSJomT8ixkARkWAmVzMSAwHgYDVQQLExdDZXJ0aWZpY2F0\n" + "ZSBBdXRob3JpdGllczEZMBcGA1UECxMQRE9FIFNjaWVuY2UgR3JpZDENMAsGA1UE\n" + "AxMEcGtpMTAeFw0wMjA5MjMyMzQ2NDRaFw0wMzA5MjMyMzQ2NDRaMFcxGzAZBgNV\n" + "BAoTEmRvZXNjaWVuY2VncmlkLm9yZzEPMA0GA1UECxMGUGVvcGxlMScwJQYDVQQD\n" + "Ex5WaWpheWEgTGFrc2htaSBOYXRhcmFqYW4gMTc5MDgwgZ8wDQYJKoZIhvcNAQEB\n" + "BQADgY0AMIGJAoGBAORYHsPQU3yVlTsC/29CDoEYF82PVlolQk5s+1m6A7m3VvML\n" + "TKh4ja6cKtq7C5rBUIWdyklkU3eXSSmiAzjJrVOmfWK3RR465A5tfvJLmXKWaq3U\n" + "7SvI6v3vx4Jzy4MJs46TDAr4v9JRJG2yshoxruRy2gDsn4F5NfLLevDNwzSLAgMB\n" + "AAGjaDBmMBEGCWCGSAGG+EIBAQQEAwIF4DAOBgNVHQ8BAf8EBAMCBPAwHwYDVR0j\n" + "BBgwFoAUVBeIygPBOSa4VabEmfQrAqu+AOkwIAYDVR0RBBkwF4EVdmlqYXlhbG5A\n" + "bWF0aC5sYmwuZ292MA0GCSqGSIb3DQEBBQUAA4IBAQC/dxf5ZuSrNrxslHUZfDle\n" + "V8SPnX5roBUOuO2EPpEGYHB25Ca+TEi0ra0RSRuZfGmY13/aS6CzjBF+6GED9MLo\n" + "6UdP1dg994wpGZ2Mj0dZoGE7we10NrSvFAS3u7uXrTTegeJoDpo1k9YVsOkK9Lu9\n" + "Sg+EztnMGa1BANWf779Qws5J9xUR2Nip0tBkV3IRORcBx0CoZzQnDIWyppmnkza2\n" + "mhgEv6CXYYB4ucCFst0P2Q3omcWrtHexoueMGOV6PtLFBst5ReOaZWU+q2D30t3b\n" + "GFITa0aayXTlb6gWgo3z/O/K5GZS5jF+BA3j1e8IhxqeibT1rVHF4W4ZMjGhBcwa\n" + "-----END CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\n" + "MIIEqjCCBBOgAwIBAgIBLzANBgkqhkiG9w0BAQUFADBbMRkwFwYDVQQKExBET0Ug\n" + "U2NpZW5jZSBHcmlkMSAwHgYDVQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEc\n" + "MBoGA1UEAxMTQ2VydGlmaWNhdGUgTWFuYWdlcjAeFw0wMTEyMjEyMzQ4MzdaFw0w\n" + "NDAxMTAyMzQ4MzdaMHUxEzARBgoJkiaJk/IsZAEZFgNuZXQxEjAQBgoJkiaJk/Is\n" + "ZAEZFgJlczEgMB4GA1UECxMXQ2VydGlmaWNhdGUgQXV0aG9yaXRpZXMxGTAXBgNV\n" + "BAsTEERPRSBTY2llbmNlIEdyaWQxDTALBgNVBAMTBHBraTEwggEiMA0GCSqGSIb3\n" + "DQEBAQUAA4IBDwAwggEKAoIBAQDhgzoAt5viFffXWG6P0KSf/dO0mrEbgpuKIHDa\n" + "RdHkxJGaoBgRO2D+YV4Wh+JcKlz64v2ScYHCgGbKoaE+cGM/O06xkLCV0pyT4Xvj\n" + "6/R80jqwzzRw8aYz9iE/wjljK1ehb+oJ6TJlnotCVBd7TlHODYfXXblt67/Uk1uu\n" + "4l17jCdfk4mUn/2Bdeae4EMibj7Vc1dkPkyY47ZADTeFXMNDyp4yGFeIDZQ6h+YH\n" + "27+t1/TDuEH1R4PpklRpSbppGprI8hv2P6uEKTySjAEkww9xVzenN6oULeafFJuS\n" + "t6Ui6BFxc1OuxMq/s0PDiFh8bPMhzJWBfzaNPHnYrFDWcDwHAgMBAAGjggHeMIIB\n" + "2jAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFFQXiMoDwTkmuFWmxJn0KwKrvgDp\n" + "MB8GA1UdIwQYMBaAFJvOT/K8vVhwMdXyMg5+nr3iURTnMA8GA1UdEwEB/wQFMAMB\n" + "Af8wgY8GA1UdHwSBhzCBhDCBgaAaoBiGFmh0dHA6Ly9lbnZpc2FnZS5lcy5uZXSB\n" + "AgDsol+kXTBbMRkwFwYDVQQKExBET0UgU2NpZW5jZSBHcmlkMSAwHgYDVQQLExdD\n" + "ZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEcMBoGA1UEAxMTQ2VydGlmaWNhdGUgTWFu\n" + "YWdlcjCB5AYDVR0gBIHcMIHZMIHWBgoqhkiG90wDBgQBMIHHMF8GCCsGAQUFBwIC\n" + "MFMwJhYfRVNuZXQgKEVuZXJneSBTY2llbmNlcyBOZXR3b3JrKTADAgEBGilFU25l\n" + "dC1ET0UgU2NpZW5jZSBHcmlkIENlcnRpZmljYXRlIFBvbGljeTBkBggrBgEFBQcC\n" + "ARZYaHR0cDovL2VudmlzYWdlLmVzLm5ldC9FbnZpc2FnZSUyMERvY3MvRE9FU0cl\n" + "MjBDQSUyMENlcnRpZmljYXRlJTIwUG9saWN5JTIwYW5kJTIwQ1BTLnBkZjANBgkq\n" + "hkiG9w0BAQUFAAOBgQCaAdUregqwmCJG6j/h6uK2bTpcfa/SfpaYwsTy+zlf5r4P\n" + "iY/wIRN0ZjJ4RrJQ/WUH16onNwb87JnYe0V4JYhATAOnp/5y9kl+iC4XvHBioVxm\n" + "3sEADL40WAVREWBGZnyFqysXAEGfk+Wg7um5FzCwi6380GASKY0VujQG03f6Pg==\n" + "-----END CERTIFICATE-----" }; // Globus CA signing policy. Using globusca.pem and usercert.pem public static String signingPolicy = "access_id_CA X509 '/C=TestCA1/CN=CA'\npos_rights globus CA:sign\ncond_subjects globus '\"/*\"'"; // Globus CA signing policy that causes usercert.pem to violate // the policy public static String signingPolicyViolation = "access_id_CA X509 '/C=TestCA1/CN=CA'\npos_rights globus CA:sign\ncond_subjects globus '\"/12*\"'"; // Globus CA signing policy without relevant signing policy public static String signingPolicySansPolicy = "# Globus CA rights\naccess_id_CA nonX509 '/C=US/O=Globus/CN=Globus Certification Authority'\npos_rights globus CA:sign\ncond_subjects globus '\"/C=usa/O=Globus/*\" \"/C=USA/O=Globus/*\"'\n# End of ca-signing-policy.conf"; public static X509Certificate[] goodCertsArr; static { try { goodCertsArr = initCerts(); } catch (Exception e) { throw new RuntimeException("Failed to load certs: " + e.getMessage()); } } public ProxyPathValidatorTest(String name) { super(name); } public static X509Certificate[] initCerts() throws Exception { CoGProperties.getDefault().setProperty(CoGProperties.getDefault().CRL_CACHE_LIFETIME, "1"); X509Certificate[] goodCertsArr = new X509Certificate[certs.length]; ClassLoader loader = ProxyPathValidatorTest.class.getClassLoader(); for (int i = 0; i < certs.length; i++) { String name = BASE + certs[i][1]; InputStream in = loader.getResourceAsStream(name); if (in == null) { throw new Exception("Unable to load: " + name); } log.debug("goodCertsArr[" + i + "]" + name); goodCertsArr[i] = CertificateLoadUtil.loadCertificate(in); } return goodCertsArr; } public void testValidateGsi2PathGood() throws Exception { X509Certificate[] chain = null; X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[0] }; // EEC, CA chain = new X509Certificate[] { goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], false); // proxy, EEC, CA chain = new X509Certificate[] { goodCertsArr[2], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], false); // limited proxy, EEC, CA chain = new X509Certificate[] { goodCertsArr[3], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], true); // double limited proxy, limited proxy, EEC, CA chain = new X509Certificate[] { goodCertsArr[4], goodCertsArr[3], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], true); } public void testValidateGsi3PathGood() throws Exception { X509Certificate[] chain = null; X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[0] }; // GSI 3 PC impersonation, EEC, CA chain = new X509Certificate[] { goodCertsArr[5], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], false); // GSI 3 PC independent, EEC, CA chain = new X509Certificate[] { goodCertsArr[6], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[6], false); // GSI 3 PC imperson limited, EEC, CA chain = new X509Certificate[] { goodCertsArr[7], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], true); // GSI 3 PC impersonation, GSI 3 PC limited impersonation, EEC, CA chain = new X509Certificate[] { goodCertsArr[30], goodCertsArr[7], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], true); // GSI 3 PC impersonation, GSI 3 PC impersonation, EEC, CA chain = new X509Certificate[] { goodCertsArr[9], goodCertsArr[5], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], false); // GSI 3 PC indepedent, GSI 3 PC independent, EEC, CA chain = new X509Certificate[] { goodCertsArr[10], goodCertsArr[6], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[10], false); // GSI 3 PC impersonation, GSI 3 PC independent, EEC, CA chain = new X509Certificate[] { goodCertsArr[31], goodCertsArr[6], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[6], false); // GSI 3 PC indepedent, GSI 3 PC limited impersonation, EEC, CA chain = new X509Certificate[] { goodCertsArr[29], goodCertsArr[7], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[29], false); } public void testValidatePathWithRestrictedProxy() throws Exception { X509Certificate[] chain = null; X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[0] }; // GSI 3 PC restricted, EEC, CA chain = new X509Certificate[] { goodCertsArr[8], goodCertsArr[1], goodCertsArr[0] }; validateError(chain, trustedCerts, ProxyPathValidatorException.UNKNOWN_POLICY); // // GSI 3 PC impersonation, GSI 3 PC restricted, EEC, CA chain = new X509Certificate[] { goodCertsArr[9], goodCertsArr[8], goodCertsArr[1], goodCertsArr[0] }; validateError(chain, trustedCerts, ProxyPathValidatorException.UNKNOWN_POLICY); TestProxyPathValidator v = new TestProxyPathValidator(); v.setProxyPolicyHandler("1.3.6.1.4.1.3536.1.1.1.8", new ProxyPolicyHandler() { public void validate(ProxyCertInfo info, CertPath path, int index) throws CertPathValidatorException { ProxyPolicy policy = info.getProxyPolicy(); String pol = policy.getPolicyAsString(); assertEquals("\r\n".trim(), pol.trim()); // COMMENT fails without trimming } }); chain = new X509Certificate[] { goodCertsArr[8], goodCertsArr[1], goodCertsArr[0] }; v.validate(chain, trustedCerts); } public void testValidatePathBad() throws Exception { X509Certificate[] chain = null; X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[0] }; // proxy, CA chain = new X509Certificate[] { goodCertsArr[5], goodCertsArr[0] }; validateChain(chain, trustedCerts); // user, proxy, CA chain = new X509Certificate[] { goodCertsArr[1], goodCertsArr[2], goodCertsArr[0] }; validateChain(chain, trustedCerts); // user, user, CA chain = new X509Certificate[] { goodCertsArr[1], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts); // user, CA, user chain = new X509Certificate[] { goodCertsArr[1], goodCertsArr[0], goodCertsArr[1] }; validateChain(chain, trustedCerts); } public void testValidatePathMixedProxy() throws Exception { X509Certificate[] chain = null; X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[0] }; // GSI 3 PC, GSI 2 PC, EEC, CA chain = new X509Certificate[] { goodCertsArr[6], goodCertsArr[2], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts); // GSI 2 PC, GSI 3 PC, EEC, CA chain = new X509Certificate[] { goodCertsArr[2], goodCertsArr[6], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts); } public void testValidatePathProxyPathConstraint() throws Exception { X509Certificate[] chain = null; X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[0] }; // GSI 3 PC pathlen=0, GSI 3 PC, EEC, CA chain = new X509Certificate[] { goodCertsArr[11], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[1], false); // GSI 3 PC, GSI 3 PC pathlen=0, EEC, CA chain = new X509Certificate[] { goodCertsArr[32], goodCertsArr[11], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts); // GSI 3 PC, GSI 3 PC pathlen=1, EEC, CA chain = new X509Certificate[] { goodCertsArr[33], goodCertsArr[12], goodCertsArr[1], goodCertsArr[0] }; validateChain(chain, trustedCerts, goodCertsArr[12], false); // GSI 3 PC, GSI 3 PC, GSI 3 PC pathlen=1, EEC, CA chain = new X509Certificate[] { goodCertsArr[34], goodCertsArr[33], goodCertsArr[12], goodCertsArr[1], goodCertsArr[0] }; validateError(chain, trustedCerts, ProxyPathValidatorException.PATH_LENGTH_EXCEEDED); } public void testValidatePathCAPathConstraint() throws Exception { X509Certificate[] chain = null; X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[16] }; // should all be OK // EEC, CA (pathlen=0) chain = new X509Certificate[] { goodCertsArr[15], goodCertsArr[16] }; validateChain(chain, trustedCerts, goodCertsArr[15], false); // GSI 2 limited PC, EEC, CA (pathlen=0) chain = new X509Certificate[] { goodCertsArr[3], goodCertsArr[15], goodCertsArr[16] }; //validateChain(chain, trustedCerts, goodCertsArr[15], true); validateError(chain, trustedCerts, ProxyPathValidatorException.PATH_LENGTH_EXCEEDED); // GSI 3 PC, EEC, CA (pathlen=0) chain = new X509Certificate[] { goodCertsArr[17], goodCertsArr[15], goodCertsArr[16] }; validateChain(chain, trustedCerts, goodCertsArr[15], false); // GSI 3 PC, EEC, CA (pathlen=0), CA (pathlen=2), CA (pathlen=2) chain = new X509Certificate[] { goodCertsArr[17], goodCertsArr[15], goodCertsArr[16], goodCertsArr[13], goodCertsArr[13] }; validateChain(chain, trustedCerts, goodCertsArr[15], false); // these should fail // EEC, CA (pathlen=0), CA (pathlen=0) chain = new X509Certificate[] { goodCertsArr[15], goodCertsArr[16], goodCertsArr[16] }; validateError(chain, trustedCerts, ProxyPathValidatorException.PATH_LENGTH_EXCEEDED); // GSI 2 limited PC, EEC, CA (pathlen=0), CA (pathlen=2), CA (pathlen=2), CA (pathlen=2) chain = new X509Certificate[] { goodCertsArr[3], goodCertsArr[15], goodCertsArr[16], goodCertsArr[13], goodCertsArr[13], goodCertsArr[13] }; validateError(chain, trustedCerts, ProxyPathValidatorException.PATH_LENGTH_EXCEEDED); // GSI 3 PC, GSI 3 PC pathlen=1, EEC, CA chain = new X509Certificate[] { goodCertsArr[10/*10*/], goodCertsArr[12], goodCertsArr[1], goodCertsArr[13] }; //validateChain(chain, trustedCerts, goodCertsArr[10/*10*/], false); validateError(chain, trustedCerts, ProxyPathValidatorException.PATH_LENGTH_EXCEEDED); // GSI 3 PC, GSI 3 PC, GSI 3 PC pathlen=1, EEC, CA chain = new X509Certificate[] { goodCertsArr[10], goodCertsArr[10], goodCertsArr[12], goodCertsArr[1], goodCertsArr[13] }; validateError(chain, trustedCerts, ProxyPathValidatorException.PATH_LENGTH_EXCEEDED); // GSI 3 PC, GSI 3 PC pathlen=0, EEC, CA chain = new X509Certificate[] { goodCertsArr[10], goodCertsArr[11], goodCertsArr[1], goodCertsArr[13] }; validateError(chain, trustedCerts, ProxyPathValidatorException.FAILURE); } public void testKeyUsage() throws Exception { X509Certificate[] certsArr = new X509Certificate[testCerts.length]; for (int i = 0; i < certsArr.length; i++) { certsArr[i] = CertificateLoadUtil.loadCertificate( new ByteArrayInputStream(testCerts[i].getBytes())); } X509Certificate[] trustedCAs = new X509Certificate[]{certsArr[2]}; X509Certificate[] chain = null; // certArr[1] - has key usage but certSign is off - but it signs proxy // certArr[2] - has key usage and certSign is on chain = new X509Certificate[] { certsArr[0], certsArr[1], certsArr[2] }; validateChain(chain, trustedCAs, certsArr[1], false); TestProxyPathValidator v = new TestProxyPathValidator(); v.validate(chain, new TrustedCertificates(trustedCAs)); assertEquals(false, v.isLimited()); assertEquals(certsArr[1], v.getIdentityCertificate()); } public void testNoBasicConstraintsExtension() throws Exception { X509Certificate[] chain = null; X509Certificate[] trustedCAs = new X509Certificate[] { goodCertsArr[16] }; X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[16] }; // EEC, EEC, CA - that should fail //chain = new X509Certificate[] { goodCertsArr[1], goodCertsArr[1], goodCertsArr[0] }; chain = new X509Certificate[] { goodCertsArr[15], goodCertsArr[15], goodCertsArr[16] }; //validateChain(chain, trustedCerts, goodCertsArr[15], false); validateChain(chain, trustedCAs); TestProxyPathValidator v = new TestProxyPathValidator(); TrustedCertificates trustedCert = new TrustedCertificates(new X509Certificate[] { goodCertsArr[16] }, new SigningPolicy[] { new SigningPolicy(new X500Principal("CN=foo"), new String[] { "CN=foo" }) }); //X509Certificate[] trustedCerts = new X509Certificate[] { goodCertsArr[1] }; chain = new X509Certificate[] { goodCertsArr[16], goodCertsArr[16], goodCertsArr[0] }; // this makes the PathValidator think the chain is: // CA, CA, CA - which is ok. irrelevant to signing policy. try { v.validate(chain, trustedCert); } catch (ProxyPathValidatorException e) { e.printStackTrace(); fail("Unexpected exception: " + e.getMessage()); } } //JGLOBUS-103 public void testCrlsChecks() throws Exception { TestProxyPathValidator tvalidator = new TestProxyPathValidator(); // chain of good certs X509Certificate[] chain = new X509Certificate[]{goodCertsArr[22], goodCertsArr[21]}; X509Certificate[] tCerts = new X509Certificate[]{goodCertsArr[1], goodCertsArr[16], goodCertsArr[25], goodCertsArr[21]}; ClassLoader loader = ProxyPathValidatorTest.class.getClassLoader(); String location1 = loader.getResource(BASE).getPath(); CertificateRevocationLists certRevLists = CertificateRevocationLists.getCertificateRevocationLists(location1); assertNotNull(certRevLists); assertEquals(2,certRevLists.getCrls().length); TrustedCertificates trustedCerts = new TrustedCertificates(tCerts); X509CRL[] crls = certRevLists.getCrls(); assertNotNull(crls); assertEquals(2, crls.length); try { tvalidator.validate(chain, trustedCerts.getCertificates(), certRevLists, trustedCerts.getSigningPolicies()); } catch (ProxyPathValidatorException e) { e.printStackTrace(); fail("Unexpected exception: " + e.getMessage()); } tvalidator.reset(); // remove signing policy checks and validity checks // ca1 ca1user1 good chain chain = new X509Certificate[] { goodCertsArr[22], goodCertsArr[21] }; certRevLists = CertificateRevocationLists.getCertificateRevocationLists(location1); assertNotNull(certRevLists.getCrls()); assertEquals(2,certRevLists.getCrls().length); try { tvalidator.validate(chain, new X509Certificate[] { goodCertsArr[21] }, certRevLists, trustedCerts .getSigningPolicies()); } catch (ProxyPathValidatorException e) { e.printStackTrace(); fail("Unexpected exception: " + e.getMessage()); } tvalidator.reset(); // ca1 ca1user2 good chain chain = new X509Certificate[] { goodCertsArr[23], goodCertsArr[21] }; try { tvalidator.validate(chain, new X509Certificate[] { goodCertsArr[21] }, certRevLists, trustedCerts .getSigningPolicies()); } catch (ProxyPathValidatorException e) { e.printStackTrace(); fail("Unexpected exception: " + e.getMessage()); } tvalidator.reset(); // ca2 user1 bad chain chain = new X509Certificate[] { goodCertsArr[26], goodCertsArr[25] }; try { tvalidator.validate(chain, new X509Certificate[] { goodCertsArr[25] }, certRevLists, trustedCerts .getSigningPolicies()); fail("Validation did not throw exception"); } catch (ProxyPathValidatorException crlExp) { // COMMENT no check on exception error code //assertEquals(ProxyPathValidatorException.REVOKED, crlExp.getErrorCode()); } tvalidator.reset(); // ca2 user2 bad chain chain = new X509Certificate[] { goodCertsArr[27], goodCertsArr[25] }; try { tvalidator.validate(chain, new X509Certificate[] { goodCertsArr[25] }, certRevLists, trustedCerts .getSigningPolicies()); fail("Validation did not throw exception"); } catch (ProxyPathValidatorException crlExp) { // COMMENT no check on exceptino error code //assertEquals(ProxyPathValidatorException.REVOKED, crlExp.getErrorCode()); } tvalidator.reset(); // ca2 user3 good chain chain = new X509Certificate[] { goodCertsArr[28], goodCertsArr[25] }; try { tvalidator.validate(chain, new X509Certificate[] { goodCertsArr[25] }, certRevLists, trustedCerts.getSigningPolicies()); } catch (ProxyPathValidatorException e) { e.printStackTrace(); fail("Unexpected exception: " + e.getMessage()); } } public void testSigningPolicy() throws Exception { X509Certificate[] chain = null; Map map = new SigningPolicyParser().parse(new StringReader(signingPolicy)); SigningPolicy policy = map.values().iterator().next(); assertNotNull(policy); TestProxyPathValidator tvalidator = new TestProxyPathValidator(true); chain = new X509Certificate[] { goodCertsArr[1], goodCertsArr[0] }; TrustedCertificates tc = new TrustedCertificates(new X509Certificate[] { goodCertsArr[0] }, new SigningPolicy[] { policy }); tvalidator.validate(chain, tc); map = new SigningPolicyParser().parse(new StringReader(signingPolicyViolation)); policy = map.values().iterator().next(); assertNotNull(policy); tc = new TrustedCertificates(new X509Certificate[] { goodCertsArr[0] }, new SigningPolicy[] { policy }); try { tvalidator.validate(chain, tc); fail("Exception expected"); } catch (ProxyPathValidatorException exp) { // COMMENT ignore error code //assertEquals(ProxyPathValidatorException.SIGNING_POLICY_VIOLATION, exp.getErrorCode()); } try { map = new SigningPolicyParser().parse(new StringReader(signingPolicySansPolicy)); fail("Exception expected"); } catch (IllegalArgumentException exp) { } } private void validateChain(X509Certificate[] chain, X509Certificate[] trustedCerts) throws Exception { validateError(chain, trustedCerts, ProxyPathValidatorException.FAILURE); } private void validateChain(X509Certificate[] chain, X509Certificate[] trustedCerts, X509Certificate expectedIdentity, boolean expectedLimited) throws Exception { TestProxyPathValidator v = new TestProxyPathValidator(); v.validate(chain, new TrustedCertificates(trustedCerts)); assertEquals(expectedLimited, v.isLimited()); assertEquals(expectedIdentity, v.getIdentityCertificate()); } private void validateError(X509Certificate[] chain, X509Certificate[] trustedCerts, int expectedErrorCode) throws Exception { TestProxyPathValidator v = new TestProxyPathValidator(); try { v.validate(chain); fail("Did not throw exception as expected"); } catch (ProxyPathValidatorException e) { // COMMENT ignore error codes, because new code works with strings //assertEquals(expectedErrorCode, e.getErrorCode()); } } // for testing only to disable validity checking class TestProxyPathValidator extends ProxyPathValidator { boolean policyChk = false; MockProxyCertPathValidator validator; TestProxyPathValidator() { super(); policyChk = false; validator = new MockProxyCertPathValidator(false, false, false); } TestProxyPathValidator(boolean checkSigningPolicy) { policyChk = checkSigningPolicy; validator = new MockProxyCertPathValidator(false, false, true); } public void validate(X509Certificate[] certPath) throws ProxyPathValidatorException { super.setValidator(validator); super.validate(certPath); } public void validate(X509Certificate[] certPath, TrustedCertificates trustedCerts) throws ProxyPathValidatorException { super.setValidator(validator); super.validate(certPath, trustedCerts); } public void validate(X509Certificate[] certPath, TrustedCertificates trustedCerts, CertificateRevocationLists crlsList, Boolean enforceSigningPolicy) throws ProxyPathValidatorException { super.setValidator(validator); super.validate(certPath, trustedCerts, crlsList, enforceSigningPolicy); } } // for testing only to disable validity checking public class MockProxyCertPathValidator extends X509ProxyCertPathValidator { boolean checkCertificateDateValidity; boolean checkCRLDateValidity; boolean checkSigningPolicy; private CertificateChecker dateChecker = new DateValidityChecker(); public MockProxyCertPathValidator(boolean checkCertificateDateValidity_, boolean checkCRLDateValidity_, boolean checkSigningPolicy_) { this.checkCertificateDateValidity = checkCertificateDateValidity_; this.checkCRLDateValidity = checkCRLDateValidity_; this.checkSigningPolicy = checkSigningPolicy_; } @Override protected List getCertificateCheckers() { List checkers = new ArrayList(); if (checkCertificateDateValidity) { checkers.add(dateChecker); } checkers.add(new UnsupportedCriticalExtensionChecker()); checkers.add(new IdentityChecker(this)); checkers.add(new CRLChecker(this.certStore, this.keyStore, this.checkCertificateDateValidity)); if (this.checkSigningPolicy) { checkers.add(new SigningPolicyChecker(this.policyStore)); } return checkers; } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/proxy/ext/000077500000000000000000000000001241116057200276035ustar00rootroot00000000000000ProxyCertInfoTest.java000066400000000000000000000074031241116057200340060ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/proxy/ext/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.proxy.ext; import org.bouncycastle.asn1.ASN1InputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import org.globus.gsi.proxy.ext.ProxyPolicy; import org.globus.gsi.proxy.ext.ProxyCertInfo; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import junit.framework.TestCase; public class ProxyCertInfoTest extends TestCase { String testPolicy = "blahblah"; DERObjectIdentifier testOid = new DERObjectIdentifier("1.2.3.4.5"); public void testCreateProxyCertInfo() throws Exception { ProxyPolicy policy = new ProxyPolicy(testOid, testPolicy); ProxyCertInfo info = new ProxyCertInfo(3, policy); assertEquals(3, info.getPathLenConstraint()); assertEquals(testPolicy, info.getProxyPolicy().getPolicyAsString()); assertEquals(testOid, info.getProxyPolicy().getPolicyLanguage()); } public void testParseProxyCertInfo() throws Exception { ProxyPolicy policy = new ProxyPolicy(testOid, testPolicy); ProxyCertInfo info = new ProxyCertInfo(3, policy); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(info); ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream dIn = new ASN1InputStream(bIn); ASN1Primitive obj = dIn.readObject(); assertTrue(obj instanceof ASN1Sequence); ProxyCertInfo testInfo = new ProxyCertInfo((ASN1Sequence)obj); assertEquals(3, testInfo.getPathLenConstraint()); assertEquals(testPolicy, testInfo.getProxyPolicy().getPolicyAsString()); assertEquals(testOid, testInfo.getProxyPolicy().getPolicyLanguage()); } public void testConstraintsCheck() throws Exception { ProxyPolicy policy; try { policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION, testPolicy); fail("Did not throw exception as expected"); } catch (IllegalArgumentException e) { } try { policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT, testPolicy); fail("Did not throw exception as expected"); } catch (IllegalArgumentException e) { } } public void testCreateProxyCertInfo2() throws Exception { ProxyPolicy policy = new ProxyPolicy(testOid, testPolicy); ProxyCertInfo info = new ProxyCertInfo(policy); assertEquals(Integer.MAX_VALUE, info.getPathLenConstraint()); assertEquals(testPolicy, info.getProxyPolicy().getPolicyAsString()); assertEquals(testOid, info.getProxyPolicy().getPolicyLanguage()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(info); ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream dIn = new ASN1InputStream(bIn); ASN1Primitive obj = dIn.readObject(); ProxyCertInfo testInfo = new ProxyCertInfo((ASN1Sequence)obj); assertEquals(Integer.MAX_VALUE, testInfo.getPathLenConstraint()); assertEquals(testPolicy, testInfo.getProxyPolicy().getPolicyAsString()); assertEquals(testOid, testInfo.getProxyPolicy().getPolicyLanguage()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/stores/000077500000000000000000000000001241116057200271415ustar00rootroot00000000000000ResourceSigningPolicyStoreTest.java000066400000000000000000000116311241116057200360720ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/stores/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.globus.gsi.stores; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.gsi.SigningPolicy; import java.io.File; import java.io.FileInputStream; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; /** * User: AmilaJ (amilaj@apache.org) * Date: 6/11/13 * Time: 10:26 AM */ public class ResourceSigningPolicyStoreTest extends TestCase { private String caCertsLocation; private Log logger = LogFactory.getLog(getClass()); public void setUp() throws Exception { String projectDirectory = System.getProperty("projectDirectory"); if (projectDirectory == null) { projectDirectory = "src/test/resources/org/globus/gsi/stores/"; File f = new File(projectDirectory); if (!f.isDirectory()) { projectDirectory = "ssl-proxies/src/test/resources/org/globus/gsi/stores/"; } } else { projectDirectory = projectDirectory + "/src/test/resources/org/globus/gsi/stores/"; } File projectDir = new File(projectDirectory); caCertsLocation = projectDir.getAbsolutePath(); logger.info("CA cert location is set to " + caCertsLocation); } public void testGetSigningPolicyWithOutDNPrincipal() throws Exception { String sigPolPattern = caCertsLocation + "/*.signing_policy"; ResourceSigningPolicyStore sigPolStore = new ResourceSigningPolicyStore(new ResourceSigningPolicyStoreParameters(sigPolPattern)); String certPath1 = caCertsLocation + "/ffc3d59b.0"; X509Certificate crt1 = readCertificate(certPath1); Assert.assertNotNull("Unable to read certificate in " + certPath1 ,crt1); // According to https://github.com/jglobus/JGlobus/issues/102 the second attempt is failing. // Therefore we query twice. SigningPolicy signingPolicy = sigPolStore.getSigningPolicy(crt1.getSubjectX500Principal()); Assert.assertNotNull(signingPolicy); signingPolicy = sigPolStore.getSigningPolicy(crt1.getSubjectX500Principal()); Assert.assertNotNull(signingPolicy); } public void testGetSigningPolicyWithDNPrincipal() throws Exception { String sigPolPattern = caCertsLocation + "/*.signing_policy"; ResourceSigningPolicyStore sigPolStore = new ResourceSigningPolicyStore(new ResourceSigningPolicyStoreParameters(sigPolPattern)); String certPath1 = caCertsLocation + "/e5cc84c2.0"; X509Certificate crt1 = readCertificate(certPath1); Assert.assertNotNull("Unable to read certificate in " + certPath1 ,crt1); SigningPolicy signingPolicy = sigPolStore.getSigningPolicy(crt1.getSubjectX500Principal()); Assert.assertNotNull(signingPolicy); // According to https://github.com/jglobus/JGlobus/issues/102 the second attempt is failing. // Therefore we query twice. signingPolicy = sigPolStore.getSigningPolicy(crt1.getSubjectX500Principal()); Assert.assertNotNull(signingPolicy); } private X509Certificate readCertificate(String certPath) { try { FileInputStream fr = new FileInputStream(certPath); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate crt = (X509Certificate) cf.generateCertificate(fr); logger.info("Read certificate:"); logger.info("\tCertificate for: " + crt.getSubjectDN()); logger.info("\tCertificate issued by: " + crt.getIssuerDN()); logger.info("\tCertificate is valid from " + crt.getNotBefore() + " to " + crt.getNotAfter()); logger.info("\tCertificate SN# " + crt.getSerialNumber()); logger.info("\tGenerated with " + crt.getSigAlgName()); return crt; } catch (Exception e) { e.printStackTrace(); } return null; } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/util/000077500000000000000000000000001241116057200265775ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/util/CertificateUtilTest.java000066400000000000000000000276201241116057200333710ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.globus.gsi.testutils.FileSetupUtil; import org.globus.gsi.util.CertificateLoadUtil; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.security.GeneralSecurityException; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.security.auth.x500.X500Principal; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class CertificateUtilTest { String validCert1 = "-----BEGIN CERTIFICATE-----\n" + "MIID+DCCAuCgAwIBAgIBKTANBgkqhkiG9w0BAQUFADB1MRMwEQYKCZImiZPyLGQB\n" + "GRYDbmV0MRIwEAYKCZImiZPyLGQBGRYCRVMxDjAMBgNVBAoTBUVTbmV0MSAwHgYD\n" + "VQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEYMBYGA1UEAxMPRVNuZXQgUm9v\n" + "dCBDQSAxMB4XDTAyMTIwNTA4MDAwMFoXDTEzMDEyNTA4MDAwMFowaTETMBEGCgmS\n" + "JomT8ixkARkWA29yZzEYMBYGCgmSJomT8ixkARkWCERPRUdyaWRzMSAwHgYDVQQL\n" + "ExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEWMBQGA1UEAxMNRE9FR3JpZHMgQ0Eg\n" + "MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT11iNho9sIPma1uJBv\n" + "sprfLWoCbRlyooIVyJZx97wrBy7L22Me4iwt/1ki12QNbjHLyy5r2cmXHcqXCO26\n" + "ZMy062DfkpkKSdR3wozhUZNIV0tUb0Bs1rJ5/vpxpUIYzX6PIXQurTeRq4Y49Nw1\n" + "9l7VNlrd7Vz2tzyWNXk5JZr+Z+wIALJLnMUha7TIgM3Il1/6fSHBo83nfCWWknfS\n" + "1oP4kGNDuHaTjFFbN5rOcs5v07O1lVED/WxXN76JzMWHbHBrhV0bLR4gg/DWl+9j\n" + "DE7fqubRLXT2q9uw2Vqug9FvF6s8pqRAukp7TfhdzHuAE+pST8XGhFFaKfkRY3ev\n" + "P0sCAwEAAaOBnjCBmzAOBgNVHQ8BAf8EBAMCAYYwEQYJYIZIAYb4QgEBBAQDAgCH\n" + "MB0GA1UdDgQWBBTKGR0Sjm6kOF1C1DEOCNvZjRcNXTAfBgNVHSMEGDAWgBS8XU1I\n" + "L/g1lFmrXIlLPtGyOhQB6jAPBgNVHRMBAf8EBTADAQH/MCUGA1UdEQQeMByBGkRP\n" + "RUdyaWRzLUNBLTFAZG9lZ3JpZHMub3JnMA0GCSqGSIb3DQEBBQUAA4IBAQBk1Wsg\n" + "Mup7f0IQ6Im3tDsSkE+ECKEy8NNJ//ja7RIxtSYKHDDiYuamHkMGCFlRUXxifn2R\n" + "FkyfVAs607UfMuq8C88hNpxlU+UmAbYhfOVHrfpiCFkUDJxshQQ4kMEdHi+1A7Uo\n" + "PGBnC8Bu2YoijG+FQKrbGx8W32QIEGf4li1Do7kuwEmrc+a65t4xxzuZtAB8lnuH\n" + "/dCCGCQUiGYTX4sFc8luS4/y+B+DqHYEqgB/lMV9kQKAZkqKZ83XXS0G9950ZnBh\n" + "h3f8awlzzcHQk3WCfLSCo1U+bf3ZRyFcZ4FGseebaCSEiSvjw6roSY0ZX39rpd9u\n" + "mVBb8lZu09U9aRqL\n" + "-----END CERTIFICATE-----"; String invalidCert1 = "MB0GA1UdDgQWBBTKGR0Sjm6kOF1C1DEOCNvZjRcNXTAfBgNVHSMEGDAWgBS8XU1I\n" + "L/g1lFmrXIlLPtGyOhQB6jAPBgNVHRMBAf8EBTADAQH/MCUGA1UdEQQeMByBGkRP\n" + "RUdyaWRzLUNBLTFAZG9lZ3JpZHMub3JnMA0GCSqGSIb3DQEBBQUAA4IBAQBk1Wsg\n" + "Mup7f0IQ6Im3tDsSkE+ECKEy8NNJ//ja7RIxtSYKHDDiYuamHkMGCFlRUXxifn2R\n" + "FkyfVAs607UfMuq8C88hNpxlU+UmAbYhfOVHrfpiCFkUDJxshQQ4kMEdHi+1A7Uo\n" + "PGBnC8Bu2YoijG+FQKrbGx8W32QIEGf4li1Do7kuwEmrc+a65t4xxzuZtAB8lnuH\n" + "/dCCGCQUiGYTX4sFc8luS4/y+B+DqHYEqgB/lMV9kQKAZkqKZ83XXS0G9950ZnBh\n" + "h3f8awlzzcHQk3WCfLSCo1U+bf3ZRyFcZ4FGseebaCSEiSvjw6roSY0ZX39rpd9u\n" + "mVBb8lZu09U9aRqL\n" + "-----END CERTIFICATE-----"; String invalidCert2 = "-----BEGIN CERTIFICATE-----\n" + "MIID+DCCAuCgAwIBAgIBKTANBgkqhkiG9w0BAQUFADB1MRMwEQYKCZImiZPyLGQB\n" + "GRYDbmV0MRIwEAYKCZImiZPyLGQBGRYCRVMxDjAMBgNVBAoTBUVTbmV0MSAwHgYD\n" + "VQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEYMBYGA1UEAxMPRVNuZXQgUm9v\n" + "dCBDQSAxMB4XDTAyMTIwNTA4MDAwMFoXDTEzMDEyNTA4MDAwMFowaTETMBEGCgmS\n" + "JomT8ixkARkWA29yZzEYMBYGCgmSJomT8ixkARkWCERPRUdyaWRzMSAwHgYDVQQL\n" + "ExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEWMBQGA1UEAxMNRE9FR3JpZHMgQ0Eg\n" + "MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT11iNho9sIPma1uJBv\n" + "sprfLWoCbRlyooIVyJZx97wrBy7L22Me4iwt/1ki12QNbjHLyy5r2cmXHcqXCO26\n" + "ZMy062DfkpkKSdR3wozhUZNIV0tUb0Bs1rJ5/vpxpUIYzX6PIXQurTeRq4Y49Nw1\n"; String invalidCrl1 = "-----BEGIN X509 CRL-----\n" + "MIIBLDCBljANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0IENBMjESMBAG\n" + "A1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdBcNMDYwNTIzMDEy\n" + "NjEwWhcNMDcwNTIzMDEyNjEwWjAoMBICAQIXDTA2MDUyMzAxMTM1MFowEgIBAxcN"; FileSetupUtil testCert1; FileSetupUtil testCert2; FileSetupUtil testCrl1; @Before public void setup() throws Exception { this.testCert1 = new FileSetupUtil("certificateUtilTest/1c3f2ca8.0"); this.testCert2 = new FileSetupUtil("certificateUtilTest/b38b4d8c-invalid.0"); this.testCrl1 = new FileSetupUtil("certificateUtilTest/validCrl.r0"); } @Test public void testReadCertificate() throws Exception { BufferedReader reader = new BufferedReader(new StringReader(this.validCert1)); X509Certificate cert = CertificateLoadUtil.readCertificate(reader); assert (cert != null); reader = new BufferedReader(new StringReader(this.invalidCert1)); boolean expected = false; try { cert = CertificateLoadUtil.readCertificate(reader); } catch (GeneralSecurityException e) { if ((e.getMessage().indexOf( "Certificate needs to start with BEGIN CERTIFICATE")) != -1) { expected = true; } } assertTrue(expected); reader = new BufferedReader(new StringReader(this.invalidCert1)); expected = false; try { cert = CertificateLoadUtil.readCertificate(reader); } catch (GeneralSecurityException e) { if ((e.getMessage().indexOf( "Certificate needs to start with BEGIN CERTIFICATE")) != -1) { expected = true; } } assertTrue(expected); } @Test public void testLoadCertificate() throws Exception { { this.testCert1.copyFileToTemp(); X509Certificate cert = CertificateLoadUtil .loadCertificate(testCert1.getAbsoluteFilename()); assert (cert != null); this.testCert2.copyFileToTemp(); boolean worked = false; try { cert = CertificateLoadUtil .loadCertificate(testCert2.getAbsoluteFilename()); } catch (GeneralSecurityException e) { String err = e.getMessage(); if (err != null && err.indexOf("BEGIN CERTIFICATE") != -1) { worked = true; } } assertTrue(worked); } } @Test public void testLoadCrl() throws Exception { this.testCrl1.copyFileToTemp(); X509CRL crl = CertificateLoadUtil.loadCrl(testCrl1.getAbsoluteFilename()); assert (crl != null); ByteArrayInputStream in = new ByteArrayInputStream(this.invalidCrl1.getBytes()); boolean worked = false; try { crl = CertificateLoadUtil.loadCrl(in); } catch (GeneralSecurityException e) { worked = true; } assertTrue(worked); } @Test public void testToGlobusIdForString() { String dn = CertificateUtil.toGlobusID("DC=org, DC=DOEGrids, OU=Certificate Authorities, CN=DOEGrids CA 1", true); assertThat(dn, is("/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1")); } @Test public void testToGlobusIdForReverseString() { String dn = CertificateUtil.toGlobusID("CN=DOEGrids CA 1, OU=Certificate Authorities, DC=DOEGrids, DC=org", false); assertThat(dn, is("/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1")); } @Test public void testToGlobusIdForX500Principal() { String dn = CertificateUtil.toGlobusID( new X500Principal("CN=DOEGrids CA 1, OU=Certificate Authorities, DC=DOEGrids, DC=org")); assertThat(dn, is("/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1")); } @Test public void testToPrincipal() { X500Principal principal = CertificateUtil.toPrincipal("/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1"); assertThat(principal, is(new X500Principal( "CN=DOEGrids CA 1, OU=Certificate Authorities, DC=DOEGrids, DC=org"))); } @Test public void testToPrincipalWithSlashInAttribute() { X500Principal principal = CertificateUtil.toPrincipal("/DC=org/DC=DOEGrids/OU=Certificate / Authorities/CN=DOEGrids CA 1"); assertThat(principal, is(new X500Principal( "CN=DOEGrids CA 1, OU=Certificate / Authorities, DC=DOEGrids, DC=org"))); } @Test public void testToPrincipalWithEmptyAttribute() { X500Principal principal = CertificateUtil.toPrincipal("/DC=org/DC=DOEGrids//CN=DOEGrids CA 1"); assertThat(principal, is(new X500Principal( "CN=DOEGrids CA 1, DC=DOEGrids, DC=org"))); } @Test public void testToPrincipalWithEmptyString() { X500Principal principal = CertificateUtil.toPrincipal(""); assertThat(principal, is(new X500Principal(""))); } @Test public void testToPrincipalWithWhiteSpace() { X500Principal principal = CertificateUtil.toPrincipal(" /DC=org/ DC=DOEGrids/OU=Certificate Authorities / CN=DOEGrids CA 1 "); assertThat(principal, is(new X500Principal( "CN=DOEGrids CA 1, OU=Certificate Authorities, DC=DOEGrids, DC=org"))); } @Test public void testToPrincipalWithRdnUnknownToJre() { String dn = "/DC=org/DC=terena/DC=tcs/C=FI/PostalCode=02101/ST=Uusimaa/L=Espoo/STREET=P.O. Box " + "405/O=CSC/OU=satellite.csc.fi/CN=liuske.csc.fi"; X500Principal principal = CertificateUtil.toPrincipal(dn); String newDn = CertificateUtil.toGlobusID(principal); assertThat(newDn, is(dn)); } @Test public void testToPrincipalWithUrl() { String dn = "/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network" + "/OU=http://www.usertrust.com/CN=UTN-USERFirst-Client Authentication and Email"; X500Principal principal = CertificateUtil.toPrincipal(dn); String newDn = CertificateUtil.toGlobusID(principal); assertThat(newDn, is(dn)); } @Test public void testToPrincipalWithComma() { String dn = "/C=DE/ST=Hamburg/O=dCache.ORG/CN=Gena, Crocodile"; X500Principal principal = CertificateUtil.toPrincipal(dn); String newDn = CertificateUtil.toGlobusID(principal); assertThat(newDn, is(dn)); } @After public void tearDown() { this.testCert1.deleteFile(); this.testCert2.deleteFile(); this.testCrl1.deleteFile(); } } TestSigningPolicyFileParser.java000066400000000000000000000426071241116057200347670ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/gsi/util/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.globus.gsi.SigningPolicyException; import java.io.StringReader; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; import javax.security.auth.x500.X500Principal; import org.globus.gsi.SigningPolicy; import org.globus.gsi.SigningPolicyParser; import org.globus.gsi.testutils.FileSetupUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestSigningPolicyFileParser { FileSetupUtil successFile; FileSetupUtil singleAllowedDn; FileSetupUtil[] tabTestFiles; @Before public void setup() throws Exception { this.successFile = new FileSetupUtil( "certificateUtilTest/samplePolicy.signing_policy"); this.singleAllowedDn = new FileSetupUtil("certificateUtilTest/5aba75cb.signing_policy"); this.tabTestFiles = new FileSetupUtil[3]; this.tabTestFiles[0] = new FileSetupUtil("certificateUtilTest/afe55e66.signing_policy"); this.tabTestFiles[1] = new FileSetupUtil("certificateUtilTest/cf4ba8c8.signing_policy"); this.tabTestFiles[2] = new FileSetupUtil("certificateUtilTest/49f18420.signing_policy"); } @Test public void testPatternMatching() throws Exception { // test getPattern method // no wildcards or question marks String patternStr = "CN=abcdefgh"; String patternR = (SigningPolicyParser.getPattern(patternStr)) .pattern(); assertTrue("CN=abcdefgh".equals(patternR)); // first character wildcard and question marks String pattern1Str = "CN=*def?gh?"; Pattern pattern1 = SigningPolicyParser.getPattern(pattern1Str); String pattern1R = pattern1.pattern(); assertTrue(("CN=" + SigningPolicyParser.WILDCARD_PATTERN + "def" + SigningPolicyParser.SINGLE_PATTERN + "gh" + SigningPolicyParser.SINGLE_PATTERN).equals(pattern1R)); // only wild cards String pattern2Str = "/CN=abc*def*gh"; Pattern pattern2 = SigningPolicyParser.getPattern(pattern2Str); String pattern2R = pattern2.pattern(); assertTrue( ("/CN=abc" + SigningPolicyParser.WILDCARD_PATTERN + "def" + SigningPolicyParser.WILDCARD_PATTERN + "gh").equals( pattern2R)); // test isValidDN methods // Add patern2, wildcards in middle Vector allowed = new Vector(); allowed.add(pattern2); X500Principal fooPrincipal = new X500Principal("CN=foo"); SigningPolicy policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject21 = new X500Principal("CN=abc12DEF34defdef56gh"); assertTrue(policy.isValidSubject(subject21)); X500Principal subject22 = new X500Principal("CN=123abc12def34defdef56gh"); assertFalse(policy.isValidSubject(subject22)); X500Principal subject23 = new X500Principal("CN=abc12def34defdef56gh123"); assertFalse(policy.isValidSubject(subject23)); // wildcard as first and last character String pattern3Str = "*abc*def*gh*"; Pattern pattern3 = SigningPolicyParser.getPattern(pattern3Str); allowed.clear(); allowed.add(pattern3); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject31 = new X500Principal("CN=ABC12def34defdef56gh"); assertTrue(policy.isValidSubject(subject31)); X500Principal subject32 = new X500Principal("CN=123abc12def34defdef56gh555"); assertTrue(policy.isValidSubject(subject32)); // use of space and slashes, from old signing policy file String pattern4Str = "/C=US/O=Globus/*"; Pattern pattern4 = SigningPolicyParser.getPattern(pattern4Str); allowed.clear(); allowed.add(pattern4); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject41 = new X500Principal( "CN=Globus Certification Authority, O=Globus, C=US"); assertTrue(policy.isValidSubject(subject41)); // wildcard as first character, question mark String pattern5Str = "/*C=US/O=Globus/CN=foo-?/CN=*"; Pattern pattern5 = SigningPolicyParser.getPattern(pattern5Str); allowed.clear(); allowed.add(pattern5); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject51 = new X500Principal( "CN=Globus Certification Authority, O=Globus, O=US"); assertFalse(policy.isValidSubject(subject51)); X500Principal subject52 = new X500Principal( "CN=test space,CN=a12b,CN=foo-1,O=Globus,C=US,C=SOME"); assertTrue(policy.isValidSubject(subject52)); X500Principal subject53 = new X500Principal("CN=,CN=foo-k,O=Globus,C=US"); assertTrue(policy.isValidSubject(subject53)); X500Principal subject54 = new X500Principal("CN= , CN=foo-1, O=Globus, C=US"); assertTrue(policy.isValidSubject(subject54)); X500Principal subject55 = new X500Principal("C=US,O=Globus,CN=foo-123,CN="); assertFalse(policy.isValidSubject(subject55)); // multiple question mark with punctuation String pattern6Str = "/C=US/O=global/CN=*/CN=user-??"; Pattern pattern6 = SigningPolicyParser.getPattern(pattern6Str); allowed.clear(); allowed.add(pattern6); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject61 = new X500Principal("CN=user-12,CN=foo,O=Globus,C=US"); assertFalse(policy.isValidSubject(subject61)); X500Principal subject62 = new X500Principal("CN=user-12,CN=foo,O=Global,C=US"); assertTrue(policy.isValidSubject(subject62)); X500Principal subject63 = new X500Principal("CN=user-12,CN=bar 1,CN=foo ,O=global,C=US"); assertTrue(policy.isValidSubject(subject63)); // add multiple patterns and test validity if atleast one matches String pattern7Str = "/C=US/O=Globus/CN=*/CN=user-??"; Pattern pattern7 = SigningPolicyParser.getPattern(pattern7Str); allowed.add(pattern7); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject71 = new X500Principal("CN=user-12, CN=bar 1, CN=foo , O=Globus,C=US"); assertTrue(policy.isValidSubject(subject71)); assertTrue(policy.isValidSubject(subject63)); } // JGLOBUS-103 @Test public void testFileSuccess() throws Exception { this.successFile.copyFileToTemp(); SigningPolicyParser parser = new SigningPolicyParser(); Map map = parser.parse(this.successFile.getAbsoluteFilename()); assertTrue(map != null); SigningPolicy policy = map.get(new X500Principal( "CN=Globus Certification Authority,O=Globus,C=US")); assertTrue(policy != null); List allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); List patterns = new Vector(2); patterns.add((allowedDN.get(0)).pattern()); patterns.add((allowedDN.get(1)).pattern()); // given the getPattern method is already tested, assuming it // works here. Pattern p1 = SigningPolicyParser.getPattern("/C=us/O=Globus/*"); assertTrue(patterns.contains(p1.pattern())); p1 = SigningPolicyParser.getPattern("/C=US/O=Globus/*"); assertTrue(patterns.contains(p1.pattern())); p1 = SigningPolicyParser .getPattern("/C=us/O=National Computational Science Alliance/*"); assertFalse(patterns.contains(p1.pattern())); policy = map.get(new X500Principal( "CN=Globus Certification Authority,O=National Computational Science Alliance,C=US")); assertTrue(policy != null); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 1); patterns.clear(); patterns.add(((Pattern) allowedDN.get(0)).pattern()); p1 = SigningPolicyParser .getPattern("/C=us/O=National Computational Science Alliance/*"); assertTrue(patterns.contains(p1.pattern())); // test file with single allows DN without double quotes this.singleAllowedDn.copyFileToTemp(); map.clear(); map = parser.parse(this.singleAllowedDn.getAbsoluteFilename()); policy = map.get(new X500Principal( "OU=Certification Authority,O=National Computational Science Alliance,C=US")); assertTrue(policy != null); allowedDN.clear(); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 1); patterns = new Vector(1); patterns.add(((Pattern) allowedDN.get(0)).pattern()); p1 = SigningPolicyParser .getPattern("/C=US/O=National Computational Science Alliance/*"); assertTrue(patterns.contains(p1.pattern())); } @Test public void testFilesWithTab() throws Exception { this.tabTestFiles[0].copyFileToTemp(); SigningPolicyParser parser = new SigningPolicyParser(); Map map = parser.parse(this.tabTestFiles[0].getAbsoluteFilename()); SigningPolicy policy = map.get(new X500Principal("CN=CyGridCA,O=HPCL,O=CyGrid,C=CY")); assertTrue(policy != null); List allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 1); allowedDN.clear(); map.clear(); this.tabTestFiles[1].copyFileToTemp(); map = parser.parse(this.tabTestFiles[1].getAbsoluteFilename()); policy = map.get(new X500Principal("CN=CNRS,O=CNRS,C=FR")); assertTrue(policy != null); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); Vector patterns = new Vector(2); patterns.add(((Pattern) allowedDN.get(0)).pattern()); patterns.add(((Pattern) allowedDN.get(1)).pattern()); // given the getPattern method is already tested, assuming it // works here. Pattern p1 = SigningPolicyParser .getPattern("/C=FR/O=CNRS/CN=CNRS-Projets"); assertTrue(patterns.contains(p1.pattern())); p1 = SigningPolicyParser.getPattern("/C=FR/O=CNRS/CN=CNRS"); assertTrue(patterns.contains(p1.pattern())); allowedDN.clear(); map.clear(); this.tabTestFiles[2].copyFileToTemp(); map = parser.parse(this.tabTestFiles[2].getAbsoluteFilename()); policy = map.get( new X500Principal("CN=INFN Certification Authority,O=INFN,C=IT")); assertTrue(policy != null); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); patterns.clear(); patterns.add(((Pattern) allowedDN.get(0)).pattern()); patterns.add(((Pattern) allowedDN.get(1)).pattern()); // given the getPattern method is already tested, assuming it // works here. p1 = SigningPolicyParser.getPattern("/C=it/O=INFN/*"); assertTrue(patterns.contains(p1.pattern())); p1 = SigningPolicyParser.getPattern("/C=IT/O=INFN/*"); assertTrue(patterns.contains(p1.pattern())); } @Test(expected = SigningPolicyException.class) public void testFileFailure() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); parser.parse("Foo"); } @Test public void testParsingFailure() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); // not x509 String error1 = "access_id_CA notX509 '/C=US/O=Globus/CN=Globus " + "Certification Authority'\n pos_rights globus CA:sign\n" + " cond_subjects globus '\"/C=us/O=Globus/*\" \"/C=US/O=Globus/*\"'"; Map map = null; boolean worked = false; try { map = parser.parse(new StringReader(error1)); } catch (IllegalArgumentException e) { worked = true; } assertTrue(worked); // not globus error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus " + "Certification Authority'\n pos_rights notglobus " + "CA:sign\n cond_subjects globus '\"/C=us/O=Globus/*\" " + "\"/C=US/O=Globus/*\"'"; map = parser.parse(new StringReader(error1)); // order of rights matter, atleast one positive right implies // allowed DN error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification " + "Authority'\n pos_rights globus CA:sign\n cond_subjects" + " globus '\"/C=us/O=Globus/*\" \"/C=US/O=Globus/*\"' \n " + "neg_rights notglobus some:right"; map = parser.parse(new StringReader(error1)); SigningPolicy policy = map.get(new X500Principal( "CN=Globus Certification Authority,O=Globus,C=US")); assertTrue(policy != null); List allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); // incorrect start error1 = "X509 '/C=US/O=Globus/CN=Globus Certification Authority'\n" + " pos_rights notglobus CA:sign\n cond_subjects " + "globus \'\"/C=us/O=Globus/*\" \"/C=US/O=Globus/*\"\'"; boolean exception = false; try { map = parser.parse(new StringReader(error1)); } catch (SigningPolicyException exp) { exception = true; } assertTrue(exception); // erroneous quote error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification " + "Authority\n pos_rights notglobus CA:sign\n " + "cond_subjects globus \'\"/C=us/O=Globus/*\" " + "\"/C=US/O=Globus/*\"\'"; exception = false; try { map = parser.parse(new StringReader(error1)); } catch (SigningPolicyException exp) { if ((exp.getMessage().indexOf("invalid")) != -1) { exception = true; } } assertTrue(exception); // neg rights rather than restrictions error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus " + "Certification Authority'\n pos_rights globus " + "CA:sign\n neg_rights notglobus some:right"; exception = false; try { map = parser.parse(new StringReader(error1)); } catch (SigningPolicyException exp) { // if ((exp.getMessage().indexOf("File format is incorrect") != -1) && // (exp.getMessage(). // indexOf("neg_rights cannot be used here") != -1)) { exception = true; // } } assertTrue(exception); // first pos_rights is all that matters error1 = "access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification " + "Authority'\n pos_rights globus CA:sign\n " + "cond_subjects globus '\"/C=us/O=Globus/*\" " + "\"/C=US/O=Globus/*\"' \n cond_subjects globus " + "'\"/C=us/O=Globus/*\"'"; map = parser.parse(new StringReader(error1)); policy = map.get(new X500Principal( "CN=Globus Certification Authority,O=Globus,C=US")); assertTrue(policy != null); allowedDN = policy.getAllowedDNs(); assertTrue(allowedDN != null); assertTrue(allowedDN.size() == 2); } @After public void cleanUp() throws Exception { this.singleAllowedDn.deleteFile(); this.successFile.deleteFile(); this.tabTestFiles[0].deleteFile(); this.tabTestFiles[1].deleteFile(); this.tabTestFiles[2].deleteFile(); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/util/000077500000000000000000000000001241116057200260155ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/util/CircularBufferTest.java000066400000000000000000000036611241116057200324240ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import junit.framework.TestCase; import org.globus.util.CircularBuffer; public class CircularBufferTest extends TestCase { private CircularBuffer buffer; protected void setUp() throws Exception { buffer = new CircularBuffer(5); } public void testInterruptBoth() throws Exception { assertTrue(buffer.put("a")); assertTrue(buffer.put("b")); buffer.interruptBoth(); assertTrue(!buffer.put("c")); assertTrue(!buffer.put("d")); assertEquals(null, buffer.get()); assertEquals(null, buffer.get()); } public void testPutFull() throws Exception { assertTrue(buffer.put("a")); assertTrue(buffer.put("b")); assertTrue(buffer.put("c")); assertTrue(buffer.put("d")); assertTrue(buffer.put("e")); Thread t = (new Thread() { public void run() { buffer.closePut(); buffer.interruptPut(); } }); t.start(); assertTrue(!buffer.put("f")); assertTrue(!buffer.put("g")); assertEquals("a", buffer.get()); assertEquals("b", buffer.get()); assertEquals("c", buffer.get()); assertEquals("d", buffer.get()); assertEquals("e", buffer.get()); assertEquals(null, buffer.get()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/util/GlobusURLTest.java000066400000000000000000000116451241116057200313450ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import junit.framework.TestCase; import org.globus.util.GlobusURL; public class GlobusURLTest extends TestCase { public void testParse() { GlobusURL url = null; try { url = new GlobusURL("file://host1"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "file", "host1", -1, null, null, null); try { url = new GlobusURL("http:///file1"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "", 80, "file1", null, null); try { url = new GlobusURL("http://host1:124"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 124, null, null, null); try { url = new GlobusURL("http://host1:124/"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 124, null, null, null); try { url = new GlobusURL("http://host1/mis/ptys"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 80, "mis/ptys", null, null); try { url = new GlobusURL("http://usr@host1"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 80, null, "usr", null); try { url = new GlobusURL("http://usr:@host1:124"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 124, null, "usr", ""); try { url = new GlobusURL("http://usr:pwd@host1:124//mis"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 124, "/mis", "usr", "pwd"); try { url = new GlobusURL(" gsiftp://localhost/foo"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "gsiftp", "localhost", 2811, "foo", null, null); } private void checkUrl(GlobusURL url, String protocol, String host, int port, String urlPath, String user, String pwd) { assertEquals("protocol", protocol, url.getProtocol()); assertEquals("host", host, url.getHost()); assertEquals("port", port, url.getPort()); assertEquals("urlpath", urlPath, url.getPath()); assertEquals("user", user, url.getUser()); assertEquals("pwd", pwd, url.getPwd()); } public void testParseBad() { try { new GlobusURL("http:/host1"); fail("The url was parsed ok!"); } catch (Exception e) { } } public void testEquals1() { GlobusURL url, url2, url3; url = url2 = url3 = null; try { url = new GlobusURL("http://host1:123/jarek"); url2 = new GlobusURL("http://host1:123/jarek"); url3 = new GlobusURL("ftp://host1:123/jarek"); } catch (Exception e) { } assertTrue("c1", url.equals("HTTP://host1:123/jarek")); assertTrue("c2", !url.equals("HTTP://host1:123/Jarek")); assertTrue("c3", url.equals(url)); assertTrue("c4", url.equals(url2)); assertTrue("c5", !url.equals(url3)); } public void testIPv6Address() { GlobusURL url = null; try { url = new GlobusURL("http://[1080:0:0:0:8:800:200C:417A]/index.html"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "[1080:0:0:0:8:800:200C:417A]", 80, "index.html", null, null); try { url = new GlobusURL("hdl://[3ffe:2a00:100:7031::1]:123"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "hdl", "[3ffe:2a00:100:7031::1]", 123, null, null, null); try { url = new GlobusURL("p1://gawor:123@[3ffe:2a00:100:7031::1]:123/testFile"); } catch (Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "p1", "[3ffe:2a00:100:7031::1]", 123, "testFile", "gawor", "123"); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/util/StringTokenizerTest.java000066400000000000000000000051131241116057200326610ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import junit.framework.TestCase; import org.globus.util.QuotedStringTokenizer; public class StringTokenizerTest extends TestCase { public void test1() { QuotedStringTokenizer s = new QuotedStringTokenizer("this"); assertEquals("this", s.nextToken()); } public void test2() { QuotedStringTokenizer s = new QuotedStringTokenizer(" this is test "); assertEquals("this", s.nextToken()); assertEquals("is", s.nextToken()); assertEquals("test", s.nextToken()); } public void test3() { QuotedStringTokenizer s = new QuotedStringTokenizer("b this \"is\" test a"); assertEquals("b", s.nextToken()); assertEquals("this", s.nextToken()); assertEquals("is", s.nextToken()); assertEquals("test", s.nextToken()); assertEquals("a", s.nextToken()); } public void test4() { QuotedStringTokenizer s = new QuotedStringTokenizer("b this \"is\" 't\"est' \"a"); assertEquals("b", s.nextToken()); assertEquals("this", s.nextToken()); assertEquals("is", s.nextToken()); assertEquals("t\"est", s.nextToken()); assertEquals("a", s.nextToken()); } public void test5() { QuotedStringTokenizer s = new QuotedStringTokenizer("b this \"jar\\\\ek\" 't\"est' \"a"); assertEquals(5, s.countTokens()); assertEquals("b", s.nextToken()); assertEquals("this", s.nextToken()); assertEquals(3, s.countTokens()); assertEquals("jar\\ek", s.nextToken()); assertEquals("t\"est", s.nextToken()); assertEquals(1, s.countTokens()); assertEquals(true, s.hasMoreTokens()); assertEquals("a", s.nextToken()); assertEquals(0, s.countTokens()); assertEquals(false, s.hasMoreTokens()); assertEquals(null, s.nextToken()); assertEquals(false, s.hasMoreTokens()); assertEquals(null, s.nextToken()); assertEquals(0, s.countTokens()); } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/java/org/globus/util/UtilTest.java000066400000000000000000000051661241116057200304450ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.util; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.util.Util; public class UtilTest extends TestCase { private Log logger = LogFactory.getLog(UtilTest.class); private static final String uStr1 = "(exe = mis)"; private static final String qStr1 = "\"(exe = mis)\""; private static final String uStr2 = "(exe = \"mis\")"; private static final String qStr2 = "\"(exe = \\\"mis\\\")\""; private static final String uStr3 = "(exe = \"mis\"\\test)"; private static final String qStr3 = "\"(exe = \\\"mis\\\"\\\\test)\""; public void testQuote1() { String tStr1 = Util.quote(uStr1); logger.debug(uStr1 + " : " + tStr1); assertEquals("t1", qStr1, tStr1); String tStr2 = Util.quote(uStr2); logger.debug(uStr2 + " : " + tStr2); assertEquals("t2", qStr2, tStr2); String tStr3 = Util.quote(uStr3); logger.debug(uStr3 + " : " + tStr3); assertEquals("t3", qStr3, tStr3); } public void testUnQuote1() { try { String tStr0 = Util.unquote(uStr1); logger.debug(uStr1 + " : " + tStr0); assertEquals("t0", uStr1, tStr0); } catch (Exception e) { fail("Unquote failed."); } try { String tStr1 = Util.unquote(qStr1); logger.debug(qStr1 + " : " + tStr1); assertEquals("t1", uStr1, tStr1); } catch (Exception e) { fail("Unquote failed."); } try { String tStr2 = Util.unquote(qStr2); logger.debug(qStr2 + " : " + tStr2); assertEquals("t2", uStr2, tStr2); } catch (Exception e) { fail("Unquote failed."); } try { String tStr3 = Util.unquote(qStr3); logger.debug(qStr3 + " : " + tStr3); assertEquals("t3", uStr3, tStr3); } catch (Exception e) { fail("Unquote failed."); } } } JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/000077500000000000000000000000001241116057200240475ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest/000077500000000000000000000000001241116057200300275ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest/1c3f2ca8.0000066400000000000000000000026341241116057200313270ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIID+DCCAuCgAwIBAgIBKTANBgkqhkiG9w0BAQUFADB1MRMwEQYKCZImiZPyLGQB GRYDbmV0MRIwEAYKCZImiZPyLGQBGRYCRVMxDjAMBgNVBAoTBUVTbmV0MSAwHgYD VQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEYMBYGA1UEAxMPRVNuZXQgUm9v dCBDQSAxMB4XDTAyMTIwNTA4MDAwMFoXDTEzMDEyNTA4MDAwMFowaTETMBEGCgmS JomT8ixkARkWA29yZzEYMBYGCgmSJomT8ixkARkWCERPRUdyaWRzMSAwHgYDVQQL ExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEWMBQGA1UEAxMNRE9FR3JpZHMgQ0Eg MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT11iNho9sIPma1uJBv sprfLWoCbRlyooIVyJZx97wrBy7L22Me4iwt/1ki12QNbjHLyy5r2cmXHcqXCO26 ZMy062DfkpkKSdR3wozhUZNIV0tUb0Bs1rJ5/vpxpUIYzX6PIXQurTeRq4Y49Nw1 9l7VNlrd7Vz2tzyWNXk5JZr+Z+wIALJLnMUha7TIgM3Il1/6fSHBo83nfCWWknfS 1oP4kGNDuHaTjFFbN5rOcs5v07O1lVED/WxXN76JzMWHbHBrhV0bLR4gg/DWl+9j DE7fqubRLXT2q9uw2Vqug9FvF6s8pqRAukp7TfhdzHuAE+pST8XGhFFaKfkRY3ev P0sCAwEAAaOBnjCBmzAOBgNVHQ8BAf8EBAMCAYYwEQYJYIZIAYb4QgEBBAQDAgCH MB0GA1UdDgQWBBTKGR0Sjm6kOF1C1DEOCNvZjRcNXTAfBgNVHSMEGDAWgBS8XU1I L/g1lFmrXIlLPtGyOhQB6jAPBgNVHRMBAf8EBTADAQH/MCUGA1UdEQQeMByBGkRP RUdyaWRzLUNBLTFAZG9lZ3JpZHMub3JnMA0GCSqGSIb3DQEBBQUAA4IBAQBk1Wsg Mup7f0IQ6Im3tDsSkE+ECKEy8NNJ//ja7RIxtSYKHDDiYuamHkMGCFlRUXxifn2R FkyfVAs607UfMuq8C88hNpxlU+UmAbYhfOVHrfpiCFkUDJxshQQ4kMEdHi+1A7Uo PGBnC8Bu2YoijG+FQKrbGx8W32QIEGf4li1Do7kuwEmrc+a65t4xxzuZtAB8lnuH /dCCGCQUiGYTX4sFc8luS4/y+B+DqHYEqgB/lMV9kQKAZkqKZ83XXS0G9950ZnBh h3f8awlzzcHQk3WCfLSCo1U+bf3ZRyFcZ4FGseebaCSEiSvjw6roSY0ZX39rpd9u mVBb8lZu09U9aRqL -----END CERTIFICATE----- 49f18420.signing_policy000066400000000000000000000002721241116057200337110ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest# EACL INFN CA access_id_CA X509 '/C=IT/O=INFN/CN=INFN Certification Authority' pos_rights globus CA:sign cond_subjects globus '"/C=it/O=INFN/*" "/C=IT/O=INFN/*"' 5aba75cb.signing_policy000066400000000000000000000004621241116057200342020ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest# # Policy for the NCSA CA (cert 5aba75cb.0) # access_id_CA X509 '/C=US/O=National Computational Science Alliance/OU=Certification Authority' pos_rights globus CA:sign cond_subjects globus '/C=US/O=National Computational Science Alliance/*' # # End NCSA CA Policy # afe55e66.signing_policy000066400000000000000000000002121241116057200341300ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest# CL HPCLUCY CA access_id_CA X509 '/C=CY/O=CyGrid/O=HPCL/CN=CyGridCA' pos_rights globus CA:sign cond_subjects globus '"/C=CY/O=CyGrid/*"' JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest/b38b4d8c-invalid.0000066400000000000000000000017161241116057200327620ustar00rootroot00000000000000 MIICtTCCAh6gAwIBAgIBADANBgkqhkiG9w0BAQQFADBMMQswCQYDVQQGEwJVUzEY MBYGA1UEChMPR2xvYnVzIEFsbGlhbmNlMSMwIQYDVQQDExpHbG9idXMgQ2VydGlm aWNhdGUgU2VydmljZTAeFw0wMzA5MjkxNzI1NDhaFw0xMzA5MjYxNzI1NDhaMEwx CzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9HbG9idXMgQWxsaWFuY2UxIzAhBgNVBAMT Gkdsb2J1cyBDZXJ0aWZpY2F0ZSBTZXJ2aWNlMIGfMA0GCSqGSIb3DQEBAQUAA4GN ADCBiQKBgQDIAWpX+GngjO5ae8SNSDKRfOi4PvWV7iSjkXga3jyza55h6pFyCFbA SyOtod4DWBoYYuSN6Dwu64taJNhDiwwHgPhFqw7bwAWA6qtOyL5nUIYbw1qee+sk zMOuRL0YyNIx56yRkdxDIR7+DuLBPEBZhE3eFdZcRKB0J39r0ba4iwIDAQABo4Gm MIGjMB0GA1UdDgQWBBQ+yRRfNptBthJ8mKBcDcfs+xEBUTB0BgNVHSMEbTBrgBQ+ yRRfNptBthJ8mKBcDcfs+xEBUaFQpE4wTDELMAkGA1UEBhMCVVMxGDAWBgNVBAoT D0dsb2J1cyBBbGxpYW5jZTEjMCEGA1UEAxMaR2xvYnVzIENlcnRpZmljYXRlIFNl cnZpY2WCAQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQAW5s+xnyW0 BpKR0RnI1JeqdjAWvQrdTBVA51fTkNnxJepQ8XO4CDzDU7S41uT0hI/Md3OQIEAl ciJ5YZE824/LWACVK1FYR5jWjmMY94fOwMLdYTOFNuCGrlHBP/ki0mCJDS2ad4aK 37mf0SHPXOVHrTZcT1TSpDJ0PNltDrRb7g== -----END CERTIFICATE----- cf4ba8c8.signing_policy000066400000000000000000000002771241116057200342170ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest# EACL French CA, root level: CNRS access_id_CA X509 '/C=FR/O=CNRS/CN=CNRS' pos_rights globus CA:sign cond_subjects globus '"/C=FR/O=CNRS/CN=CNRS-Projets" "/C=FR/O=CNRS/CN=CNRS"' samplePolicy.signing_policy000066400000000000000000000032561241116057200353560ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest# ca-signing-policy.conf # # This is the configuration file describing the policy for what CAs are # allowed to sign whose certificates. # # This file is parsed from start to finish with a given CA and subject # name. # subject names may include the following wildcard characters: # * Matches any number of characters. # ? Matches any single character. # # CA names must be specified (no wildcards). Names containing whitespaces # must be included in single quotes, e.g. 'Certification Authority'. # Names must not contain new line symbols. # The value of condition attribute is represented as a set of regular # expressions. Each regular expression must be included in double quotes. # # This policy file dictates the following policy: # -The Globus CA can sign certificates for the Globus or the Alliance # -The Alliance CA can sign certificates for the Alliance (note that # this may not be the real DN for the Alliance CA). # # Format: #------------------------------------------------------------------------ # token type | def.authority | value #--------------|---------------|----------------------------------------- # ACL entry #1 | # Globus CA rights access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification Authority' pos_rights globus CA:sign cond_subjects globus '"/C=us/O=Globus/*" "/C=US/O=Globus/*"' # Alliance CA rights access_id_CA X509 '/C=US/O=National Computational Science Alliance/CN=Globus Certification Authority' pos_rights globus CA:sign cond_subjects globus '"/C=us/O=National Computational Science Alliance/*"' # End of ca-signing-policy.conf JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest/validCrl.r0000066400000000000000000000007171241116057200320370ustar00rootroot00000000000000-----BEGIN X509 CRL----- MIIBLDCBljANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0IENBMjESMBAG A1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdBcNMDYwNTIzMDEy NjEwWhcNMDcwNTIzMDEyNjEwWjAoMBICAQIXDTA2MDUyMzAxMTM1MFowEgIBAxcN MDYwNTIzMDExMzM1WjANBgkqhkiG9w0BAQQFAAOBgQBCGPIuGU+r1gSRqtmmxbCj EG6/YLpjb12rbW5ikD9MzuvXeQ/7N3xpTYml/kL2v+zOb4TJ9neokRqOc1k47OYf xYxGqTkH+ca5KgMhtHb5EnbI8CmrIuTJaDT8O/YmQCKchRKFxZ6s/eA6EO74GWYo cRMHFdSTx7aEQx8Z/xVF3w== -----END X509 CRL----- validPolicy1.signing_policy000066400000000000000000000032561241116057200352550ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/certificateUtilTest# ca-signing-policy.conf # # This is the configuration file describing the policy for what CAs are # allowed to sign whose certificates. # # This file is parsed from start to finish with a given CA and subject # name. # subject names may include the following wildcard characters: # * Matches any number of characters. # ? Matches any single character. # # CA names must be specified (no wildcards). Names containing whitespaces # must be included in single quotes, e.g. 'Certification Authority'. # Names must not contain new line symbols. # The value of condition attribute is represented as a set of regular # expressions. Each regular expression must be included in double quotes. # # This policy file dictates the following policy: # -The Globus CA can sign certificates for the Globus or the Alliance # -The Alliance CA can sign certificates for the Alliance (note that # this may not be the real DN for the Alliance CA). # # Format: #------------------------------------------------------------------------ # token type | def.authority | value #--------------|---------------|----------------------------------------- # ACL entry #1 | # Globus CA rights access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification Authority' pos_rights globus CA:sign cond_subjects globus '"/C=us/O=Globus/*" "/C=US/O=Globus/*"' # Alliance CA rights access_id_CA X509 '/C=US/O=National Computational Science Alliance/CN=Globus Certification Authority' pos_rights globus CA:sign cond_subjects globus '"/C=us/O=National Computational Science Alliance/*"' # End of ca-signing-policy.conf JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/key.pem000066400000000000000000000015671241116057200253530ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDDXeTIiMCf3hi1XiYlIWxmcoqAm3FPQlFQso1uZbc80YAsgWXJ rCz9PbCD5twpoNkRPEkMZvZSzEi+RR+KUR/opnTcGIixI3CEg0JYNDiu8sna7pS2 Sjt5skNjwsu1NlCWrlvZf6xBrCRclGKHmJ+WH0Of3uRNvDrLg9DBnlzOfwIDAQAB AoGAbvKJlKCk06UrXwRioT+D8gImSbb8+EfvKebcjs9Q6kcHhT7O8WLIAeDgt2eJ rFJeM32K9nIafRbqULOsn75GYbfv+3UKfUW+C4QQughcR/U+MCfMB/pCn2etRMkE OauGBQRlngLT/spuV8j+RoSFuUOmiyhn+2R9jsCQ00AaACECQQD0jRYbMyV5XPpd EuRNAw6xG1Lv5OCdswnWCYcbD4urtlBse2/pD2u3qce11PbUtPfqysXEqILmVBd8 J3QExf2ZAkEAzINW2vFMN2sQvqn0y/gI4VQHjEGzC87t1D4RfjlNknlBIw6a3LCN RmSHJQdQ/0L3LKVSdDyCUf6eJFxj5LFL1wJBAJ1MKo3wRghcH8XCIwrODqMoeh5H z5pf0NHVawui4ineqLg+ZWs5OgX2tLhmdSW4CUcCilbGNPxF1p1LGzr+xvECQCan kGwTfYdf+is/bmB7AhqsyjxtUo0h0Hv0O1QzOoE7397jbMvXpuwuJgkOp/WHT7al jL8hjLQ4vuU6fTsFc8MCQALSPPZgrBoL3D3w4z5Ca+C7nefJD6qZCwmKudl8Yz3B okH7S0dEAaH7W+57fMmp+RWQgGv85FagKGZqtq9jxH8= -----END RSA PRIVATE KEY----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/log4j.properties000066400000000000000000000005631241116057200272100ustar00rootroot00000000000000log4j.rootCategory=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c{2} %x - %m%n log4j.category.COM.claymoresystems.ptls.SSLDebug=OFF log4j.category.org.globus.security.gridmap=ERROR log4j.logger.org.globus.security.filestore=INFO JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/000077500000000000000000000000001241116057200246365ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/000077500000000000000000000000001241116057200261315ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/000077500000000000000000000000001241116057200267135ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/errors.properties000066400000000000000000000062301241116057200323460ustar00rootroot00000000000000proxyNotFound = [JGLOBUS-5] Proxy file ({0}) not found. encPrivKey = [JGLOBUS-6] Private key file must not be encrypted. ioError00 = [JGLOBUS-7] Failed to load credentials. secError00 = [JGLOBUS-8] Failed to load credentials. error00 = [JGLOBUS-9] Failed to load credentials. expired00 = [JGLOBUS-10] Expired credentials. noCerts00 = [JGLOBUS-11] No certificates loaded noKey00 = [JGLOBUS-12] No private key loaded certFileNull = [JGLOBUS-13] Certificate file is null noCertData = [JGLOBUS-14] Certificate data not found. crlFileNull = [JGLOBUS-15] CRL file is null noCrlData = [JGLOBUS-16] CRL data not found. proxyFileNull = [JGLOBUS-17] Proxy file is null credInpStreamNull = [JGLOBUS-18] Credential input stream cannot be null pemFooter = [JGLOBUS-19] PEM footer missing dataNull = [JGLOBUS-20] Data is null noPrivateKey = [JGLOBUS-21] PRIVATE KEY section not found. algNotSup = [JGLOBUS-22] Algorithm not supported. unsupEnc = [JGLOBUS-23] Unsupported encryption: \"{0}\" ivLength = [JGLOBUS-24] Expected IV length of \"{0}\" but got \"{1}\" oidNull = [JGLOBUS-25] OID is null certNull = [JGLOBUS-26] Certificate is null extensionNull = [JGLOBUS-27] Extension is null certReqVerification = [JGLOBUS-28] Certificate request verification failed restrictProxy = [JGLOBUS-29] Restricted proxy requires ProxyCertInfo extension invalidProxyType = [JGLOBUS-30] Invalid proxyType keyUsageExt = [JGLOBUS-31] KeyUsage extension present in isuer certificate, but also provided in X509Extension map. This is unsupported. unsupportedProxy = [JGLOBUS-32] Unsupported proxyType : \"{0}\" proxyCertCritical = [JGLOBUS-33] ProxyCertInfo extension must be critical proxyDNErr = [JGLOBUS-34] Issuer name + proxy CN entry is not equal to subject name certTypeErr = [JGLOBUS-35] Unexpected certificate type: \"{0}\" certChainNull = [JGLOBUS-36] Certificate chain is null octetExp = [JGLOBUS-37] Expected octet string byteArrayErr = [JGLOBUS-38] Failed to convert to byte array certVerifyError = [JGLOBUS-116] Certificate validation failed. #Signing policy errors invalidPosRights= File format is incorrect. pos_rights cannot be used here. Invalid line: \"{0}\" invalidNegRights= File format is incorrect. neg_rights cannot be used here. Invalid line: \"{0}\" invalidRestrictions= File format is incorrect. Restrictions cannot be used here. Invalid line: \"{0}\" invalidLine= File format is incorrect. Each line should start with access_id, pos_rights, neg_rights or cond_. Invalid line: \"{0}\" invalidAccessId = File format is incorrect. Expected line to start with access_id. Invalid line: \"{0}\" invalidTokens= Line format is incorrect, atleast three tokens are expected. Invalid line: \"{0}\" invalidSubjects= Line format is incorrect, subject DNs with space should be enclosed in quotes. Invalid line is: \"{0}\" emptySubjects= Line format is incorrect, subject DNs list is empty. Invalid line is: \"{0}\" unmatchedQuotes= Line format is incorrect, unmatched quotes. Invalid line is: \"{0}\" invalidCaDN = Line format is incorrect, CA DN with space should be enclosed in quotes. Invalid section of the line is: \"{0}\" invalidRestriction = Line format is incorrect, Mismatched quotations in allowed subjects. Invalid line is: \"{0}\" JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/gridmap/000077500000000000000000000000001241116057200303365ustar00rootroot00000000000000errors.properties000066400000000000000000000003031241116057200337050ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/gridmapglobusIdErr = [JGLOBUS-1] Globus ID missing: \"{0}\" userIdErr = [JGLOBUS-2] User ID mapping missing: \"{0}\" globusIdNull = [JGLOBUS-3] Globus ID is null userIdNull = [JGLOBUS-4] User ID is nullJGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/proxy/000077500000000000000000000000001241116057200300745ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/proxy/errors.properties000066400000000000000000000056071241116057200335360ustar00rootroot00000000000000proxyPolicyId = [JGLOBUS-74] Proxy Policy id is null proxyPolixyHandler = [JGLOBUS-75] Proxy Policy handler is null certsNull = [JGLOBUS-76] Certificate array is null unknownCA = [JGLOBUS-77] Unknown CA proxyErr00 = [JGLOBUS-78] CA certificate cannot sign Proxy Certificate proxyErr01 = [JGLOBUS-79] CA Certificate does not allow path length > \"{0}\" and path length is \"{1}\" proxyErr02 = [JGLOBUS-80] Proxy Certificate can only sign another proxy of the same type proxyErr03 = [JGLOBUS-81] Proxy Certificate cannot be used to sign another Proxy Certificate. Proxy path length constraint is 0. proxyErr04 = [JGLOBUS-82] Proxy Certificate does not allow path length > \"{0}\" and path length is \"{1}\" proxyErr05 = [JGLOBUS-83] End Entity Certificate can only sign Proxy Certificates proxyErr06 = [JGLOBUS-84] Unknown cert type \"{0}\" limitedProxy = [JGLOBUS-85] Limited proxies not accepted proxyErr07 = [JGLOBUS-86] Could not retreive ProxyCertInfo extension proxyErr08 = [JGLOBUS-87] Could not retreive ProxyPolicy from ProxyCertInfo extension proxyErr09 = [JGLOBUS-88] Unknown Policy \"{0}\" proxyErr10 = [JGLOBUS-89] KeyUsage extension present but keyCertSign bit not asserted proxyErr11 = [JGLOBUS-90] Proxy certificate cannot contain subject or issuer alternative name extension proxyErr12 = [JGLOBUS-91] Proxy certificate cannot have BasicConstraint CA=true proxyErr13 = [JGLOBUS-92] The keyCertSign and nonRepudiation bits must not be asserted in Proxy Certificate proxyErr14 = [JGLOBUS-93] Bad KeyUsage in Proxy Certificate proxyErr15 = [JGLOBUS-94] KeyUsage extension in Proxy Certificate is not critical proxyErr16 = [JGLOBUS-95] Unsuppored critical exception : \"{0}\" proxyErr17 = [JGLOBUS-96] Certificate \"{0}\" expired. Certificate valid till \"{1}\" and current time is \"{2}\" proxyErr18 = [JGLOBUS-97] Certificate \"{0}\" not yet valid. Certificate valid from \"{1}\" and current time is \"{2}\" proxyErr19 = [JGLOBUS-98] Trusted certificates are null, cannot verify CRLs proxyErr20 = [JGLOBUS-99] CRL verification failed proxyErr21 = [JGLOBUS-100] This certificate \"{0}\" is on a CRL proxyErr22 = [JGLOBUS-101] Extension is null proxyErr23 = [JGLOBUS-102] Oid cannot be changed proxyErr24 = [JGLOBUS-103] Critical property cannot be changed proxyErr25 = [JGLOBUS-104] Invalid sequnece proxyErr26 = [JGLOBUS-105] Unable convert byte array: proxyErr27 = [JGLOBUS-106] Unknown object in factory proxyErr28 = [JGLOBUS-107] ProxyCertInfo is null proxyErr29 = [JGLOBUS-108] Critical property cannot be changed proxyErr30 = [JGLOBUS-109] Invalid sequence proxyErr31 = [JGLOBUS-110] Policy langauge oid required proxyErr32 = [JGLOBUS-111] Constraints violation proxyErr33 = No signing policy file found for CA \"{0}\" proxyErr34 = \"{0}\" violates the signing policy defined for CA \"{1}\" in file \"{2}\" proxyErr35 = No relevant signing policy for CA \"{0}\" in file \"{1}\" proxyErr36 = CRL for CA \"{0}\" has expired. JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/ptls/000077500000000000000000000000001241116057200276755ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/ptls/errors.properties000066400000000000000000000003651241116057200333330ustar00rootroot00000000000000malformedName = [JGLOBUS-112] Malformed name, \"{0}\" missing in \"{1}\" invalidToken00 = [JGLOBUS-113] Token \"{0}\" does not start with '/' rdnMissing = [JGLOBUS-114] RDN \"{0}\" is missing '=' conversionFail = [JGLOBUS-115] Conversion failed.JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores/000077500000000000000000000000001241116057200302325ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores/e5cc84c2.0000066400000000000000000000027251241116057200315410ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIEIDCCAwigAwIBAgIBAjANBgkqhkiG9w0BAQUFADBuMRMwEQYKCZImiZPyLGQB GRMDRURVMRYwFAYKCZImiZPyLGQBGRMGVVRFWEFTMRQwEgYKCZImiZPyLGQBGRME VEFDQzESMBAGA1UEChMJVVQtQVVTVElOMRUwEwYDVQQDEwxUQUNDIFJvb3QgQ0Ew HhcNMDgxMDAyMDQwMjA0WhcNMTMxMDAxMDQwMjA0WjBxMRMwEQYKCZImiZPyLGQB GRMDRURVMRYwFAYKCZImiZPyLGQBGRMGVVRFWEFTMRQwEgYKCZImiZPyLGQBGRME VEFDQzESMBAGA1UEChMJVVQtQVVTVElOMRgwFgYDVQQDEw9UQUNDIENsYXNzaWMg Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCbmMzgAdglOWoY9CQV iNllCsS/wFIub2g7dZmiP7KJ0Fxz10DU6aBx5XkDeVe3iRje7nh9h1HTjnqNlMFh Il8eQISktuvajhxywuKDsf6N1sxQ5VE4jBwPncwa4LIuCcA7ECDPZ2aZvrPOSca/ cLHUBbi2z8aAq1vCHs5rGf0nl53E//bQY7Bbe6OpU2aY3MBDF1tK84+0eP9LLmhu +dol2VKYbMgwRDG5kZ20TdHXtaTBgjyXNS+mMoGJdE07zG5Wax9AFxerH+2ab9EQ BvEcIjFfxqurou7k/zu57Ye4d4TU3gq/09HYTfTh0gANB+daPjkNBm9CSSqQvxv9 FsyTAgMAkGOjgcUwgcIwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUbF3onuVy e3rRG5n2jLbRoXSCBwQwHwYDVR0jBBgwFoAUjXUjaNFVmWzDph6G/N/EU+jlU8cw DgYDVR0PAQH/BAQDAgEGMB0GA1UdEQQWMBSBEmNhQHRhY2MudXRleGFzLmVkdTBA BgNVHR8EOTA3MDWgM6Axhi9odHRwOi8vd3d3LnRhY2MudXRleGFzLmVkdS9DQS9U QUNDX1Jvb3RfQ1JMLmRlcjANBgkqhkiG9w0BAQUFAAOCAQEAb3jne8SKCsMHMKHX 6qh6V5xnkh8WmpIXdyXr7HRugVQT2XUjgdFs7yqBDz/cjhmzj4XkCoZNoZTD2jwT cycTKD/tFUf6nuSu0GZQAWs1zL58oSse2YSYcMoqeL9I/4eDNgi7b+gij3oUn1aR 3JJnr0ImHnsZrfGXcrSBGfVZY+wnYELXNUfKxfZNQJkIz/CZCFlIs+b+iOCuVjwk E6TOOcAXJHzQ9VdZLWxnukcQVK7iwX6Mv60YDqvLXL8OmH4ucvvHeWg5qWugEE8D cIjq9WdowSamDsHje8nzv6gKVHym4uiDO9mYq85nTLtzcqdEPox0PLGRwUzYIT+8 CDUwpw== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores/e5cc84c2.crl_url000066400000000000000000000000521241116057200330330ustar00rootroot00000000000000http://www.tacc.utexas.edu/CA/e5cc84c2.r0 e5cc84c2.signing_policy000066400000000000000000000003341241116057200343320ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores# TACC Classic CA Signing Policy access_id_CA X509 '/DC=EDU/DC=UTEXAS/DC=TACC/O=UT-AUSTIN/CN=TACC Classic CA' pos_rights globus CA:sign cond_subjects globus '"/DC=EDU/DC=UTEXAS/DC=TACC/O=UT-AUSTIN/O=TACC Classic CA/*"' e5cc84c2.tacc.cadesc000066400000000000000000000016371241116057200334570ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores# $Id: e5cc84c2.tacc.cadesc,v 1.1 2008/10/23 02:20:34 marg Exp $ CA_NAME TACC Classic Certification Authority HOMEPAGE http://www.tacc.utexas.edu/CA/ CONTACT ca@tacc.utexas.edu HASH e5cc84c2 SIGNED_BY /DC=EDU/DC=UTEXAS/DC=TACC/O=UT-AUSTIN/CN=TACC Root CA SUBJECT /DC=EDU/DC=UTEXAS/DC=TACC/O=UT-AUSTIN/CN=TACC Classic CA MAY_SIGN /DC=EDU/DC=UTEXAS/DC=TACC/O=UT-AUSTIN/O=TACC Classic CA/* CERTIFICATE_MD5 EA:31:04:07:7B:0A:04:EC:DD:B1:A2:75:29:39:83:98 CERTIFICATE_SHA1 5B:AE:F7:20:B1:3A:91:4F:1C:FE:8F:AF:5E:ED:48:DB:62:0E:47:65 CERTIFICATE_URL http://www.tacc.utexas.edu/CA/e5cc84c2.0 SIGNING_POLICY_URL http://www.tacc.utexas.edu/CA/e5cc84c2.signing_policy # CERT_BEGINS Thu 2008-10-02 04:02:04 UTC CERT_EXPIRES Tue 2013-10-01 04:02:04 UTC CRL_URL http://www.tacc.utexas.edu/CA/e5cc84c2.r0 e5cc84c2.tacc.cadesc.sig000066400000000000000000000007231241116057200342330ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores-----BEGIN PGP SIGNATURE----- Version: 9.10.0.500 iQEVAwUATCotnbY5Ggxzc9voAQgJSQf/YbjNFde83PJt1FebHFXjvgX4IY3GyqlL FaXpIIftd1aHi1vSkdTXqptwSE8H9TjKiouyhsvghvvTAGFXRuYHqwKIjZOyZcyW d2SGfjCgxRUkCLegfoPvAySPbzKKlJMs+q3yX6kbWStPv3nW42Z3GFuKq8C/qf5N aIgoWKjbWlWnEzlKsW6FsG6kx65h5Ive5jsvxKOV0sSHhwFDKRUBAiFE7Gczn7Dz 5zr6m9rUl8Ll00rlpbaS6ghR1zjYBJRn7dR/eIqqiZzAtBj6f+VQz6Ehx+vAys5v g13dRbz5wetaN7EFWOUjlzRz/lhHzCS55yIyt0X8LRemHKUe9pvqSw== =a5yr -----END PGP SIGNATURE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores/ffc3d59b.0000066400000000000000000000025271241116057200316260ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIDwzCCAqugAwIBAgICAQAwDQYJKoZIhvcNAQEFBQAwVDELMAkGA1UEBhMCVUsx FTATBgNVBAoTDGVTY2llbmNlUm9vdDESMBAGA1UECxMJQXV0aG9yaXR5MRowGAYD VQQDExFVSyBlLVNjaWVuY2UgUm9vdDAeFw0xMTA2MTgxMzAwMDBaFw0yNzEwMzAw OTAwMDBaMFMxCzAJBgNVBAYTAlVLMRMwEQYDVQQKEwplU2NpZW5jZUNBMRIwEAYD VQQLEwlBdXRob3JpdHkxGzAZBgNVBAMTElVLIGUtU2NpZW5jZSBDQSAyQjCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKkLgb2eIcly4LZfj0Rf5F7s+HE/ 6Tvpf4jsKkm7qs33y3EEudCbcPwQKjS2MgytPv+8xpEPHqy/hqTseNlZ6oJgc+V8 xlJ+0iws882Ca8a9ZJ/iGQH9UzXU4q35ArN3cbwoWAAvMvzZ6hUV86fAAQ1AueQN 6h7/tnfYfaUMiB4PNxucmouMHDJGmYzl47FtlLeHUr2c4m/oWSG5pADIvGFpWFHj NIw8/x4n97w5/ks0tc/8/5Q6xzUfCX/VfqciQCvKcui2J5MBhUlBDLenzwqvUytB 4XAwX/pRcKmnFEYwoc9OKGExNx9tn9RjQYJAC/KLb44Jqno9l0eRxu3uw4sCAwEA AaOBnzCBnDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjA5BgNVHR8E MjAwMC6gLKAqhihodHRwOi8vY3JsLmNhLm5ncy5hYy51ay9jcmwvcm9vdC1jcmwu ZGVyMB0GA1UdDgQWBBQSpb+Rn3/ir2pcCfLi+lngNuHzVTAfBgNVHSMEGDAWgBRe +BtIpndrKTwuAFMzK2Oie36TwDANBgkqhkiG9w0BAQUFAAOCAQEAFQlXpYR45+fy uKIh/c+7nIxODO5iWmKskxDSQhqhMCU8/d5WVfXZ35XoTakhhsxu+Q3smIa6AhbA meAhIWc2kDgDatEUlMA5G3TQgUoQgjw5RAWxX5/7biaj2nSU7B4Nn5llOp4g+p9P 5H+wGm2KFhvslaoKBKhSUkM/1teS+XsoDjqaPp/4RQ80ywUYhVWJz18vH1ltWLQW 93i3mnLDDb+aOyeoxqIPCQSy6Q8nIYoM8e3jYvdjjZNruT45g6IK6bx7eQmEMfO+ u7qJiCKWGMxY+72ZeOw/0DMw4y8kU0wrl7gQ1o1Jk94hHNpBam+hX0Btc1K7YwXB CemmHAuKQw== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores/ffc3d59b.crl_url000066400000000000000000000000531241116057200331210ustar00rootroot00000000000000http://crl.ca.ngs.ac.uk/crl/escience2b.crl ffc3d59b.signing_policy000066400000000000000000000003551241116057200344220ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/stores# @(#)$Id: ffc3d59b.signing_policy,v 1.3 2011/09/30 06:19:28 pmacvsdg Exp $ # access_id_CA X509 '/C=UK/O=eScienceCA/OU=Authority/CN=UK e-Science CA 2B' pos_rights globus CA:sign cond_subjects globus '"/C=UK/O=eScience/*"' JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/test/000077500000000000000000000000001241116057200276725ustar00rootroot0000000000000049f18420.signing_policy000066400000000000000000000002721241116057200335540ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/test# EACL INFN CA access_id_CA X509 '/C=IT/O=INFN/CN=INFN Certification Authority' pos_rights globus CA:sign cond_subjects globus '"/C=it/O=INFN/*" "/C=IT/O=INFN/*"' 5aba75cb.signing_policy000066400000000000000000000004621241116057200340450ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/test# # Policy for the NCSA CA (cert 5aba75cb.0) # access_id_CA X509 '/C=US/O=National Computational Science Alliance/OU=Certification Authority' pos_rights globus CA:sign cond_subjects globus '/C=US/O=National Computational Science Alliance/*' # # End NCSA CA Policy # afe55e66.signing_policy000066400000000000000000000002121241116057200337730ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/test# CL HPCLUCY CA access_id_CA X509 '/C=CY/O=CyGrid/O=HPCL/CN=CyGridCA' pos_rights globus CA:sign cond_subjects globus '"/C=CY/O=CyGrid/*"' cf4ba8c8.signing_policy000066400000000000000000000002771241116057200340620ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/test# EACL French CA, root level: CNRS access_id_CA X509 '/C=FR/O=CNRS/CN=CNRS' pos_rights globus CA:sign cond_subjects globus '"/C=FR/O=CNRS/CN=CNRS-Projets" "/C=FR/O=CNRS/CN=CNRS"' samplePolicy.signing_policy000066400000000000000000000032561241116057200352210ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/org/globus/gsi/test# ca-signing-policy.conf # # This is the configuration file describing the policy for what CAs are # allowed to sign whose certificates. # # This file is parsed from start to finish with a given CA and subject # name. # subject names may include the following wildcard characters: # * Matches any number of characters. # ? Matches any single character. # # CA names must be specified (no wildcards). Names containing whitespaces # must be included in single quotes, e.g. 'Certification Authority'. # Names must not contain new line symbols. # The value of condition attribute is represented as a set of regular # expressions. Each regular expression must be included in double quotes. # # This policy file dictates the following policy: # -The Globus CA can sign certificates for the Globus or the Alliance # -The Alliance CA can sign certificates for the Alliance (note that # this may not be the real DN for the Alliance CA). # # Format: #------------------------------------------------------------------------ # token type | def.authority | value #--------------|---------------|----------------------------------------- # ACL entry #1 | # Globus CA rights access_id_CA X509 '/C=US/O=Globus/CN=Globus Certification Authority' pos_rights globus CA:sign cond_subjects globus '"/C=us/O=Globus/*" "/C=US/O=Globus/*"' # Alliance CA rights access_id_CA X509 '/C=US/O=National Computational Science Alliance/CN=Globus Certification Authority' pos_rights globus CA:sign cond_subjects globus '"/C=us/O=National Computational Science Alliance/*"' # End of ca-signing-policy.conf JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/ssl.properties000066400000000000000000000011151241116057200267640ustar00rootroot00000000000000# # Copyright 1999-2010 University of Chicago # # 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. # JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/000077500000000000000000000000001241116057200271055ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/1c3f2ca8.0000066400000000000000000000026341241116057200304050ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIID+DCCAuCgAwIBAgIBKTANBgkqhkiG9w0BAQUFADB1MRMwEQYKCZImiZPyLGQB GRYDbmV0MRIwEAYKCZImiZPyLGQBGRYCRVMxDjAMBgNVBAoTBUVTbmV0MSAwHgYD VQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEYMBYGA1UEAxMPRVNuZXQgUm9v dCBDQSAxMB4XDTAyMTIwNTA4MDAwMFoXDTEzMDEyNTA4MDAwMFowaTETMBEGCgmS JomT8ixkARkWA29yZzEYMBYGCgmSJomT8ixkARkWCERPRUdyaWRzMSAwHgYDVQQL ExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEWMBQGA1UEAxMNRE9FR3JpZHMgQ0Eg MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT11iNho9sIPma1uJBv sprfLWoCbRlyooIVyJZx97wrBy7L22Me4iwt/1ki12QNbjHLyy5r2cmXHcqXCO26 ZMy062DfkpkKSdR3wozhUZNIV0tUb0Bs1rJ5/vpxpUIYzX6PIXQurTeRq4Y49Nw1 9l7VNlrd7Vz2tzyWNXk5JZr+Z+wIALJLnMUha7TIgM3Il1/6fSHBo83nfCWWknfS 1oP4kGNDuHaTjFFbN5rOcs5v07O1lVED/WxXN76JzMWHbHBrhV0bLR4gg/DWl+9j DE7fqubRLXT2q9uw2Vqug9FvF6s8pqRAukp7TfhdzHuAE+pST8XGhFFaKfkRY3ev P0sCAwEAAaOBnjCBmzAOBgNVHQ8BAf8EBAMCAYYwEQYJYIZIAYb4QgEBBAQDAgCH MB0GA1UdDgQWBBTKGR0Sjm6kOF1C1DEOCNvZjRcNXTAfBgNVHSMEGDAWgBS8XU1I L/g1lFmrXIlLPtGyOhQB6jAPBgNVHRMBAf8EBTADAQH/MCUGA1UdEQQeMByBGkRP RUdyaWRzLUNBLTFAZG9lZ3JpZHMub3JnMA0GCSqGSIb3DQEBBQUAA4IBAQBk1Wsg Mup7f0IQ6Im3tDsSkE+ECKEy8NNJ//ja7RIxtSYKHDDiYuamHkMGCFlRUXxifn2R FkyfVAs607UfMuq8C88hNpxlU+UmAbYhfOVHrfpiCFkUDJxshQQ4kMEdHi+1A7Uo PGBnC8Bu2YoijG+FQKrbGx8W32QIEGf4li1Do7kuwEmrc+a65t4xxzuZtAB8lnuH /dCCGCQUiGYTX4sFc8luS4/y+B+DqHYEqgB/lMV9kQKAZkqKZ83XXS0G9950ZnBh h3f8awlzzcHQk3WCfLSCo1U+bf3ZRyFcZ4FGseebaCSEiSvjw6roSY0ZX39rpd9u mVBb8lZu09U9aRqL -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/1c3f2ca8.r0000066400000000000000000000205431241116057200305660ustar00rootroot00000000000000-----BEGIN X509 CRL----- MIIYfzCCF2cCAQEwDQYJKoZIhvcNAQEFBQAwaTETMBEGCgmSJomT8ixkARkWA29y ZzEYMBYGCgmSJomT8ixkARkWCERPRUdyaWRzMSAwHgYDVQQLExdDZXJ0aWZpY2F0 ZSBBdXRob3JpdGllczEWMBQGA1UEAxMNRE9FR3JpZHMgQ0EgMRcNMDkwODA2MTU0 OTIxWhcNMDkwOTA1MTU0OTIxWjCCFrcwEwICZzoXDTA4MDkyNTEzNDQ1NlowPAID AIUmFw0wOTA3MDgxODQyMDlaMCYwCgYDVR0VBAMKAQMwGAYDVR0YBBEYDzIwMDkw NzA4MDcwMDAwWjAiAgMAgKQXDTA5MDUxMzIyMDU0OFowDDAKBgNVHRUEAwoBBTAw AgMAhR8XDTA5MDcwOTIxNDc0MFowGjAYBgNVHRgEERgPMjAwOTA3MDkwNTAwMDBa MBMCAnkgFw0wOTA3MTMxOTM2NTdaMC8CAnYfFw0wOTA0MDIxNzQ0MDBaMBowGAYD VR0YBBEYDzIwMDkwNDAyMDUwMDAwWjAUAgMAhQoXDTA5MDcwNzEyNTAwN1owLwIC ZxwXDTA4MDkxOTE4NDAyOFowGjAYBgNVHRgEERgPMjAwODA5MTkwNTAwMDBaMCIC AwCAhxcNMDkwNTE0MjAwMDIwWjAMMAoGA1UdFQQDCgEEMC8CAnYJFw0wOTAxMjcx NTM5MTJaMBowGAYDVR0YBBEYDzIwMDkwMTI3MDYwMDAwWjATAgJokRcNMDgxMDIw MjAxMDMzWjAvAgJ2BxcNMDkwMTIzMTkwMzQ2WjAaMBgGA1UdGAQRGA8yMDA5MDEy MzA1MDAwMFowIQICboQXDTA5MDMxODIwMjAzMlowDDAKBgNVHRUEAwoBBTA7AgJo hxcNMDgxMjEyMjIyODQ0WjAmMAoGA1UdFQQDCgEDMBgGA1UdGAQRGA8yMDA4MTAw NjA3MDAwMFowIQICboMXDTA5MDMxODIwMjAwOVowDDAKBgNVHRUEAwoBBTAiAgMA gHIXDTA5MDYyNTE0MjYyNFowDDAKBgNVHRUEAwoBATATAgJ0eBcNMDkwNjE5MTYz MDQ0WjAhAgJ0dxcNMDgxMjMwMjMxMzMwWjAMMAoGA1UdFQQDCgEFMBMCAmV/Fw0w ODA5MjUxMzUzMzBaMCICAwCH5BcNMDkwODA0MTU0OTIwWjAMMAoGA1UdFQQDCgEB MBMCAnRvFw0wODEyMzAxNDQ5NTZaMC8CAndtFw0wOTAyMTEyMDEwMTBaMBowGAYD VR0YBBEYDzIwMDkwMjExMDUwMDAwWjAiAgMAh+EXDTA5MDgwNDAwMjE0NFowDDAK BgNVHRUEAwoBBTAUAgMAgeEXDTA5MDYwNDIxMDM0MVowIQICZXMXDTA4MDgyNjIw NTgyNVowDDAKBgNVHRUEAwoBBDATAgJlchcNMDgwOTI1MTM1MzAwWjAUAgMAgd4X DTA5MDYwNDIxMTQwOFowEwICZXEXDTA4MDkyNTEzNTIzNVowEwICZW4XDTA4MDky NTEzNTIxMlowIgIDAIBaFw0wOTA1MTUxNDUzMzRaMAwwCgYDVR0VBAMKAQQwFAID AIHZFw0wOTA2MDQyMTE0NTFaMBQCAwCB2BcNMDkwNjA0MjEyMDEwWjATAgJlZhcN MDgwOTI1MTM1MTQ3WjAhAgJ6URcNMDkwNTE1MTQ1MDUwWjAMMAoGA1UdFQQDCgEE MCECAnLPFw0wOTA2MTkxNjMwMTNaMAwwCgYDVR0VBAMKAQUwIQICZVcXDTA5MDMz MDE5Mzc1NlowDDAKBgNVHRUEAwoBBDAvAgJ0TBcNMDkwMTE0MTcwMDIxWjAaMBgG A1UdGAQRGA8yMDA5MDExNDA2MDAwMFowIQICZVUXDTA4MDgyNTE5MTE0NlowDDAK BgNVHRUEAwoBAzA7AgJ3SBcNMDkwMjEwMTcwNzAwWjAmMAoGA1UdFQQDCgEDMBgG A1UdGAQRGA8yMDA5MDIxMDA1MDAwMFowLwICfUQXDTA5MDQxMzE2NTkwOFowGjAY BgNVHRgEERgPMjAwOTA0MTMwNTAwMDBaMBQCAwCGPhcNMDkwNzI0MDA0MzI5WjAv AgJj0xcNMDgwODEyMjA1NTA1WjAaMBgGA1UdGAQRGA8yMDA4MDgxMjA1MDAwMFow LwICdEUXDTA4MTIyMzIyMDQzOFowGjAYBgNVHRgEERgPMjAwODEyMjMwNjAwMDBa MCICAwCAORcNMDkwNjA1MjE0NDMwWjAMMAoGA1UdFQQDCgEFMBQCAwCHshcNMDkw ODAzMjAzMTEzWjA7AgJyvxcNMDkwMjA5MTkyMzI0WjAmMAoGA1UdFQQDCgEEMBgG A1UdGAQRGA8yMDA4MDIwOTA2MDAwMFowIQICejYXDTA5MDMxNjIwMTQxMlowDDAK BgNVHRUEAwoBBTATAgJxOBcNMDgxMTE3MTY1MzIzWjAhAgJ3NBcNMDkwMjI1MjI1 NzU4WjAMMAoGA1UdFQQDCgEFMDsCAnoyFw0wOTAzMTYxODIwMTNaMCYwCgYDVR0V BAMKAQQwGAYDVR0YBBEYDzIwMDkwMzE2MDUwMDAwWjA7AgJ6MRcNMDkwMzE2MTgx OTIxWjAmMAoGA1UdFQQDCgEEMBgGA1UdGAQRGA8yMDA5MDMxNjA1MDAwMFowOwIC cTEXDTA4MTIxMjIyMTkwOVowJjAKBgNVHRUEAwoBAzAYBgNVHRgEERgPMjAwODEx MTcwODAwMDBaMC8CAncrFw0wOTA0MTAxODUwNDZaMBowGAYDVR0YBBEYDzIwMDkw NDEwMDUwMDAwWjAvAgJ3KBcNMDkwMzEyMjAxNjMwWjAaMBgGA1UdGAQRGA8yMDA5 MDMxMjA0MDAwMFowLwICcSkXDTA5MDExNDIwMzkzN1owGjAYBgNVHRgEERgPMjAw OTAxMTQwNjAwMDBaMCECAnKjFw0wODEyMTYyMjIwNDlaMAwwCgYDVR0VBAMKAQUw OwICdx8XDTA5MDIwOTE3NTc1N1owJjAKBgNVHRUEAwoBBDAYBgNVHRgEERgPMjAw OTAyMDkwNjAwMDBaMDsCAnceFw0wOTAyMDkxNzU2MTVaMCYwCgYDVR0VBAMKAQQw GAYDVR0YBBEYDzIwMDkwMjA5MDYwMDAwWjATAgJ9GRcNMDkwNDA4MTkxNDE1WjA7 AgJmpxcNMDkwMjA1MDIwNTM1WjAmMAoGA1UdFQQDCgEEMBgGA1UdGAQRGA8yMDA5 MDIwMTA1MDAwMFowEwICaCMXDTA4MTIxMzE3NTA0N1owOwICcpoXDTA5MDQyMDIy NTYzMlowJjAKBgNVHRUEAwoBATAYBgNVHRgEERgPMjAwOTA0MTcwNjAwMDBaMC8C AnuIFw0wOTAzMjUxOTE2NDNaMBowGAYDVR0YBBEYDzIwMDkwMzI1MDUwMDAwWjAv AgJ7hhcNMDkwMzI1MTc0MjA5WjAaMBgGA1UdGAQRGA8yMDA5MDMyNTA1MDAwMFow EwICZo8XDTA4MDkyNTEzNTUzNVowEwICZo4XDTA4MDkyNTEzNTUwNFowEwICZo0X DTA4MDkyNTEzNTQzM1owLwICe30XDTA5MDMyNDE4NTkwMFowGjAYBgNVHRgEERgP MjAwOTAzMjQwNTAwMDBaMC8CAm4CFw0wOTAzMzAyMTMxNThaMBowGAYDVR0YBBEY DzIwMDkwMzMwMDUwMDAwWjATAgJ1ehcNMDkwMTE1MjExMjU0WjAvAgJt/hcNMDgx MDE2MTUyODM0WjAaMBgGA1UdGAQRGA8yMDA4MTAxNTA2MDAwMFowOwICcnoXDTA5 MDcyODIxMjg1NlowJjAKBgNVHRUEAwoBATAYBgNVHRgEERgPMjAwOTA3MjcwNzAw MDBaMDsCAnJ5Fw0wOTA3MjgyMTI4NTZaMCYwCgYDVR0VBAMKAQEwGAYDVR0YBBEY DzIwMDkwNzI3MDcwMDAwWjATAgJmfhcNMDgwOTI1MTM1NDEwWjAhAgJ/7BcNMDkw NTA4MjIwMDIxWjAMMAoGA1UdFQQDCgEEMDACAwCEaRcNMDkwNzI4MjExOTE2WjAa MBgGA1UdGAQRGA8yMDA5MDcyNzA3MDAwMFowEwICZPkXDTA4MDkyNTEzNTEwN1ow LwICbfMXDTA5MDcyODIxMjIwNFowGjAYBgNVHRgEERgPMjAwOTA3MjcwNzAwMDBa MBMCAmT4Fw0wODA5MjUxMzUwMzBaMC8CAm3yFw0wOTA3MjgyMTIyMDRaMBowGAYD VR0YBBEYDzIwMDkwNzI3MDcwMDAwWjAvAgJ27BcNMDkwMjExMjAxMTE2WjAaMBgG A1UdGAQRGA8yMDA5MDIxMTA1MDAwMFowEwICZPcXDTA5MDcyMDE2MTAzN1owLwIC dWoXDTA5MDIxOTE4MzkwNlowGjAYBgNVHRgEERgPMjAwOTAyMTkwNjAwMDBaMBQC AwCF3hcNMDkwNzIwMTYxMTI1WjAvAgJ54xcNMDkwNDMwMTUxMDQ3WjAaMBgGA1Ud GAQRGA8yMDA5MDQzMDA0MDAwMFowEwICeeIXDTA5MDMxNTE3Mjk0N1owFAIDAIXX Fw0wOTA3MjExMzI2MzRaMCICAwCC1xcNMDkwNjA5MTU1NDU5WjAMMAoGA1UdFQQD CgEBMC8CAm9SFw0wOTAxMTQyMDM5MTJaMBowGAYDVR0YBBEYDzIwMDkwMTE0MDYw MDAwWjA7AgJyThcNMDgxMjA3MjIwMzAyWjAmMAoGA1UdFQQDCgEBMBgGA1UdGAQR GA8yMDA4MTIwNjA4MDAwMFowLwICZNYXDTA5MDIyNDIxMTE1M1owGjAYBgNVHRgE ERgPMjAwOTAyMjQwNjAwMDBaMBQCAwCEOxcNMDkwNjI5MTg0ODA5WjAhAgJkzhcN MDgwODE1MjMxNzAzWjAMMAoGA1UdFQQDCgEFMC8CAnJFFw0wODEyMTcxODQwMjda MBowGAYDVR0YBBEYDzIwMDgxMjE3MDUwMDAwWjATAgJkyhcNMDgwODE3MDAwNTU3 WjAvAgJyPRcNMDkwMTIwMTgxOTExWjAaMBgGA1UdGAQRGA8yMDA5MDEyMDA1MDAw MFowEwICZMQXDTA4MDkyNTEzNDk0M1owOwICZ8AXDTA4MTIwNjE1MjI0OFowJjAK BgNVHRUEAwoBATAYBgNVHRgEERgPMjAwODA5MjMwNTAwMDBaMDsCAm87Fw0wOTA0 MTQxOTU5MDZaMCYwCgYDVR0VBAMKAQQwGAYDVR0YBBEYDzIwMDkwNDE0MDQwMDAw WjAvAgJyNxcNMDgxMjA1MTM1NjUwWjAaMBgGA1UdGAQRGA8yMDA4MTIwNTA1MDAw MFowOwICV0kXDTA4MDMzMTIzMjgwOVowJjAKBgNVHRUEAwoBBDAYBgNVHRgEERgP MjAwODAzMzEwNzAwMDBaMDsCAnU0Fw0wOTAxMjIxODQxMjRaMCYwCgYDVR0VBAMK AQQwGAYDVR0YBBEYDzIwMDkwMTIxMDgwMDAwWjA7AgJnsxcNMDgwOTI0MjI1NDMy WjAmMAoGA1UdFQQDCgEFMBgGA1UdGAQRGA8yMDA4MDkyMjA3MDAwMFowLwICZLIX DTA5MDExMzE2MTQ0NVowGjAYBgNVHRgEERgPMjAwOTAxMTMwNjAwMDBaMDsCAnUk Fw0wOTA2MTUxOTUwMzlaMCYwCgYDVR0VBAMKAQEwGAYDVR0YBBEYDzIwMDkwNjEy MDQwMDAwWjAvAgJ7GxcNMDkwMzIwMTgxMzQ4WjAaMBgGA1UdGAQRGA8yMDA5MDMy MDA1MDAwMFowLwICZKkXDTA5MDIyNDIxMTEyOVowGjAYBgNVHRgEERgPMjAwOTAy MjQwNjAwMDBaMBMCAmSlFw0wODA5MDgxOTA2NTNaMBMCAngUFw0wOTAyMTkxOTUz MzFaMDsCAm8XFw0wODEwMzAxNjM4MzVaMCYwCgYDVR0VBAMKAQMwGAYDVR0YBBEY DzIwMDgxMDMwMDUwMDAwWjAvAgJ5jhcNMDkwMzEyMjAxNzAyWjAaMBgGA1UdGAQR GA8yMDA5MDMxMjA0MDAwMFowEwICchIXDTA5MDQwNzIzMDIwN1owLwICfgcXDTA5 MDQyNzE1MzU1NVowGjAYBgNVHRgEERgPMjAwOTA0MjcwNTAwMDBaMC8CAn4GFw0w OTA0MjcxNTM1MzhaMBowGAYDVR0YBBEYDzIwMDkwNDI3MDUwMDAwWjAvAgJklhcN MDgwODExMjAwMzA4WjAaMBgGA1UdGAQRGA8yMDA4MDgxMTA1MDAwMFowLwICZJUX DTA5MDQxMDE2MjYyNVowGjAYBgNVHRgEERgPMjAwOTA0MTAwNTAwMDBaMCECAnIJ Fw0wODEyMDEyMjUzMjVaMAwwCgYDVR0VBAMKAQUwLwICcIQXDTA4MTExMjE1MTYx OVowGjAYBgNVHRgEERgPMjAwODExMTIwNjAwMDBaMBMCAnICFw0wOTAxMDkxOTEy MzRaMBMCAnIBFw0wOTAxMDkxOTEyMzRaMC8CAnT/Fw0wOTAxMDkxNDM0MjdaMBow GAYDVR0YBBEYDzIwMDkwMTA5MDYwMDAwWjATAgJ5eRcNMDkwMzA2MTk1MTI4WjAT AgJ5eBcNMDkwMzA2MTk1MDUyWjATAgJ5dxcNMDkwMzA2MTk0OTA5WjATAgJ5dhcN MDkwMzA2MTk0OTU1WjATAgJ5dRcNMDkwMzA2MTk0ODIwWjATAgJ5dBcNMDkwMzA2 MTk0NTE0WjATAgJ5cxcNMDkwMzA2MTk0NzIyWjATAgJ5chcNMDkwMzA2MTk0NjE4 WjATAgJ5cRcNMDkwMzA2MTk0NDE2WjATAgJ5cBcNMDkwMzA2MTk0MjQ5WjAUAgMA hWYXDTA5MDcxMDE1MjI0NVowFAIDAIVkFw0wOTA3MTAxNTE5MDJaMCICAwCCZBcN MDkwNjA5MTU1MjQ1WjAMMAoGA1UdFQQDCgEBMBMCAmR3Fw0wODA5MjUxMzQ3NTla MDACAwCFWRcNMDkwNzIyMTg0MjE3WjAaMBgGA1UdGAQRGA8yMDA5MDcyMjA0MDAw MFowLwICdOIXDTA5MDEwOTE5MDU0MlowGjAYBgNVHRgEERgPMjAwOTAxMDkwNTAw MDBaMC8CAnxXFw0wOTA0MDMxODA3MzVaMBowGAYDVR0YBBEYDzIwMDkwNDAzMDUw MDAwWjAiAgMAgNMXDTA5MDUxODIxMDEyN1owDDAKBgNVHRUEAwoBBTAUAgMAg80X DTA5MDYyMjE5NDUyNVowLwICcFgXDTA4MTExMTIwMTA1MFowGjAYBgNVHRgEERgP MjAwODExMTEwNjAwMDBaMC8CAmRfFw0wODA4MDcxNTE3MTRaMBowGAYDVR0YBBEY DzIwMDgwODA3MDUwMDAwWjAvAgJl2RcNMDkwMTI0MTY0ODU3WjAaMBgGA1UdGAQR GA8yMDA5MDEyNDA1MDAwMFowLwICd80XDTA5MDIxMjIyMjY0NFowGjAYBgNVHRgE ERgPMjAwOTAyMTIwNTAwMDBaMDsCAnfGFw0wOTAyMTIxNzUzMDlaMCYwCgYDVR0V BAMKAQQwGAYDVR0YBBEYDzIwMDkwMjEyMDYwMDAwWjAvAgJnShcNMDgxMTE3MTcz NzIyWjAaMBgGA1UdGAQRGA8yMDA4MTExNzA2MDAwMFowPAIDAII3Fw0wOTA2MTkx OTE4MDdaMCYwCgYDVR0VBAMKAQEwGAYDVR0YBBEYDzIwMDkwNjE5MDQwMDAwWjAU AgMAg7UXDTA5MDYyMjEzMzc1MlowFAIDAIO0Fw0wOTA2MjIxMzM4MDdaMBQCAwCG rhcNMDkwNzMxMjAyNDUxWjA8AgMAhScXDTA5MDcwODIwMjgyNlowJjAKBgNVHRUE AwoBAzAYBgNVHRgEERgPMjAwOTA3MDgwNzAwMDBaoA8wDTALBgNVHRQEBAICCpQw DQYJKoZIhvcNAQEFBQADggEBAAojoY5/evh2vL1OC0aqZXQJC9+X3tkpgvdjndrs LZwj7kEYEw19mPDjcvQfx2LEJlh6i/ub8fsBzDIAoq9zeaPv39hWRX8hwWwJPNnF dPwnugu2YfnspwTAkIUzrWzNyKOYi8LCuK0VE7G9j4dk6n/zQfttPFCRSwgfSCYY Ghc1w7TfG+o2fAz6nCamVYF+p9lErCalnpXbEkYkLUpRU4ZKiwI+c8MJF0R4vCwQ 5yoBCAHznd0T2LWOh2rgcLALwLD6MAXLvuOXEyCSa9U/afeTuyWZo1/aqdfcAzSO ctQSl/0Jwuq6KFtARuNRkAbHSXHH3ZYj7xPfKy3vF9K39aY= -----END X509 CRL----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/1c3f2ca8.signing_policy000066400000000000000000000041201241116057200332530ustar00rootroot00000000000000# $Id: 1c3f2ca8.signing_policy,v 1.3 2006/08/23 23:07:04 dhiva Exp $ # ca-signing-policy.conf, see ca-signing-policy.doc for more information # # This is the configuration file describing the policy for what CAs are # allowed to sign whoses certificates. # # This file is parsed from start to finish with a given CA and subject # name. # subject names may include the following wildcard characters: # * Matches any number of characters. # ? Matches any single character. # # CA names must be specified (no wildcards). Names containing whitespaces # must be included in single quotes, e.g. 'Certification Authority'. # Names must not contain new line symbols. # The value of condition attribute is represented as a set of regular # expressions. Each regular expression must be included in double quotes. # # This policy file dictates the following policy: # # The DOEGrids CA signs certificates for doegrids.org # # Format: #------------------------------------------------------------------------ # token type | def.authority | value #--------------|---------------|----------------------------------------- # EACL entry #1| access_id_CA X509 '/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1' pos_rights globus CA:sign cond_subjects globus '"/DC=org/DC=DOEGrids/*" "/DC=org/DC=doegrids/*" "/O=DOEGrids.org/*" "/O=doegrids.org/*"' # # End DOE SG CA Policy # # $Log: 1c3f2ca8.signing_policy,v $ # Revision 1.3 2006/08/23 23:07:04 dhiva # updated with doesciencegrid string removal # # Revision 1.2 2003/05/27 16:29:35 helm # Change statement of policy # # Revision 1.1 2003/05/22 22:38:21 helm # *** empty log message *** # # Revision 1.4 2003/05/09 22:21:39 helm # doegrids # # Revision 1.3 2003/05/03 01:29:50 dhiva # modified the cond_subject # from /DC=/DOEGrids # to /DC=DOEGrids # # Revision 1.2 2003/05/03 01:16:38 dhiva # $Id: 1c3f2ca8.signing_policy,v 1.3 2006/08/23 23:07:04 dhiva Exp $ Included # # Revision 1.1 2003/05/03 01:15:05 dhiva # Globus Support Files for pki1.doegrids.org CA # JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/b38b4d8c.0000066400000000000000000000017511241116057200304130ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICtTCCAh6gAwIBAgIBADANBgkqhkiG9w0BAQQFADBMMQswCQYDVQQGEwJVUzEY MBYGA1UEChMPR2xvYnVzIEFsbGlhbmNlMSMwIQYDVQQDExpHbG9idXMgQ2VydGlm aWNhdGUgU2VydmljZTAeFw0wMzA5MjkxNzI1NDhaFw0xMzA5MjYxNzI1NDhaMEwx CzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9HbG9idXMgQWxsaWFuY2UxIzAhBgNVBAMT Gkdsb2J1cyBDZXJ0aWZpY2F0ZSBTZXJ2aWNlMIGfMA0GCSqGSIb3DQEBAQUAA4GN ADCBiQKBgQDIAWpX+GngjO5ae8SNSDKRfOi4PvWV7iSjkXga3jyza55h6pFyCFbA SyOtod4DWBoYYuSN6Dwu64taJNhDiwwHgPhFqw7bwAWA6qtOyL5nUIYbw1qee+sk zMOuRL0YyNIx56yRkdxDIR7+DuLBPEBZhE3eFdZcRKB0J39r0ba4iwIDAQABo4Gm MIGjMB0GA1UdDgQWBBQ+yRRfNptBthJ8mKBcDcfs+xEBUTB0BgNVHSMEbTBrgBQ+ yRRfNptBthJ8mKBcDcfs+xEBUaFQpE4wTDELMAkGA1UEBhMCVVMxGDAWBgNVBAoT D0dsb2J1cyBBbGxpYW5jZTEjMCEGA1UEAxMaR2xvYnVzIENlcnRpZmljYXRlIFNl cnZpY2WCAQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQAW5s+xnyW0 BpKR0RnI1JeqdjAWvQrdTBVA51fTkNnxJepQ8XO4CDzDU7S41uT0hI/Md3OQIEAl ciJ5YZE824/LWACVK1FYR5jWjmMY94fOwMLdYTOFNuCGrlHBP/ki0mCJDS2ad4aK 37mf0SHPXOVHrTZcT1TSpDJ0PNltDrRb7g== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/b38b4d8c.signing_policy000066400000000000000000000004261241116057200332670ustar00rootroot00000000000000#ACL entry #1 oly| access_id_CA X509 '/C=US/O=Globus Alliance/CN=Globus Certificate Service' pos_rights globus CA:sign cond_subjects globus '"/C=US/O=Globus Alliance/OU=Service/*" "/C=US/O=Globus Alliance/OU=User/*"' # end of EACL JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/ca.csr000066400000000000000000000013201241116057200301750ustar00rootroot00000000000000-----BEGIN CERTIFICATE REQUEST----- MIIB3DCCAUUCAQAwgYMxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhJbGxpbm9pczEQ MA4GA1UEBxMHQ2hpY2FnbzEPMA0GA1UEChMGR2xvYnVzMQ0wCwYDVQQLEwRDcnV4 MREwDwYDVQQDEwhUb20gSG93ZTEcMBoGCSqGSIb3DQEJARYNbm9uZUBub25lLmNv bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAoNF0u12nGOyk7k5U7Aa0gws/ QGxGzijW/clGt5YqUNiafn1qmSLyL300VCZRXXT9vNLu9SgTAKHrsVBlc2i4DhkN JCKk66kXDmp8xgNKiRkMobK8TgbRL2/mccpEQvSzZvRoR3gn7cAZFvy+8ZW1FSps xMpi+qN3PlyTYibiiS8CAwEAAaAYMBYGCSqGSIb3DQEJBzEJFgdQYXUxaWUhMA0G CSqGSIb3DQEBBQUAA4GBAHarTRxK6aGvhwEnf3xOy1OpbDvCxqs2Z+Yj0gFdUQpp xjeHkWcXGcW6LiqSmawg/yspN1wcXPy+QIHW28AStRSOoV7vGAaOAAtdx9QZUPhU nj21renh1Km8+zfbSYOWs1MQxXDXVGsRHeQz2xwvqEZHSmaA/Nc+FohWzZAmOpPA -----END CERTIFICATE REQUEST----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/d1b603c3.0000066400000000000000000000026501241116057200303160ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIEADCCAuigAwIBAgIBITANBgkqhkiG9w0BAQUFADB1MRMwEQYKCZImiZPyLGQB GRYDbmV0MRIwEAYKCZImiZPyLGQBGRYCRVMxDjAMBgNVBAoTBUVTbmV0MSAwHgYD VQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEYMBYGA1UEAxMPRVNuZXQgUm9v dCBDQSAxMB4XDTAyMTAwODA3MDAwMFoXDTIyMTAyNjA3MDAwMFowdTETMBEGCgmS JomT8ixkARkWA25ldDESMBAGCgmSJomT8ixkARkWAkVTMQ4wDAYDVQQKEwVFU25l dDEgMB4GA1UECxMXQ2VydGlmaWNhdGUgQXV0aG9yaXRpZXMxGDAWBgNVBAMTD0VT bmV0IFJvb3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALKF PX1QK86g62z/KX0pRAtRnS8VXmrLUDaFMwZyKEeueWxkrymyvnuDo4hCDPrIfEzI cAWnJyE1ev4aWw3l3Qm75GDUiyV401Op598iPT5bbCMlHJcYBANwRNKnvtZ8DcoU 9Ba75tqUQHV1TRx6Nkw1AQ5gNMQSuZ5wCsDREGs+Be3JRa06RJf8k5gw5odqBjCT kGmIwCcx1qEuLGXOcQoM+yEKZvD485MiPKaEKYJBRDHi0h+vvj1j8ge9SJ8Jy6ML 4B+2QNLb7fTjSutMF5qGJKlCgHw6dNLHuW2glS1KZ3Dt1iXkO6SdowclsKvpFhW9 fDIftu/TOcMLOJi5fgUCAwEAAaOBmjCBlzARBglghkgBhvhCAQEEBAMCAAcwIQYD VR0RBBowGIEWRVNuZXQtUm9vdC1DQS0xQGVzLm5ldDAPBgNVHRMBAf8EBTADAQH/ MB0GA1UdDgQWBBS8XU1IL/g1lFmrXIlLPtGyOhQB6jAfBgNVHSMEGDAWgBS8XU1I L/g1lFmrXIlLPtGyOhQB6jAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQEFBQAD ggEBAA7Gy/hGi6nKiwm2fAXvQNU7Oe86VGz92VPICxjCyCCMW3uYuFAJVTjB6wRM UH/fw01I+pC9CZ+RUIhxWqFKJiz+Wf3jkq+25rPQ2Ve5FTesB/urUncwqZKRaOk5 StSW5XQjCIfKk7W6q6BJk3nMAm67btSoRdE9NfsefEpHbJJ+dtjRgyJx+QX7sOft IsqHMWmEj7QTAjoCJvrSTXavHKosQ5s+aPySbZ6R6MCBzTsUzJk1fbTvrzJnzi0s H4eyZ17WxRj8BxnyN6BHM/0ger2b/c6vrfrW67/J6A0ebClbdunFdsYxPtcH49yo ugTqyKEVEeH7hhVkOH0bGf4Q0Vc= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/d1b603c3.r0000066400000000000000000000113101241116057200304710ustar00rootroot00000000000000Certificate Revocation List (CRL): Version 2 (0x1) Signature Algorithm: sha1WithRSAEncryption Issuer: /DC=net/DC=ES/O=ESnet/OU=Certificate Authorities/CN=ESnet Root CA 1 Last Update: Jul 16 18:41:13 2009 GMT Next Update: Jul 16 18:41:13 2010 GMT CRL extensions: X509v3 CRL Number: 90 Revoked Certificates: Serial Number: 2C Revocation Date: May 25 00:48:19 2007 GMT CRL entry extensions: X509v3 CRL Reason Code: Cessation Of Operation Serial Number: 26 Revocation Date: Oct 26 19:35:16 2006 GMT CRL entry extensions: X509v3 CRL Reason Code: Superseded Serial Number: 25 Revocation Date: Oct 26 19:35:00 2006 GMT CRL entry extensions: X509v3 CRL Reason Code: Superseded Serial Number: 0E Revocation Date: Jun 11 00:41:12 2003 GMT Serial Number: 23 Revocation Date: Oct 26 19:34:31 2006 GMT CRL entry extensions: X509v3 CRL Reason Code: Superseded Serial Number: 22 Revocation Date: Oct 26 19:34:02 2006 GMT CRL entry extensions: X509v3 CRL Reason Code: Superseded Serial Number: 0A Revocation Date: May 6 18:43:40 2003 GMT CRL entry extensions: X509v3 CRL Reason Code: Superseded Invalidity Date: May 6 07:00:00 2003 GMT Serial Number: 09 Revocation Date: Dec 6 02:13:21 2002 GMT CRL entry extensions: X509v3 CRL Reason Code: Superseded Invalidity Date: Dec 5 08:00:00 2002 GMT Serial Number: 06 Revocation Date: Dec 6 02:08:21 2002 GMT CRL entry extensions: X509v3 CRL Reason Code: Cessation Of Operation Invalidity Date: Dec 5 08:00:00 2002 GMT Serial Number: 05 Revocation Date: Dec 6 02:12:49 2002 GMT CRL entry extensions: X509v3 CRL Reason Code: Superseded Invalidity Date: Dec 5 08:00:00 2002 GMT Serial Number: 32 Revocation Date: Jan 30 23:16:39 2008 GMT CRL entry extensions: X509v3 CRL Reason Code: Cessation Of Operation Invalidity Date: Jan 30 08:00:00 2008 GMT Signature Algorithm: sha1WithRSAEncryption 72:a5:36:9e:bf:2b:0b:47:63:46:5a:09:37:2b:89:50:ec:e3: a6:fe:36:8f:76:5b:a2:c3:01:39:6d:0d:93:35:92:79:ec:81: c4:3b:62:b9:11:eb:bf:9c:36:cf:5e:dc:7d:65:d4:d7:91:a8: e3:28:ff:4c:f5:29:4c:da:21:7b:96:f4:95:ce:9c:4d:bf:e9: 7a:d8:9e:02:9b:de:6b:90:b0:23:52:2c:2f:cb:ff:d6:71:43: 74:f1:92:f8:27:a4:7a:68:01:0e:e0:bb:86:7b:72:1e:87:04: e8:ee:54:ef:8f:33:40:c5:0c:96:8c:ce:ce:90:20:00:5a:3a: 71:d9:dc:b8:25:36:2b:36:e2:a8:29:27:ab:ca:5d:50:93:11: 0a:e2:ed:9b:42:24:25:1a:37:5c:d0:a4:f2:50:64:4f:c8:fd: f5:70:ab:34:07:4d:6f:a6:2e:fa:82:16:b3:01:39:61:66:95: fe:70:15:54:29:04:76:68:60:38:83:6b:7a:5d:72:bf:5f:1a: 15:31:fe:4d:df:24:5d:e9:70:9d:90:f9:fd:0d:19:8b:b6:fb: 39:28:a5:b7:ea:a6:8b:19:37:35:79:73:a0:21:47:a4:05:73: 3c:0e:75:15:f7:65:fe:7b:56:f2:ea:54:88:5f:ee:38:43:99: a4:72:36:6e -----BEGIN X509 CRL----- MIIDvTCCAqUCAQEwDQYJKoZIhvcNAQEFBQAwdTETMBEGCgmSJomT8ixkARkWA25l dDESMBAGCgmSJomT8ixkARkWAkVTMQ4wDAYDVQQKEwVFU25ldDEgMB4GA1UECxMX Q2VydGlmaWNhdGUgQXV0aG9yaXRpZXMxGDAWBgNVBAMTD0VTbmV0IFJvb3QgQ0Eg MRcNMDkwNzE2MTg0MTEzWhcNMTAwNzE2MTg0MTEzWjCCAeowIAIBLBcNMDcwNTI1 MDA0ODE5WjAMMAoGA1UdFQQDCgEFMCACASYXDTA2MTAyNjE5MzUxNlowDDAKBgNV HRUEAwoBBDAgAgElFw0wNjEwMjYxOTM1MDBaMAwwCgYDVR0VBAMKAQQwEgIBDhcN MDMwNjExMDA0MTEyWjAgAgEjFw0wNjEwMjYxOTM0MzFaMAwwCgYDVR0VBAMKAQQw IAIBIhcNMDYxMDI2MTkzNDAyWjAMMAoGA1UdFQQDCgEEMDoCAQoXDTAzMDUwNjE4 NDM0MFowJjAKBgNVHRUEAwoBBDAYBgNVHRgEERgPMjAwMzA1MDYwNzAwMDBaMDoC AQkXDTAyMTIwNjAyMTMyMVowJjAKBgNVHRUEAwoBBDAYBgNVHRgEERgPMjAwMjEy MDUwODAwMDBaMDoCAQYXDTAyMTIwNjAyMDgyMVowJjAKBgNVHRUEAwoBBTAYBgNV HRgEERgPMjAwMjEyMDUwODAwMDBaMDoCAQUXDTAyMTIwNjAyMTI0OVowJjAKBgNV HRUEAwoBBDAYBgNVHRgEERgPMjAwMjEyMDUwODAwMDBaMDoCATIXDTA4MDEzMDIz MTYzOVowJjAKBgNVHRUEAwoBBTAYBgNVHRgEERgPMjAwODAxMzAwODAwMDBaoA4w DDAKBgNVHRQEAwIBWjANBgkqhkiG9w0BAQUFAAOCAQEAcqU2nr8rC0djRloJNyuJ UOzjpv42j3ZbosMBOW0NkzWSeeyBxDtiuRHrv5w2z17cfWXU15Go4yj/TPUpTNoh e5b0lc6cTb/petieApvea5CwI1IsL8v/1nFDdPGS+CekemgBDuC7hntyHocE6O5U 748zQMUMlozOzpAgAFo6cdncuCU2KzbiqCknq8pdUJMRCuLtm0IkJRo3XNCk8lBk T8j99XCrNAdNb6Yu+oIWswE5YWaV/nAVVCkEdmhgOINrel1yv18aFTH+Td8kXelw nZD5/Q0Zi7b7OSilt+qmixk3NXlzoCFHpAVzPA51Ffdl/ntW8upUiF/uOEOZpHI2 bg== -----END X509 CRL----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/d1b603c3.signing_policy000066400000000000000000000040001241116057200331630ustar00rootroot00000000000000# $Id: d1b603c3.signing_policy,v 1.5 2006/04/20 20:23:16 helm Exp $ # # This file is parsed from start to finish with a given CA and subject # name. # subject names may include the following wildcard characters: # * Matches any number of characters. # ? Matches any single character. # # CA names must be specified (no wildcards). Names containing whitespaces # must be included in single quotes, e.g. 'Certification Authority'. # Names must not contain new line symbols. # The value of condition attribute is represented as a set of regular # expressions. Each regular expression must be included in double quotes. # # This policy file dictates the following policy: # # The ESnet root CA signs certificates of various entities. # # Format: #------------------------------------------------------------------------ # token type | def.authority | value #--------------|---------------|----------------------------------------- # EACL entry #1| access_id_CA X509 '/DC=net/DC=ES/O=ESnet/OU=Certificate Authorities/CN=ESnet Root CA 1' pos_rights globus CA:sign cond_subjects globus '"/DC=org/DC=DOEGrids/OU=Certificate Authorities/*" "/DC=net/DC=ES/*" "/DC=org/DC=fusiongrid/OU=Certificate Authorities/*"' # # End DOE SG CA Policy # # $Log: d1b603c3.signing_policy,v $ # Revision 1.5 2006/04/20 20:23:16 helm # Added fusion grid subdir from mrt, removed misleading doc # # Revision 1.4 2006/04/20 20:17:22 helm # revision change # # Revision 1.2 2003/05/27 16:29:35 helm # Change statement of policy # # Revision 1.1 2003/05/22 22:38:22 helm # *** empty log message *** # # Revision 1.3 2003/05/03 01:31:42 dhiva # Fixed the Subject Name of the ESnet Root CA # Modified the access_id_CA and included /O=ESnet # # Revision 1.2 2003/05/03 01:18:09 dhiva # $Id: d1b603c3.signing_policy,v 1.5 2006/04/20 20:23:16 helm Exp $ included for all these files # # Revision 1.1 2003/05/03 01:15:06 dhiva # Globus Support Files for pki1.doegrids.org CA # JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/usercert.pem000066400000000000000000000016401241116057200314450ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICfzCCAegCCQDuWom2sZyUjDANBgkqhkiG9w0BAQUFADCBgzELMAkGA1UEBhMC VVMxETAPBgNVBAgTCElsbGlub2lzMRAwDgYDVQQHEwdDaGljYWdvMQ8wDQYDVQQK EwZHbG9idXMxDTALBgNVBAsTBENydXgxETAPBgNVBAMTCFRvbSBIb3dlMRwwGgYJ KoZIhvcNAQkBFg1ub25lQG5vbmUuY29tMB4XDTEwMDEyMjE4NTQ1MVoXDTExMDEy MjE4NTQ1MVowgYMxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhJbGxpbm9pczEQMA4G A1UEBxMHQ2hpY2FnbzEPMA0GA1UEChMGR2xvYnVzMQ0wCwYDVQQLEwRDcnV4MREw DwYDVQQDEwhUb20gSG93ZTEcMBoGCSqGSIb3DQEJARYNbm9uZUBub25lLmNvbTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAoNF0u12nGOyk7k5U7Aa0gws/QGxG zijW/clGt5YqUNiafn1qmSLyL300VCZRXXT9vNLu9SgTAKHrsVBlc2i4DhkNJCKk 66kXDmp8xgNKiRkMobK8TgbRL2/mccpEQvSzZvRoR3gn7cAZFvy+8ZW1FSpsxMpi +qN3PlyTYibiiS8CAwEAATANBgkqhkiG9w0BAQUFAAOBgQAvAhI1261czaCbaAO7 YAnzBDIJiYgpJtmFH2Mhu4yuLCq386Oasf31SY9BSDriVHXW4M3n2YWTTNOVAJJs bUBFKIbjS22e3Y50zf1gJ8BidLKp0/CZ9e4l9WeJxIX/owo8f5mqMriq0H6WB31M CmQz8hVPbH18b5HMkHTQrmHOqg== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/testTrustStore/userkey.pem000066400000000000000000000015671241116057200313100ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQCg0XS7XacY7KTuTlTsBrSDCz9AbEbOKNb9yUa3lipQ2Jp+fWqZ IvIvfTRUJlFddP280u71KBMAoeuxUGVzaLgOGQ0kIqTrqRcOanzGA0qJGQyhsrxO BtEvb+ZxykRC9LNm9GhHeCftwBkW/L7xlbUVKmzEymL6o3c+XJNiJuKJLwIDAQAB AoGAZ7lxDwBCrGLFpibDw1A30WXJsCWmLYZN1Hajs/mY5XgvfXIq9QaDKnoY7EWi qSKyHb32/gyQ5RGK0VzHcn6SZw+cN08BE90Xp8Sfuvl2QGwUBUM2gwcXEL1FJ/TV KriHdvyK1KsMcVdheSdDAhaCkVDVIrY1Iq8MNXiaA5bU+jECQQDOu9HfZi970sQc U9ZDjmiAbgQyljgmHowUM8n/anyDCVGtZGf1vrjckmcch+TDxj2+JVmjZAFEjKJ7 nxiFE9lzAkEAxyR5kqQQW8IDkOQs+JJphjGRxKKET5BfYVSz3mTFIz8I6Q8ImJtN TxGtDJUh9Z/3Gd/JLKQyYjraD1lB1qnSVQJBALlBRcjTYSmsrWBVIGRZcPvlmo1a X+aI6S4RWqovWnRyHWcr2p0006OU7iF7BV0KgLmr7q+kJh6vh8sPvoFCUFECQFi5 kIzcGgm3vDz+3GZ3XRqT1T1FpyuHyGcmBOmN/iNA/2hO8WaEswIKfw4/F51HAyH9 CbWhBm2riOITw3ivuu0CQQDA9U7LXS1Pv1uxw74yqpzalRzPztuAdtZc9eBgeEms 3p4qpPLaeQoX7cQP/PYQHYp5aipmaS31LKkcoeVaPgsg -----END RSA PRIVATE KEY----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/000077500000000000000000000000001241116057200266745ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/TestCA1.pem000066400000000000000000000015021241116057200306010ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICOjCCAaOgAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTA2NTRaFw0xNDA5MjgxNTA3MDRa MB8xEDAOBgNVBAYTB1Rlc3RDQTExCzAJBgNVBAMTAkNBMIGfMA0GCSqGSIb3DQEB AQUAA4GNADCBiQKBgQCfYjmxW7l/9RINzolbMIRtWNgLSOiZ4ECMTBUNwVMQv3qH ocy5sWYz8tIIq4RUfvrH+41WzjsTOck88kFz0cpPScZJInlJVyTOCY7KzR05cj8P uUKrflbzqUJJ2wcF9H3PtJo5DdhchDFsdn/AxVCldfnfq9nbj+oR2PtV6ZI+NwID AQABo4GFMIGCMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP2TTo9FYbEEhl13 7jnG7GqA/A6FMEMGA1UdIwQ8MDqAFP2TTo9FYbEEhl137jnG7GqA/A6FoR8xEDAO BgNVBAYTB1Rlc3RDQTExCzAJBgNVBAMTAkNBggEAMAsGA1UdDwQEAwIBBjANBgkq hkiG9w0BAQUFAAOBgQBzgiKGVOzrWQpn0p/Zx2pz1Mo8icujaUBV8ZCe3x2yDlTb me/t4z4cGvs+83su3xErw3o8ujc8JnPg1HTbi4E1Ye/NljwkPz2+ZASVPxX1zgxz VJgzhWkV5tuaohrYPZtRxlUUWSPjDRmBgc7iOx1Ar9qMhUKHtmbF6RyGd8Kpjw== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/ca1cert.pem000066400000000000000000000014721241116057200307250ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICNTCCAZ6gAwIBAgIBADANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0 IENBMTESMBAGA1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdDAe Fw0wNjA1MjIyMzUyMjFaFw0xMTA1MjEyMzUyMjFaMD0xETAPBgNVBAoTCHRlc3Qg Q0ExMRIwEAYDVQQLEwlzaW1wbGUgY2ExFDASBgNVBAMTC0dsb2J1cyBUZXN0MIGf MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCutM951t2bQu+euQZDn3nkMiQZ7lVn EGWxlD+8ShNooHML2R7KB7AO8NUm4x2b9xrfUTUsZIeQDq5xZIeD2rhiz/5erLN2 fEeHpX92xOhZ11MrN+3ffGGyF56kYV2BrvzI8t7w597MU1IAwL2y+tVgtwsEn/Wa 6BJ12Y85c+kJDQIDAQABo0UwQzAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSq qtDnic1O/dG/vh4mtFE4hO3C6TARBglghkgBhvhCAQEEBAMCAAcwDQYJKoZIhvcN AQEEBQADgYEATSv2I1Z8oWj/b5Wv2W4/JcjQ5EWp225UtAIiuZi7hNuC6rten27H dUHuc48wgCJfHsyrHs3OrQk5PaVd5P0wfYHA9XMqc7p7KoV0gh9vm2U/WqgPYXeS 8ZuiJRHHyj7nnSD7jHy41ZIKxbvq7HYSuyuqK0l69f3+z0M+FbOyhSI= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/ca2cert.pem000066400000000000000000000014721241116057200307260ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICNTCCAZ6gAwIBAgIBADANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0 IENBMjESMBAGA1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdDAe Fw0wNjA1MjMwMDU4MTlaFw0xMTA1MjIwMDU4MTlaMD0xETAPBgNVBAoTCHRlc3Qg Q0EyMRIwEAYDVQQLEwlzaW1wbGUgY2ExFDASBgNVBAMTC0dsb2J1cyBUZXN0MIGf MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgEZvXgOkjXUS2B85djJtwglNEBJsV 9nFrpvN2WuE8H+BFhmUaSmGkkKj4FhKL5/dthFpoB0ID+N/Bl9KGQa6mRMmK9FH6 UzLwyBi/pE4H77i+heSYF/+BfOW8rleUea6N3MP2NuvdUSDeZpoqNR7kDKVGzwfJ CkD43lwiMsY5YQIDAQABo0UwQzAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSX flnj0fDGGcnTwF04ZRDkIqzNgTARBglghkgBhvhCAQEEBAMCAAcwDQYJKoZIhvcN AQEEBQADgYEAk37O/06ZVEswEHhZij2FJ21O4eaMCGDADX6L2Ke/lRj/gBJwH+wl X9vBpcj1GFhqvsOopibqJL01z45IELCBfe6+pg1egwzz0OBwyLFsT2eoK28E+NLf YyWvY1Unxg06KNEzW+OncbxtORdHl2MfJPI3T1xEbVhDT4sqfluQr+w= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/ca2crl.r0000066400000000000000000000007171241116057200303120ustar00rootroot00000000000000-----BEGIN X509 CRL----- MIIBLDCBljANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0IENBMjESMBAG A1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdBcNMDYwNTIzMDEy NjEwWhcNMDcwNTIzMDEyNjEwWjAoMBICAQIXDTA2MDUyMzAxMTM1MFowEgIBAxcN MDYwNTIzMDExMzM1WjANBgkqhkiG9w0BAQQFAAOBgQBCGPIuGU+r1gSRqtmmxbCj EG6/YLpjb12rbW5ikD9MzuvXeQ/7N3xpTYml/kL2v+zOb4TJ9neokRqOc1k47OYf xYxGqTkH+ca5KgMhtHb5EnbI8CmrIuTJaDT8O/YmQCKchRKFxZ6s/eA6EO74GWYo cRMHFdSTx7aEQx8Z/xVF3w== -----END X509 CRL----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/crl_proxy.pem000066400000000000000000000036671241116057200314340ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIB2jCCAUOgAwIBAwIBATANBgkqhkiG9w0BAQQFADBNMQ0wCwYDVQQKEwRHcmlk MRQwEgYDVQQLEwtSYWNoYW5hVGVzdDEUMBIGA1UECxMLc2xhbmdtZS5vcmcxEDAO BgNVBAMTB1JhY2hhbmEwHhcNMDMwODA4MTUyNjM1WhcNMDQwODA1MjEzNTIwWjBd MQ0wCwYDVQQKEwRHcmlkMRQwEgYDVQQLEwtSYWNoYW5hVGVzdDEUMBIGA1UECxML c2xhbmdtZS5vcmcxEDAOBgNVBAMTB1JhY2hhbmExDjAMBgNVBAMTBXByb3h5MFww DQYJKoZIhvcNAQEBBQADSwAwSAJBAOXVHCSqMvnE+lIEn+4aEwskm7nkjSXA31Hp /zURurAqsBHj4H0Y8tgTNMOPIZx6wyQ/oHBC1VUYE9DbuYmB2WMCAwEAATANBgkq hkiG9w0BAQQFAAOBgQCSA25hNugA8FMr7dXCZeZ9V6qqXpmCbwQlR+NYFCaWA+FX z9371Zz+ncRo0U5/Aj4V+mAdEGMJp8jPkZYpr9hztsRTZgY0qTN+XON0YDiDlrIE V3b0L+KW55DwWFonmiIbhCkcFoxRBo/V41QCBZx0F/4SDPqq/TNxp8nwAKjeqQ== -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAOXVHCSqMvnE+lIEn+4aEwskm7nkjSXA31Hp/zURurAqsBHj4H0Y 8tgTNMOPIZx6wyQ/oHBC1VUYE9DbuYmB2WMCAwEAAQJALJHALGgJDKCjPmaBMSZD TSTjQhBNQuX9KKBtCjiO8HxopUO+VD9NtxcXST62j+llO9/5UlL13ahlouT+eqKg kQIhAPUdk/p5mn/3Po8c9q2LUooqo5FYMnLkUXCdsV9/OqyJAiEA8AnMDJu0Ehoz 0O6G5HQZ9U7+EmQ4Q6Y15xObxUUYE4sCIQDLYiaGH96lrZZ4E1VPfJoZUPX1xNPf Zzl4EzC5B4282QIhAMtSARzM5oJO34UiBfCMx1AaUOuTKHVk3FOXMGKwW+xxAiBb Kms5kpJeQClUtJKtTis+k0QwtLP1SLGrzMkfP2uS1Q== -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIICDjCCAXegAwIBAgIBATANBgkqhkiG9w0BAQQFADA2MQ0wCwYDVQQKEwRHcmlk MRQwEgYDVQQLEwtSYWNoYW5hVGVzdDEPMA0GA1UEAxMGVGVzdENBMB4XDTAzMDgw NjIxMzUyMFoXDTA0MDgwNTIxMzUyMFowTTENMAsGA1UEChMER3JpZDEUMBIGA1UE CxMLUmFjaGFuYVRlc3QxFDASBgNVBAsTC3NsYW5nbWUub3JnMRAwDgYDVQQDEwdS YWNoYW5hMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7v3WmZSzGcB7Aq+le QSN6lLB3Ezc7woqlekmz/5NhnwgWm4xtNjein5nUNL3xfwIU3YVdZbZxxSgSsY/E wyG72zwVBzuyYgsg1Iam/CFhMZAfDf19n1Dw69cWmO8luMY7KvcYwEgRkrJGAkKP EJVwk4L2wwjt6+az0Pxd6Q224wIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAw DQYJKoZIhvcNAQEEBQADgYEApFkbx2pm3IkJJBEc63Lae0hVbQxcof5Yj8rHAzFI l402JXLr2rtiGpX5vv7VkAkKCDSdTSyTN93Sb9xedl2a83wIj8OMi0y1ofgVkDPj 9zwWDyJluYMkBOcoE/EkcTsJvh/Tau1/rCxmiEMsD2eYtUOcGbTNVGmhOs+59vhC mCk= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/crl_usercert.pem000066400000000000000000000047451241116057200321050ustar00rootroot00000000000000Certificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: md5WithRSAEncryption Issuer: O=Grid, OU=RachanaTest, CN=TestCA Validity Not Before: Aug 6 21:35:20 2003 GMT Not After : Aug 5 21:35:20 2004 GMT Subject: O=Grid, OU=RachanaTest, OU=slangme.org, CN=Rachana Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:bb:bf:75:a6:65:2c:c6:70:1e:c0:ab:e9:5e:41: 23:7a:94:b0:77:13:37:3b:c2:8a:a5:7a:49:b3:ff: 93:61:9f:08:16:9b:8c:6d:36:37:a2:9f:99:d4:34: bd:f1:7f:02:14:dd:85:5d:65:b6:71:c5:28:12:b1: 8f:c4:c3:21:bb:db:3c:15:07:3b:b2:62:0b:20:d4: 86:a6:fc:21:61:31:90:1f:0d:fd:7d:9f:50:f0:eb: d7:16:98:ef:25:b8:c6:3b:2a:f7:18:c0:48:11:92: b2:46:02:42:8f:10:95:70:93:82:f6:c3:08:ed:eb: e6:b3:d0:fc:5d:e9:0d:b6:e3 Exponent: 65537 (0x10001) X509v3 extensions: Netscape Cert Type: SSL Client, SSL Server, S/MIME, Object Signing Signature Algorithm: md5WithRSAEncryption a4:59:1b:c7:6a:66:dc:89:09:24:11:1c:eb:72:da:7b:48:55: 6d:0c:5c:a1:fe:58:8f:ca:c7:03:31:48:97:8d:36:25:72:eb: da:bb:62:1a:95:f9:be:fe:d5:90:09:0a:08:34:9d:4d:2c:93: 37:dd:d2:6f:dc:5e:76:5d:9a:f3:7c:08:8f:c3:8c:8b:4c:b5: a1:f8:15:90:33:e3:f7:3c:16:0f:22:65:b9:83:24:04:e7:28: 13:f1:24:71:3b:09:be:1f:d3:6a:ed:7f:ac:2c:66:88:43:2c: 0f:67:98:b5:43:9c:19:b4:cd:54:69:a1:3a:cf:b9:f6:f8:42: 98:29 -----BEGIN CERTIFICATE----- MIICDjCCAXegAwIBAgIBATANBgkqhkiG9w0BAQQFADA2MQ0wCwYDVQQKEwRHcmlk MRQwEgYDVQQLEwtSYWNoYW5hVGVzdDEPMA0GA1UEAxMGVGVzdENBMB4XDTAzMDgw NjIxMzUyMFoXDTA0MDgwNTIxMzUyMFowTTENMAsGA1UEChMER3JpZDEUMBIGA1UE CxMLUmFjaGFuYVRlc3QxFDASBgNVBAsTC3NsYW5nbWUub3JnMRAwDgYDVQQDEwdS YWNoYW5hMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7v3WmZSzGcB7Aq+le QSN6lLB3Ezc7woqlekmz/5NhnwgWm4xtNjein5nUNL3xfwIU3YVdZbZxxSgSsY/E wyG72zwVBzuyYgsg1Iam/CFhMZAfDf19n1Dw69cWmO8luMY7KvcYwEgRkrJGAkKP EJVwk4L2wwjt6+az0Pxd6Q224wIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAw DQYJKoZIhvcNAQEEBQADgYEApFkbx2pm3IkJJBEc63Lae0hVbQxcof5Yj8rHAzFI l402JXLr2rtiGpX5vv7VkAkKCDSdTSyTN93Sb9xedl2a83wIj8OMi0y1ofgVkDPj 9zwWDyJluYMkBOcoE/EkcTsJvh/Tau1/rCxmiEMsD2eYtUOcGbTNVGmhOs+59vhC mCk= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/eecFromTestCA1.pem000066400000000000000000000012701241116057200321040ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi2fullproxy.pem000066400000000000000000000033541241116057200322350ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBgTCB66ADAgECAgEAMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rlc3RD QTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA0WhcNMDkwOTI5MDMzMTA0 WjAxMRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMQ4wDAYDVQQDEwVw cm94eTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCpchzgrrMGN9Ej1uydasWb5vMx iZjzjB2pCkurUjjAQTRAa+wAzGRG3abWhquRctYajsU+xgpTP57063/WXGqZAgMB AAEwDQYJKoZIhvcNAQEFBQADgYEApBBqe+ZEaGi/VPwnqW4VmTzIcC9LTLwaaA17 9OqHMadTCJ9gTlZ0BtaaMOC0tKmd3J6xqvSzmG0/yNx4Zpr7QiKmZKeFqjhay6iW d0T2ZQvtrX3ODyclQ3kczy3tirh1GytmPKgCOa5t9bwRtBu4F15ZVnE2DdCBHR56 IoNx3+M= -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAKlyHOCuswY30SPW7J1qxZvm8zGJmPOMHakKS6tSOMBBNEBr7ADM ZEbdptaGq5Fy1hqOxT7GClM/nvTrf9ZcapkCAwEAAQJBAKQv1XmE7iWVSkqvBCFY h1gUhgu3J4S+fTMBrea4yhLGx8mvvVDZ8Dy1VP+2srC9rq9V5WXyH2f0CRXFBVIG qd0CIQDXtm472vaALhPDxrm5yYGrMCD8iMk+spcOoOYR7Wv2AwIhAMkXlqTUXJ70 C4WWcHf9TpZfyCad4+ij/I1F9J9Zg3gzAiBvzRa/IRKnhropuyLhnwX84toF6SNc wpU2OMBlxEczXwIgOCE6blXMaJ3sHWSpjgSJjBW+M3E87XHgi7psFpKQzNsCIC0Q ppxx+M2+gL/EnZsOwGXnP1GDCuAEkzGAj4HEMeg7 -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi2limited2xproxy.pem000066400000000000000000000044661241116057200332010ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBeTCCASOgAwIBAgIBADANBgkqhkiG9w0BAQUFADA5MRAwDgYDVQQGEwdUZXN0 Q0ExMQ0wCwYDVQQDEwRFRUMxMRYwFAYDVQQDEw1saW1pdGVkIHByb3h5MB4XDTA5 MDkyODE1MjYwNloXDTA5MDkyOTAzMzEwNlowUTEQMA4GA1UEBhMHVGVzdENBMTEN MAsGA1UEAxMERUVDMTEWMBQGA1UEAxMNbGltaXRlZCBwcm94eTEWMBQGA1UEAxMN bGltaXRlZCBwcm94eTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCKYc0JAynwHP7W tLa3jHgwwFjoolfKnu6PXbyR+x5V/gKPF5H+lgwnFsxxbL6kqPef77eHbqEufhvf r0F/CLoZAgMBAAEwDQYJKoZIhvcNAQEFBQADQQBLtlXM6Gqc6fN3nMWghGv+dzdE 5iU6Ev0p5R1ev6TLWBZWavLmTmArrWiTJqvj1mjuEbY3fU+IOSEDKd0lK8KM -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAIphzQkDKfAc/ta0treMeDDAWOiiV8qe7o9dvJH7HlX+Ao8Xkf6W DCcWzHFsvqSo95/vt4duoS5+G9+vQX8IuhkCAwEAAQJAA08JVwDTXOFkmn+hqsva B9hhh9Zx4O9h5t2n55mohQfPxuww2tRSEwMQ3XBhJJzB4p0GAMYoABPLMFLZ2NT7 XQIhAMWdx5jry9sSx3JIXx2e9spA+jowp30G6JrYp5RBG8dLAiEAs0P7jBpGsexs x19AgVR01RdBMT3rcjUDklNRKkV38asCIQC/ZtaP8rJ7+XBb7GTT18fIla7G9aED o9FfSUDmgzlYiQIgCkQFXrOOgtfgLtakkgNtIVrQj+pU1lh02OdOiZYq1TsCIQCq dbJUtCistCoJfZxu1E3Vt4O4r0DLE7OHLzwNNtsaLg== -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBiTCB86ADAgECAgEAMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rlc3RD QTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA1WhcNMDkwOTI5MDMzMTA1 WjA5MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRYwFAYDVQQDEw1s aW1pdGVkIHByb3h5MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ4C1cRTxFyRiJQF cTmnHbMLlUNH9ncCd+mezA0nd4Ilm0e+GsEdjsC5WkFsMhD12ERfce249ly4Iunx G1sSaVkCAwEAATANBgkqhkiG9w0BAQUFAAOBgQB9Utle+V6RebBFVNcJAxmiqsUt Y1NKu6w9xbYKUsJL9MFjQs1V+fdcSodWJ3z78yIoH/VcI0LveMAet3ykw8VHF4Fh J/n2GzrjPdMVXXuA/kculRFlQBrS3o2yyY0uBq3xz10VBpH6m+bl4tHG5N/R0klt jPcRKx6nq0HMo/yA5w== -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi2limitedproxy.pem000066400000000000000000000033741241116057200327240ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBiTCB86ADAgECAgEAMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rlc3RD QTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA1WhcNMDkwOTI5MDMzMTA1 WjA5MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRYwFAYDVQQDEw1s aW1pdGVkIHByb3h5MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ4C1cRTxFyRiJQF cTmnHbMLlUNH9ncCd+mezA0nd4Ilm0e+GsEdjsC5WkFsMhD12ERfce249ly4Iunx G1sSaVkCAwEAATANBgkqhkiG9w0BAQUFAAOBgQB9Utle+V6RebBFVNcJAxmiqsUt Y1NKu6w9xbYKUsJL9MFjQs1V+fdcSodWJ3z78yIoH/VcI0LveMAet3ykw8VHF4Fh J/n2GzrjPdMVXXuA/kculRFlQBrS3o2yyY0uBq3xz10VBpH6m+bl4tHG5N/R0klt jPcRKx6nq0HMo/yA5w== -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAJ4C1cRTxFyRiJQFcTmnHbMLlUNH9ncCd+mezA0nd4Ilm0e+GsEd jsC5WkFsMhD12ERfce249ly4IunxG1sSaVkCAwEAAQJAFul0U86Nt5qGwmfznheE b/TrBOGHdIRQHPkgv3uMkbtlmUBHH+FlIchsSi50IqXRwPUSIreKohC3sLOooBaw 8QIhAN/9Lo15RT/Py+JsF/PHSpq2mEl7kbmnCNW0bOO57crFAiEAtJfMPCnZFtmA tsXtTSfBDNPS37d5xLUp2mJjIKhM3YUCIQCRG3uCKZNEQMFMAU0PIAfj7PEBge0p Qd4GXGnCqhw0JQIgZ5t7Gb0shfZs6O8u0IgRMmnIXn8lxhvlkhvGITNNPf0CIQCs DZ8PcvdCECCJXkkYu+TSPWSpiUOftNcnilt7gGaQbA== -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi2proxyFromgsi3.pem000066400000000000000000000045471241116057200327710ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBbTCCARegAwIBAgIDAWVLMA0GCSqGSIb3DQEBBQUAMDYxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExEzARBgNVBAMTCjExMzcxODQ0MjAwHhcNMDkx MDAyMTYzMzI1WhcNMDkxMDAzMDQzODI1WjBGMRAwDgYDVQQGEwdUZXN0Q0ExMQ0w CwYDVQQDEwRFRUMxMRMwEQYDVQQDEwoxMTM3MTg0NDIwMQ4wDAYDVQQDEwVwcm94 eTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCZhViFa6bBR6wNbGOO1y1m2Eg0Kzqs FNip0iWW3YyJijpZ5M/LaT9cMr+KSPQu1lZwBBErnfnTqZ28IrM99inPAgMBAAEw DQYJKoZIhvcNAQEFBQADQQAP3f0i2na/6Ht6N7zSqYvUE4CZB7G2P4zZxe9rPISq e2X5SKaW51P6I7E2AoSnl+6WtFHW98ta6qygsKfKglLW -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOQIBAAJBAJmFWIVrpsFHrA1sY47XLWbYSDQrOqwU2KnSJZbdjImKOlnkz8tp P1wyv4pI9C7WVnAEESud+dOpnbwisz32Kc8CAwEAAQJAW2n7e/bOJOj4mkWgQr3+ Wu8Oj4HuPelr2jM4Ds19kae/aGraZ/WD5O8BpWhXQHrqk0kX6mV7UYml1W3Vlarq gQIhAOGDZO8tEz3JmYr5oAKSi6RGnfQQEA+3cYFu8K9Up7Y7AiEArkZs90WKGBIb aziIN8WG+dyl9iTpt8mv7X62gkLwnX0CIQCTqDPLgykJGNpHK+FALfHu8ynzJx1N HSDdzeUb+AMEBwIfSCjg9YHVrCHTOJIv1Of0+4BhN4oRPAhG0A+ngkg1WQIgR6Sm ts5DsqiQ2cVI9t5d+iVp3qrArBlnleI1/Ug8kGU= -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBvjCCASegAwIBAgIDAWVLMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA3WhcNMDkwOTI5MDMz MTA3WjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxMTM3MTg0NDIwMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAI8F83TDsYOcnsxa kx4t6EPW3tOPN+7AEmAtj+ubzsE9MuBOdpKyK9axz6JrzMzM304b99Emsw3+gytX 8P9O+dcCAwEAAaMzMDEwHwYKKwYBBAGbUAGBXgEB/wQOMAwwCgYIKwYBBQUHFQEw DgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA4GBABmB5pJM9ooyJC9vC5tc pNRXym2C2e7kznVbYklFJ07/+U0fWgtUR2vImvcjKRdTXYx8il0pNqbg7jLO7T8+ vBYYwR/q2NB6+50CrUMNwuVetVa3DSNPjO22HgSMit7J+BtREPIz9Lo5ybja8hFF UGLrtU7ZIygwxgGKES3lTv9J -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3FromPathOneIssuedProxy.pem000066400000000000000000000061641241116057200345160ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIB0TCCAXugAwIBAgIDCEwsMA0GCSqGSIb3DQEBBQUAMEsxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExEzARBgNVBAMTCjE2NjcwNTg2NzcxEzARBgNV BAMTCjE2MDA4MzMzNDUwHhcNMDkwOTI5MTYxMjE1WhcNMDkwOTMwMDQxNzE1WjBg MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQDEwoxNjY3 MDU4Njc3MRMwEQYDVQQDEwoxNjAwODMzMzQ1MRMwEQYDVQQDEwoxMDg3MjEyNDg4 MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIHmTyoVRJCkKAUAK/1PhTBe1vyhKczM tv1VlWA6Bc9fC7pdCv3kWiVkCYMJ8LEbeI4EMrzAF5rSA21MAY3yjDECAwEAAaMz MDEwHwYKKwYBBAGbUAGBXgEB/wQOMAwwCgYIKwYBBQUHFQEwDgYDVR0PAQH/BAQD AgWgMA0GCSqGSIb3DQEBBQUAA0EAlvWKkWl78Oh6lxCfg3pI6dNgRH3l5mBtzsf0 fAraUiPj+VRnpMHMgablu2J8WsHYhe35+QPlxORxRXdNj/0gsw== -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAIHmTyoVRJCkKAUAK/1PhTBe1vyhKczMtv1VlWA6Bc9fC7pdCv3k WiVkCYMJ8LEbeI4EMrzAF5rSA21MAY3yjDECAwEAAQJAeznZu1g1lOjEtgm1sTUw afRuCXVxS8Cfjq8TZxdjz5U6+fkm9VhppcbmQfkpniUZbHfKzKMTKUeJz3B1kZWR YQIhAOvG+7bYvycxrhmKOSSIF9aoUci3k31gIVyyfanF5dutAiEAjQqLy5UPVGl3 tb5UYKP94KliK60DjsF6MZvfWFMmgxUCIQDG5BAqaiS1916aBNO3UWZqmYqD+vfb 51+9RoRi1qHT8QIgcxUu2i/HcWYZYrdpm+1Tw1QSoXar13jxXrdD94rper0CIQDU QueoH/fQjpllhw4BHXFZHTrjSZhTakXvI3jExgT9aw== -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBpzCCAVGgAwIBAgIDBnu+MA0GCSqGSIb3DQEBBQUAMDYxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExEzARBgNVBAMTCjE2NjcwNTg2NzcwHhcNMDkw OTI5MTYwNzMzWhcNMDkwOTMwMDQxMjMzWjBLMRAwDgYDVQQGEwdUZXN0Q0ExMQ0w CwYDVQQDEwRFRUMxMRMwEQYDVQQDEwoxNjY3MDU4Njc3MRMwEQYDVQQDEwoxNjAw ODMzMzQ1MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJzlafv8Xgj4TnooT61omTT6 aZejyW0i3WyeETus+DXj/6zz4DHn59nwdry29Gn2YKTwDUntYm1gs49WCsXsWNUC AwEAAaMzMDEwHwYKKwYBBAGbUAGBXgEB/wQOMAwwCgYIKwYBBQUHFQEwDgYDVR0P AQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA0EAkKLEjeAjWGDd4ZX1MAAInZhESyBV VtOYE1yH5KN/uuAwLR4DKoN4iS9zmQQkVUCWWBc2TdfUwsgBsM1iQFFV8w== -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIBwTCCASqgAwIBAgIDBocAMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjExWhcNMDkwOTI5MDMz MTExWjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxNjY3MDU4Njc3MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKATtVc0sisAK2nX iB9wyR9+9wDNkikZ+0xPay4I0gN4S/w+r1VxaTitivtfzuijY4q0IFiBlXkZGSVv bVxEfc0CAwEAAaM2MDQwIgYKKwYBBAGbUAGBXgEB/wQRMA8CAQEwCgYIKwYBBQUH FQIwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA4GBACbi2ZGUq4Wmik2Q 3vqqePVRscZCinjXxax/w12nGWo0taRNGc2z+d1+GOZwv9zupKKRh7bM72rzbj6h WcFTQ7Vg0v1/4u8LFcI+HmHxtLRjRSHfzowfDqL5qjMpnALxpNQuZYW5Vog8DoDC xfVYT4ghKddp4aDRdSMfCb2t9fgo -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi3FromPathOneProxy.pem000066400000000000000000000046741241116057200334240ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBpzCCAVGgAwIBAgIDBnu+MA0GCSqGSIb3DQEBBQUAMDYxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExEzARBgNVBAMTCjE2NjcwNTg2NzcwHhcNMDkw OTI5MTYwNzMzWhcNMDkwOTMwMDQxMjMzWjBLMRAwDgYDVQQGEwdUZXN0Q0ExMQ0w CwYDVQQDEwRFRUMxMRMwEQYDVQQDEwoxNjY3MDU4Njc3MRMwEQYDVQQDEwoxNjAw ODMzMzQ1MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJzlafv8Xgj4TnooT61omTT6 aZejyW0i3WyeETus+DXj/6zz4DHn59nwdry29Gn2YKTwDUntYm1gs49WCsXsWNUC AwEAAaMzMDEwHwYKKwYBBAGbUAGBXgEB/wQOMAwwCgYIKwYBBQUHFQEwDgYDVR0P AQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA0EAkKLEjeAjWGDd4ZX1MAAInZhESyBV VtOYE1yH5KN/uuAwLR4DKoN4iS9zmQQkVUCWWBc2TdfUwsgBsM1iQFFV8w== -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAJzlafv8Xgj4TnooT61omTT6aZejyW0i3WyeETus+DXj/6zz4DHn 59nwdry29Gn2YKTwDUntYm1gs49WCsXsWNUCAwEAAQJAGT9JiMUZlLPwXPPzrmHw lXfeWgp/NVKw8vOUrletMW6XIkgS7II5S4/C0uXolKQ32fr8u6L0bEyeADDvftEp mQIhAPb5PBrXDF5rSNnoXHCRpmsHtEc1ygpRHWWgmL3xIrY/AiEAoqFirvWnNJ86 E4QuWQ9MmPo7waVCXZ1Ue8q94+wfs+sCIQCua15zZiSqGgKdQmjmZzasqAg9slM5 7gdg2oaEvmPRaQIgIZHepO7gTORxQIYQayHVVd6RZy+Nu3U2czcua1XaVXECIGWe 5eoKvjmXecwPAxBPJP6sVpmRxZm71AXpt0r4zvJC -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBwTCCASqgAwIBAgIDBocAMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjExWhcNMDkwOTI5MDMz MTExWjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxNjY3MDU4Njc3MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKATtVc0sisAK2nX iB9wyR9+9wDNkikZ+0xPay4I0gN4S/w+r1VxaTitivtfzuijY4q0IFiBlXkZGSVv bVxEfc0CAwEAAaM2MDQwIgYKKwYBBAGbUAGBXgEB/wQRMA8CAQEwCgYIKwYBBQUH FQIwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA4GBACbi2ZGUq4Wmik2Q 3vqqePVRscZCinjXxax/w12nGWo0taRNGc2z+d1+GOZwv9zupKKRh7bM72rzbj6h WcFTQ7Vg0v1/4u8LFcI+HmHxtLRjRSHfzowfDqL5qjMpnALxpNQuZYW5Vog8DoDC xfVYT4ghKddp4aDRdSMfCb2t9fgo -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi3FromPathZeroProxy.pem000066400000000000000000000046741241116057200336220ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBpjCCAVCgAwIBAgIDCbl4MA0GCSqGSIb3DQEBBQUAMDYxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExEzARBgNVBAMTCjEzNTI3MTIzNTMwHhcNMDkw OTI5MTYwMjI4WhcNMDkwOTMwMDQwNzI4WjBKMRAwDgYDVQQGEwdUZXN0Q0ExMQ0w CwYDVQQDEwRFRUMxMRMwEQYDVQQDEwoxMzUyNzEyMzUzMRIwEAYDVQQDEwk1NTEz MTQ1MTIwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAoqzObYUD3eMe/WN9vctVb0OT CpGOwuxTIBqqAajXXqbjfL9NHUX4cSgukCyMTTVSgcUpFOLj8bKlfnQxhSK8wQID AQABozMwMTAfBgorBgEEAZtQAYFeAQH/BA4wDDAKBggrBgEFBQcVATAOBgNVHQ8B Af8EBAMCBaAwDQYJKoZIhvcNAQEFBQADQQAXWkfzzh8J2sZxMQqnKIBjSWJbusIq kWYfnS1rXTTGAig5LBmBibPxJsSfIofP3PfDaDPYsIDgdibpNUngcHo1 -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAKKszm2FA93jHv1jfb3LVW9DkwqRjsLsUyAaqgGo116m43y/TR1F +HEoLpAsjE01UoHFKRTi4/GypX50MYUivMECAwEAAQJBAIiOE0LwU8yhaVQ/fkAi PfeGfBp1EagjBax/dZKrDw+OJLaiwpnSJirHLhP2SXqH7TakJ2z9lzJDrldsXj+R ApkCIQDeDdR+EgDVMm/iohGiG8zEYfT8KazhhNQDdb0vDA9c7wIhALuLKAEHGN/9 hSIxhXX1Ia0mdgyB6PVQEhGBO88NueFPAiEAslspcpnDUXtRoxfKUgtCTfrgbCqN Uhb+tEi9zCxDqsECIDOqBB00XU/nQTPIPKHgI6TVgZO0ff6GTlPwLA/AEkLVAiA6 U0fC3xUthMyPybPVpiFeUSrFhbgyKZzGLjaPeuCeNQ== -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBwTCCASqgAwIBAgIDA77LMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjExWhcNMDkwOTI5MDMz MTExWjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxMzUyNzEyMzUzMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIgP1X3fVXSlJLvm uIiN4wRtqVLTS7MUr1SjYNfoth+vwaDLvNtxppHK2hu0vQzN8qZbAp0aWYsNZ1yf kZBtooECAwEAAaM2MDQwIgYKKwYBBAGbUAGBXgEB/wQRMA8CAQAwCgYIKwYBBQUH FQEwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA4GBAC1ipJTUEj/ZBGbA rLiE6DjC2jiTf2eq2tK+lzozC36K3TF9N3l1pTni1skhVKK0Zkof3bGT3cYSESsd GccPbajUDZG1g2LadFy0ckeUda37r5rFYJvUtBQgVkyQccjF9DmMz0auA9stUDlB 9LOKv3TN/kUpqB1Hsi4MJwig+p5h -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3impersonation2xproxy.pem000066400000000000000000000046701241116057200343600ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIBpjCCAVCgAwIBAgIDDthyMA0GCSqGSIb3DQEBBQUAMDYxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExEzARBgNVBAMTCjExMzcxODQ0MjAwHhcNMDkw OTI4MTUyNjA5WhcNMDkwOTI5MDMzMTA5WjBKMRAwDgYDVQQGEwdUZXN0Q0ExMQ0w CwYDVQQDEwRFRUMxMRMwEQYDVQQDEwoxMTM3MTg0NDIwMRIwEAYDVQQDEwk3MzMz NzE2NTcwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAr6GcRV57NlSECPZhn+khUjSz IsSs73o17wFG85c5BurUfDS1sDaqjUzn2BF0pKcd14hUuOSrszIjpRjYict6awID AQABozMwMTAfBgorBgEEAZtQAYFeAQH/BA4wDDAKBggrBgEFBQcVATAOBgNVHQ8B Af8EBAMCBaAwDQYJKoZIhvcNAQEFBQADQQAaLlWjWt/NLpjurP7rzagmQ6gI+VIs FFRCQ0Rbj9EYt11BZp0WqBP+ms5z9Fpyp5mp60BC3LURXOF5VvNx0ReF -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAK+hnEVeezZUhAj2YZ/pIVI0syLErO96Ne8BRvOXOQbq1Hw0tbA2 qo1M59gRdKSnHdeIVLjkq7MyI6UY2InLemsCAwEAAQJAf1Whch3VIQfXjpPrJcAl e29f7TZA14N4dOctJNCf9OW63Df7mdqHTSYBIOwjJgKOknBvkPhGLvx9Lp56xOGD kQIhAOCZh925I4wAbXAxAOGc2387b/gaU03rc3378tuZbklZAiEAyC99TurRGiUT ajBe5WBZs+haiM1mMtwffy5BUA89ZWMCIQCIp4GOO25QaZYss/QoUasPj9eBqmrT NxYPKnPKf2EmCQIhAJSSqm3n2UmOOtqVC9kxqWHdEVR3HWKh/L5nlhHVPbwBAiAR qAjrc/gcAI6oYHMGMwngWUT1I9rZT6GRoNMcLHFXwA== -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBvjCCASegAwIBAgIDAWVLMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA3WhcNMDkwOTI5MDMz MTA3WjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxMTM3MTg0NDIwMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAI8F83TDsYOcnsxa kx4t6EPW3tOPN+7AEmAtj+ubzsE9MuBOdpKyK9axz6JrzMzM304b99Emsw3+gytX 8P9O+dcCAwEAAaMzMDEwHwYKKwYBBAGbUAGBXgEB/wQOMAwwCgYIKwYBBQUHFQEw DgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA4GBABmB5pJM9ooyJC9vC5tc pNRXym2C2e7kznVbYklFJ07/+U0fWgtUR2vImvcjKRdTXYx8il0pNqbg7jLO7T8+ vBYYwR/q2NB6+50CrUMNwuVetVa3DSNPjO22HgSMit7J+BtREPIz9Lo5ybja8hFF UGLrtU7ZIygwxgGKES3lTv9J -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3impersonationFromIndependentProxy.pem000066400000000000000000000046601241116057200370470ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIBozCCAU2gAwIBAgIDDnCBMA0GCSqGSIb3DQEBBQUAMDQxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExETAPBgNVBAMTCDU5MzgyODUxMB4XDTA5MDky ODE2NTEwNVoXDTA5MDkyOTA0NTYwNVowSTEQMA4GA1UEBhMHVGVzdENBMTENMAsG A1UEAxMERUVDMTERMA8GA1UEAxMINTkzODI4NTExEzARBgNVBAMTCjExNTQ0ODg0 MTMwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAjftaHojSDEbMI1igkqUVD2zTnsuX Yk6s39yaxvN0owkM22gNy4KPfnM9NyouVfclvDiapcoEfkSX3lpllabjBwIDAQAB ozMwMTAfBgorBgEEAZtQAYFeAQH/BA4wDDAKBggrBgEFBQcVATAOBgNVHQ8BAf8E BAMCBaAwDQYJKoZIhvcNAQEFBQADQQAFWdius72IjJfBcSr8Mqvpjl+ByUWKdGXV 6GPVYSf9lv+LceItTSAX03STjg8/n/KqY2W406U129EZTFFoQ2pQ -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOQIBAAJBAI37Wh6I0gxGzCNYoJKlFQ9s057Ll2JOrN/cmsbzdKMJDNtoDcuC j35zPTcqLlX3Jbw4mqXKBH5El95aZZWm4wcCAwEAAQJAYQfJytxOUD2B/RXwhsdy 4RvKc9dHGdQSqNqmnBh9OX1IAiA491+fiGF+D8my0saMdgDnGU4KFdbBxYSS4IFN AQIhAOkZMqrSaIT+tZiNmiqPFSTeDB9p1V0Gus8iEBDxksFnAiEAm+5svmfTPV6m 24EHAM1MsBDgbo4qXQw2lkB47Hg/rWECIBoaW0Ur2M6D43wY51m6uihtwTfHV0Ba n5LQgrITC1cjAiAPur5nequ5bhng3KQrNYp93EX3gQnO9xNulrRcDklGIQIgBmWs M8jz+w+4m3y9e4385cyAkMWZElbFYl4edA/v7Y0= -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBvDCCASWgAwIBAgIDBTRXMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA4WhcNMDkwOTI5MDMz MTA4WjA0MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMREwDwYDVQQD Ewg1OTM4Mjg1MTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCV3aY4Zf7aTZiM+9OY /Z+IMFLqoou6e7RUuBiPXvSq0VXuzSIC+4kMhZRzbCRFEsO+sY1lAobdMeMo/S1M 6YhFAgMBAAGjMzAxMB8GCisGAQQBm1ABgV4BAf8EDjAMMAoGCCsGAQUFBxUCMA4G A1UdDwEB/wQEAwIFoDANBgkqhkiG9w0BAQUFAAOBgQAArXgjm6WPzbHSYky7Faev JRrdXJc5P6yMaob0S2FCg/I4mQ2E6O0pT1J0kzzMEsQ/d7kgregHmdnOJmEk1oqW ukVOidEOso5dQc3ukpcbAFE93FwrCNL5cjdjYcVf3a+1Fn+fFOdApFuzZavfsBnq rbf7e6HE50mgYZ1XisiJQg== -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3impersonationp0proxy.pem000066400000000000000000000035051241116057200343420ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIBwTCCASqgAwIBAgIDA77LMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjExWhcNMDkwOTI5MDMz MTExWjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxMzUyNzEyMzUzMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIgP1X3fVXSlJLvm uIiN4wRtqVLTS7MUr1SjYNfoth+vwaDLvNtxppHK2hu0vQzN8qZbAp0aWYsNZ1yf kZBtooECAwEAAaM2MDQwIgYKKwYBBAGbUAGBXgEB/wQRMA8CAQAwCgYIKwYBBQUH FQEwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA4GBAC1ipJTUEj/ZBGbA rLiE6DjC2jiTf2eq2tK+lzozC36K3TF9N3l1pTni1skhVKK0Zkof3bGT3cYSESsd GccPbajUDZG1g2LadFy0ckeUda37r5rFYJvUtBQgVkyQccjF9DmMz0auA9stUDlB 9LOKv3TN/kUpqB1Hsi4MJwig+p5h -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAIgP1X3fVXSlJLvmuIiN4wRtqVLTS7MUr1SjYNfoth+vwaDLvNtx ppHK2hu0vQzN8qZbAp0aWYsNZ1yfkZBtooECAwEAAQJBAIcEf2y7FMf9oOg9Wd1Y P3EDiUVBnBsHab1pqw5WRXRGtgTISzijs3ZuJ/yTqn7NSK+lvX/cx5PDdueLeet4 qkkCIQDQhKHrsOvHS34X8iDFhKD6EJHjpUZWiompYRoS57Z3OwIhAKcLbrI67R2g b+SkdUZGHacO/FxMfcBpZFvF7gYrfwlzAiBeVKIrzc3cSvqwOok40ddBSV22bn5z iBje117ETq7tIQIgKrDcSIaQxOqUzh1Nr3kJ6QEGc9xEoyEMOfwauc7x94sCIQCN /PKRj2BEfG9A8ey6L9xMkp8LZpFhmYBLJpriVokCFA== -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3impersonationproxy.pem000066400000000000000000000034751241116057200341100ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIBvjCCASegAwIBAgIDAWVLMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA3WhcNMDkwOTI5MDMz MTA3WjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxMTM3MTg0NDIwMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAI8F83TDsYOcnsxa kx4t6EPW3tOPN+7AEmAtj+ubzsE9MuBOdpKyK9axz6JrzMzM304b99Emsw3+gytX 8P9O+dcCAwEAAaMzMDEwHwYKKwYBBAGbUAGBXgEB/wQOMAwwCgYIKwYBBQUHFQEw DgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA4GBABmB5pJM9ooyJC9vC5tc pNRXym2C2e7kznVbYklFJ07/+U0fWgtUR2vImvcjKRdTXYx8il0pNqbg7jLO7T8+ vBYYwR/q2NB6+50CrUMNwuVetVa3DSNPjO22HgSMit7J+BtREPIz9Lo5ybja8hFF UGLrtU7ZIygwxgGKES3lTv9J -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAI8F83TDsYOcnsxakx4t6EPW3tOPN+7AEmAtj+ubzsE9MuBOdpKy K9axz6JrzMzM304b99Emsw3+gytX8P9O+dcCAwEAAQJAXeLNLzArPjc48vLeMmh2 WNobSgtw7xQ8u9AM8uBDuAtC28kNZwv5RZUtO7Nyzy/c5AtevhZ+5vSFXDqVH2iu CQIhAOFgoKMpDlOTzZPRfShDX+TLqEAc5ibycunUnXgT2VtrAiEAonTFqamsB+d/ 9J4/PYXDGEx6i09e2QQlJVuDVQgngkUCIQC26Pj18igSZG3/fZEZ0DRPN4nBHrMb AMGKTGfQQCuzKQIgbvK9A9Ai8wsBcjiZDBVMVk306yt7pU6VZ9wF5464HNkCIF09 AL8V7omZNjHpSGEsXJyY+mGmuN+8q3JfGXUHW6XZ -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3independent2xproxy.pem000066400000000000000000000046601241116057200337650ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIBozCCAU2gAwIBAgIDCccFMA0GCSqGSIb3DQEBBQUAMDQxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExETAPBgNVBAMTCDU5MzgyODUxMB4XDTA5MDky ODE1MjYxMFoXDTA5MDkyOTAzMzExMFowSTEQMA4GA1UEBhMHVGVzdENBMTENMAsG A1UEAxMERUVDMTERMA8GA1UEAxMINTkzODI4NTExEzARBgNVBAMTCjE1NTQzMDgx MDUwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAt/fOqixDeM9gFCMbWSmadlHwa4BT Lb264gVZdwquqicarLa2sBnKb2w+3hbhkUJnGvKZh1paQT2jbUn7DHZSGQIDAQAB ozMwMTAfBgorBgEEAZtQAYFeAQH/BA4wDDAKBggrBgEFBQcVAjAOBgNVHQ8BAf8E BAMCBaAwDQYJKoZIhvcNAQEFBQADQQAt4NmFUjNXNn6LmWJr9zvrhu5R0XwDP9Ho d5aAcoWdNkZylhrOv6eNheGDiUZGPPUtK2mqw6Vanplc3S09nzla -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBALf3zqosQ3jPYBQjG1kpmnZR8GuAUy29uuIFWXcKrqonGqy2trAZ ym9sPt4W4ZFCZxrymYdaWkE9o21J+wx2UhkCAwEAAQJAALAPeLljoy77R/f9oS6z oh+aS3yWUwRzj2a/t981WfN71tnIbS6rZr60Dlu5GBeFC1opvulMpQ5l1FQ3HuNK tQIhAPPICiUX7TO+KXTJWx1HVSmGQtcbQgBQhmPTWnSNJY0TAiEAwTBNMYAKisP1 rMJq1j7WHEcluwe83TnQcgq85oUnZaMCIAeEgrOUIk93LMYaM4IaogiuyD7j60wh L5PCf8aaV68bAiEAlIwofyx+bq85hErGTdFpX7sRdxv/DHi9IEPDdtniLlMCIBLa LfuHiSNtbzX4CJu3CV6fXNQsISqVxO3kLXmgcI5m -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBvDCCASWgAwIBAgIDBTRXMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA4WhcNMDkwOTI5MDMz MTA4WjA0MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMREwDwYDVQQD Ewg1OTM4Mjg1MTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCV3aY4Zf7aTZiM+9OY /Z+IMFLqoou6e7RUuBiPXvSq0VXuzSIC+4kMhZRzbCRFEsO+sY1lAobdMeMo/S1M 6YhFAgMBAAGjMzAxMB8GCisGAQQBm1ABgV4BAf8EDjAMMAoGCCsGAQUFBxUCMA4G A1UdDwEB/wQEAwIFoDANBgkqhkiG9w0BAQUFAAOBgQAArXgjm6WPzbHSYky7Faev JRrdXJc5P6yMaob0S2FCg/I4mQ2E6O0pT1J0kzzMEsQ/d7kgregHmdnOJmEk1oqW ukVOidEOso5dQc3ukpcbAFE93FwrCNL5cjdjYcVf3a+1Fn+fFOdApFuzZavfsBnq rbf7e6HE50mgYZ1XisiJQg== -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3independentFromLimitedProxy.pem000066400000000000000000000046701241116057200356100ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIBpDCCAU6gAwIBAgIDB6gEMA0GCSqGSIb3DQEBBQUAMDUxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExEjAQBgNVBAMTCTI2Mjc5NTA5NDAeFw0wOTA5 MjgxNjM0NTVaFw0wOTA5MjkwNDM5NTVaMEkxEDAOBgNVBAYTB1Rlc3RDQTExDTAL BgNVBAMTBEVFQzExEjAQBgNVBAMTCTI2Mjc5NTA5NDESMBAGA1UEAxMJMTc4NzI5 MTA4MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAI0kC6oRGfzTbdC5jD5hPa4wmwFn eEKzIV06I2fSavtE5Uuq4xhUNutuHHSwHMi0KDEbz9ZiO7VPdBoJ8YHFUsECAwEA AaMzMDEwHwYKKwYBBAGbUAGBXgEB/wQOMAwwCgYIKwYBBQUHFQIwDgYDVR0PAQH/ BAQDAgWgMA0GCSqGSIb3DQEBBQUAA0EAc5dZmxEGzDljk44zYY21Qa9UMXakEU2x ISpRCXurBlXHDJqeVYy/+Kj5n5p+tJ5GIRI0RBmjS8+gK1O/hKcqIA== -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAI0kC6oRGfzTbdC5jD5hPa4wmwFneEKzIV06I2fSavtE5Uuq4xhU NutuHHSwHMi0KDEbz9ZiO7VPdBoJ8YHFUsECAwEAAQJAQvSgm/M08t2SMPx07XrP +fyQ7B+by3iTEVjtRulpWv1kTEG+0eaP91dPQ8t4QWkV0n7CBYc7/QJ4lSFCybdA aQIhANd7OLmvyPACORIaz+3xMlbXOjtW/WgdM4KVWsfJkharAiEAp649qxlrOxIv syAylwvMp/g8WWP2uS1O7sV4zT3sLEMCIGRGgXVX6mhWgHx+YbjW/5gN/JlUuARV Yn0oR+ClWwiVAiEAkTDbbwrMgdKmgNjxVT6/T/Yu80wOd5tWzIMqrbTfihcCIB8z 9QMOP485DHnmChzrniW7/mX0xetkJMT8WA8JAh12 -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBwDCCASmgAwIBAgIDA3r1MA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA4WhcNMDkwOTI5MDMz MTA4WjA1MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRIwEAYDVQQD EwkyNjI3OTUwOTQwXDANBgkqhkiG9w0BAQEFAANLADBIAkEApeaHiILBmwonACcF 6dFA7d41GYWeIhoro5MJPgzJ8iSD3cDTJ/7rICwxL9HxkC8Rvc34HOYv7Y/R2oN6 OPf/7QIDAQABozYwNDAiBgorBgEEAZtQAYFeAQH/BBEwDzANBgsrBgEEAZtQAQEB CTAOBgNVHQ8BAf8EBAMCBaAwDQYJKoZIhvcNAQEFBQADgYEAnT1AglOF42xgTMOq D9Y5iZAA54RZUKPxLPuKpqM+gaTFG8I1kXvXpTzkghVMkoI/8/uehJyxOzfFkYOb ol9UB9gYP7wWlaaeu3NJ5nM73MeSCej3l91AYKGSqEo2OgYX3CYVF46Ir689glLJ JTWxklIwOPUzBruOYP19jkI6wX4= -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3independentp1proxy.pem000066400000000000000000000035011241116057200337450ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIBwTCCASqgAwIBAgIDBocAMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjExWhcNMDkwOTI5MDMz MTExWjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxNjY3MDU4Njc3MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKATtVc0sisAK2nX iB9wyR9+9wDNkikZ+0xPay4I0gN4S/w+r1VxaTitivtfzuijY4q0IFiBlXkZGSVv bVxEfc0CAwEAAaM2MDQwIgYKKwYBBAGbUAGBXgEB/wQRMA8CAQEwCgYIKwYBBQUH FQIwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3DQEBBQUAA4GBACbi2ZGUq4Wmik2Q 3vqqePVRscZCinjXxax/w12nGWo0taRNGc2z+d1+GOZwv9zupKKRh7bM72rzbj6h WcFTQ7Vg0v1/4u8LFcI+HmHxtLRjRSHfzowfDqL5qjMpnALxpNQuZYW5Vog8DoDC xfVYT4ghKddp4aDRdSMfCb2t9fgo -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAKATtVc0sisAK2nXiB9wyR9+9wDNkikZ+0xPay4I0gN4S/w+r1Vx aTitivtfzuijY4q0IFiBlXkZGSVvbVxEfc0CAwEAAQI/fa77snytZxW7AF85gXYM c648QWUmXR8JL+ErRfmm6xFItksfwv99XWcFvkgfDYV1mwA8sb19nlUiZ/dBl7cB AiEA4mwxyAQH3JfsCp6f+HUVrmupD72EGiBPpAEkc5YXzUECIQC0/Njks1OTzr51 /Nbvf3itUWb3hV4Kz3W2bgktSB8xjQIhAMGHWMVtLIsQD2DEVFc5PF7pBoe9pLvw AiJcF5v0HkQBAiAZ7cNw+FP37/2PT7rHMv7p7aiPu3aem9wkV51O9G8rnQIhAMa9 D1DUaGlhBjl28DdyIIZhavOt0ZGjQqjE37AiU4FK -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi3independentproxy.pem000066400000000000000000000034751241116057200335750ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBvDCCASWgAwIBAgIDBTRXMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA4WhcNMDkwOTI5MDMz MTA4WjA0MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMREwDwYDVQQD Ewg1OTM4Mjg1MTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCV3aY4Zf7aTZiM+9OY /Z+IMFLqoou6e7RUuBiPXvSq0VXuzSIC+4kMhZRzbCRFEsO+sY1lAobdMeMo/S1M 6YhFAgMBAAGjMzAxMB8GCisGAQQBm1ABgV4BAf8EDjAMMAoGCCsGAQUFBxUCMA4G A1UdDwEB/wQEAwIFoDANBgkqhkiG9w0BAQUFAAOBgQAArXgjm6WPzbHSYky7Faev JRrdXJc5P6yMaob0S2FCg/I4mQ2E6O0pT1J0kzzMEsQ/d7kgregHmdnOJmEk1oqW ukVOidEOso5dQc3ukpcbAFE93FwrCNL5cjdjYcVf3a+1Fn+fFOdApFuzZavfsBnq rbf7e6HE50mgYZ1XisiJQg== -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAJXdpjhl/tpNmIz705j9n4gwUuqii7p7tFS4GI9e9KrRVe7NIgL7 iQyFlHNsJEUSw76xjWUCht0x4yj9LUzpiEUCAwEAAQJAaCNRMbeOVFu/OZhz/Meg Z55Mv8abmcYEFSqnxliRY3BrLpfAltyh5yXbpKOzmjrrytl1/2MMqy3ljkdhh/nx AQIhAMYJ9nSTOax9V/NJmn84XFvYHzKIaiNtipu9+XIfBcw1AiEAwbpS9fA2G8SV S6iY3e1890g+Hl7N4bQV55U3C282rdECIA4rTk/e7MRzn2RPwtcRYEJN/0VtTzLD tqQX/o30vER1AiEAnOMZ4FYiW6Z+CYGGGuQDOfdlZw77yHcg7iTnKPlt3KECIAVF UlWE8P/7fZ7DXVNLSI5zxcrGe3PzQ+gS3wqL32wU -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- gsi3limitedimpersonation2xproxy.pem000066400000000000000000000046701241116057200357300ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest-----BEGIN CERTIFICATE----- MIIBpTCCAU+gAwIBAgIDCOLMMA0GCSqGSIb3DQEBBQUAMDUxEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExEjAQBgNVBAMTCTI2Mjc5NTA5NDAeFw0wOTA5 MjgxNjQyNTFaFw0wOTA5MjkwNDQ3NTFaMEoxEDAOBgNVBAYTB1Rlc3RDQTExDTAL BgNVBAMTBEVFQzExEjAQBgNVBAMTCTI2Mjc5NTA5NDETMBEGA1UEAxMKMTM0MDEy NjEzMzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCq9AZaMV0fdCxSEGRAtk4srpzB UDxeiAYVmsxWyMNBmQnrppNePbvD7+wSBwsERfBizzV0ephcswOGnVFunS1RAgMB AAGjMzAxMB8GCisGAQQBm1ABgV4BAf8EDjAMMAoGCCsGAQUFBxUBMA4GA1UdDwEB /wQEAwIFoDANBgkqhkiG9w0BAQUFAANBAG96iXzV9TSSYMW8M5uKaNUZttO0YrRI 03lVl+g9ZFV9tbtjIWyW8sdv2VDsjwdpToH6ci7ufTZd5tpxGKM3e50= -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAKr0BloxXR90LFIQZEC2TiyunMFQPF6IBhWazFbIw0GZCeumk149 u8Pv7BIHCwRF8GLPNXR6mFyzA4adUW6dLVECAwEAAQJATgErJNyBcWjBEHEKTbzh zuGeBVdnNHs8y37m3nKdJcC9S8DK3gwdbIg7l0LJK4A/PZYSu9l8wArrGxW8gfMS QQIhAPjNBJf6BbclkAEpG6mVdzbbr3jkcRwhOu1Q1ntV10QTAiEAr+ZakCcR13sf 4d/Bmb4rovIwt+OfQjYy0hVxtkDozYsCIQClE4pXt7jxEoggbQEAnL3zdQFQ6eku a9HoQXl9bbAdZwIgP22BGpn8BQeQ55IX7ah1c7yBdM3Pj8CbcsXoyx980yECIBvx dWNCtNz6jeSibOlAQEMP3Q1FfSiBYquUCxLI8HZq -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBwDCCASmgAwIBAgIDA3r1MA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA4WhcNMDkwOTI5MDMz MTA4WjA1MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRIwEAYDVQQD EwkyNjI3OTUwOTQwXDANBgkqhkiG9w0BAQEFAANLADBIAkEApeaHiILBmwonACcF 6dFA7d41GYWeIhoro5MJPgzJ8iSD3cDTJ/7rICwxL9HxkC8Rvc34HOYv7Y/R2oN6 OPf/7QIDAQABozYwNDAiBgorBgEEAZtQAYFeAQH/BBEwDzANBgsrBgEEAZtQAQEB CTAOBgNVHQ8BAf8EBAMCBaAwDQYJKoZIhvcNAQEFBQADgYEAnT1AglOF42xgTMOq D9Y5iZAA54RZUKPxLPuKpqM+gaTFG8I1kXvXpTzkghVMkoI/8/uehJyxOzfFkYOb ol9UB9gYP7wWlaaeu3NJ5nM73MeSCej3l91AYKGSqEo2OgYX3CYVF46Ir689glLJ JTWxklIwOPUzBruOYP19jkI6wX4= -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi3limitedproxy.pem000066400000000000000000000035011241116057200327150ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBwDCCASmgAwIBAgIDA3r1MA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA4WhcNMDkwOTI5MDMz MTA4WjA1MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRIwEAYDVQQD EwkyNjI3OTUwOTQwXDANBgkqhkiG9w0BAQEFAANLADBIAkEApeaHiILBmwonACcF 6dFA7d41GYWeIhoro5MJPgzJ8iSD3cDTJ/7rICwxL9HxkC8Rvc34HOYv7Y/R2oN6 OPf/7QIDAQABozYwNDAiBgorBgEEAZtQAYFeAQH/BBEwDzANBgsrBgEEAZtQAQEB CTAOBgNVHQ8BAf8EBAMCBaAwDQYJKoZIhvcNAQEFBQADgYEAnT1AglOF42xgTMOq D9Y5iZAA54RZUKPxLPuKpqM+gaTFG8I1kXvXpTzkghVMkoI/8/uehJyxOzfFkYOb ol9UB9gYP7wWlaaeu3NJ5nM73MeSCej3l91AYKGSqEo2OgYX3CYVF46Ir689glLJ JTWxklIwOPUzBruOYP19jkI6wX4= -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAKXmh4iCwZsKJwAnBenRQO3eNRmFniIaK6OTCT4MyfIkg93A0yf+ 6yAsMS/R8ZAvEb3N+BzmL+2P0dqDejj3/+0CAwEAAQJBAIney0PnZn4yMbcutvtZ q1wDDp3nLUOp/Bo0V7n5ZtqTn2zLOOs9B383vKqc6hn23n6P7EgJjtr5bpwJBNRg JQECIQD/4HvKqyTwrp0vTdn9mehFh5Hbkz4GBLuwaPrXUmkIAwIhAKX69qRbzukD dg71Gdk7T46XyLHvFPQw/LJWzMTBYi1PAiBU+jOCgkYZXJQ9Moiz7VozRSvOlV7i 1s2Sb7rmqarSCwIgWt95M+lT8j1D4NKOkWGooBA4ADs+hKdhYp6lQ8AA6X8CIDP8 olFEfZoa5mCnodpzkaoDoEo6jD0KhXGnBQFwKYYm -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi3proxyFromgsi2.pem000066400000000000000000000045031241116057200327610ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBjDCCATagAwIBAgIDBXPKMA0GCSqGSIb3DQEBBQUAMDExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzExDjAMBgNVBAMTBXByb3h5MB4XDTA5MTAwMjE2 MzYyMloXDTA5MTAwMzA0NDEyMlowRTEQMA4GA1UEBhMHVGVzdENBMTENMAsGA1UE AxMERUVDMTEOMAwGA1UEAxMFcHJveHkxEjAQBgNVBAMTCTEzMDQ3ODI4MTBcMA0G CSqGSIb3DQEBAQUAA0sAMEgCQQCEoU8nDoasvhASZk2hssbUSnDgDTpnKBbextVG w7JXUHlDyVGyYHzDiSlmx3SV+NpG65IC0sJHDc//4AwfCiVzAgMBAAGjIzAhMB8G CisGAQQBm1ABgV4BAf8EDjAMMAoGCCsGAQUFBxUBMA0GCSqGSIb3DQEBBQUAA0EA BrI3r0+eUNiSajs+wsVsElnD0KtenvYNsQfIKbG1I6jE/m3DZs/0dJxOC2fEKWFH VAG3TD58PeYoHk3vLPBBkw== -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAIShTycOhqy+EBJmTaGyxtRKcOANOmcoFt7G1UbDsldQeUPJUbJg fMOJKWbHdJX42kbrkgLSwkcNz//gDB8KJXMCAwEAAQJAKv+dCL2F3fUUgtKV8oli OqsTox/GwnDV0U3HEVUauYGLSxcHIHsdtlPrkLF6+i2+6cB3HqYXKk/PZifnxUMx GQIhAOxfvlfJx0zKhwZWQ7cYqzH7QdpyZFivEYh2zwKjjE3/AiEAj6RvAJ0V/HJk WQLvY0W/9n+BFAA6rWY2W6IWkXyc0I0CIQDIjyhbJosjXgiZWOKV3amMfCtRJZR9 JvZSerSFAa4PkwIgTYZ27oLZue1XYX8nCpI7n+ODG/Nft/SBhAVAXvc9f4UCIEO1 5kN2wNyY4Sg0wexdRtWdHcNsWPZdSx0toO0uFkqS -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIBgTCB66ADAgECAgEAMA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rlc3RD QTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTUyNjA0WhcNMDkwOTI5MDMzMTA0 WjAxMRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMQ4wDAYDVQQDEwVw cm94eTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCpchzgrrMGN9Ej1uydasWb5vMx iZjzjB2pCkurUjjAQTRAa+wAzGRG3abWhquRctYajsU+xgpTP57063/WXGqZAgMB AAEwDQYJKoZIhvcNAQEFBQADgYEApBBqe+ZEaGi/VPwnqW4VmTzIcC9LTLwaaA17 9OqHMadTCJ9gTlZ0BtaaMOC0tKmd3J6xqvSzmG0/yNx4Zpr7QiKmZKeFqjhay6iW d0T2ZQvtrX3ODyclQ3kczy3tirh1GytmPKgCOa5t9bwRtBu4F15ZVnE2DdCBHR56 IoNx3+M= -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/gsi3restrictedproxy.pem000066400000000000000000000035411241116057200334420ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIB2DCCAUGgAwIBAgIDChc6MA0GCSqGSIb3DQEBBQUAMCExEDAOBgNVBAYTB1Rl c3RDQTExDTALBgNVBAMTBEVFQzEwHhcNMDkwOTI4MTg0MjMxWhcNMDkwOTI5MDY0 NzMxWjA2MRAwDgYDVQQGEwdUZXN0Q0ExMQ0wCwYDVQQDEwRFRUMxMRMwEQYDVQQD EwoxMTQ0MDU2MTMyMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIfkdpIEsWiEkUBD 145OSd+2gDtBhSIDSPUxz60pT5fSHF9kCO7+5bKn2CIRGxUUARIFAgNkvnAedebS M0Np9l0CAwEAAaNNMEswOQYKKwYBBAGbUAGBXgEB/wQoMCYwJAYLKwYBBAGbUAEB AQgEFTxBbGxQZXJtaXNzaW9ucy4uLj4KCjAOBgNVHQ8BAf8EBAMCBaAwDQYJKoZI hvcNAQEFBQADgYEAnHLiZ/vnU2yHIIaLprHmPA2Kwth67b93CETSIK4aEYer/YJW KLDSucjAXMrioeU0bVTu0aHWD0yga0XsPQFBXkkAlvCbzpgdCT6REAyD44Y9Z8Ns RmtoKae38SQm9L7FKtIyuG7zf6QvgoHviLHWT3M321bPDVeNz+aKF/h+FIY= -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAIfkdpIEsWiEkUBD145OSd+2gDtBhSIDSPUxz60pT5fSHF9kCO7+ 5bKn2CIRGxUUARIFAgNkvnAedebSM0Np9l0CAwEAAQJAO0HSuoW1XuA//ogW3QUi jZ0lebFufpB0JgeciePzwz3GqRe8lI9vtknwU36N0ptxc8ez4FDGoVQjUjHDeqwh wQIhAMyPqiVvrL4dT/nBuNovZRqB6GM9m3d8EmEUuBVIm+M5AiEAqhBYW4f0yuOa WVaOBnH4myTf+mBXN1j/DPh31ob7eEUCIQCFefywvsS9rIzB0FkY7TIQcNG857co 6OlpNUbEhINLaQIgNbG7dArVC0oZbaOabAaIC9P0s8S/RMZgoOPCUoWD2FECIF+m vSPe5L8Pg5+TV0Ykg33e2VWq2PoKv+DNPCkSbfC2 -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIB1jCCAT+gAwIBAgIBADANBgkqhkiG9w0BAQUFADAfMRAwDgYDVQQGEwdUZXN0 Q0ExMQswCQYDVQQDEwJDQTAeFw0wOTA5MjgxNTMwNTRaFw0xNDA5MjgxNTMxMDRa MCExEDAOBgNVBAYTB1Rlc3RDQTExDTALBgNVBAMTBEVFQzEwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAKceuxtRadJub/PZQsSNGxdY7RljcW7f1Y+Tn6hDuKgA KvKAhhEI+rEC6icHoU1ooTBuE6NtNPtFV9Q+me77EFyAIwURlsq9l6QUHsjZyxTI Vs1cIBVre4kZTGTjsKsLrMbiyVeFx7xx623FvB76ioWyMGhuZdsqGK+eHMR5wVd5 AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMA0GCSqGSIb3 DQEBBQUAA4GBADo8WsjAwT4FU3/YIHwjgjXj3acbgU41IrckNlUDl2JqKzZ+0kRr 26hkPdzpP16XCiK1e8hpd9Bz+Heq470kfIQNbjUSn7NyGeuxIvYeFhO6Njenr3Y0 hE6xHCeZX4EMTSgrvUAII8MOQ7XMx/+HloLkJNndI25oNLcDTwDDfsnK -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testca.pem000066400000000000000000000015271241116057200306670ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICSjCCAbOgAwIBAgIBADANBgkqhkiG9w0BAQQFADBGMQ0wCwYDVQQKEwRHcmlk MRMwEQYDVQQLEwpHbG9idXNUZXN0MQ4wDAYDVQQLEwVKYXJlazEQMA4GA1UEAxMH SmFyZWtDQTAeFw0wMjEyMTkxOTM3MTJaFw0wMzAxMTgxOTM3MTJaMEYxDTALBgNV BAoTBEdyaWQxEzARBgNVBAsTCkdsb2J1c1Rlc3QxDjAMBgNVBAsTBUphcmVrMRAw DgYDVQQDEwdKYXJla0NBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmC+V6 qA0qC9OjptSPr6QK6NwEoXZ2K/5GGb5dmCqX7YavC0loY9q5B2NkrOy/p0222aVr zXG/HtlussjiWSmW3Thev69zUYHUg22ORvYJm0QzyW2/rVa6kqvaRGmY3YZ6ftI9 xcy7uFrUoJ0Au2TQ6pv6ooSMJHOjiA8/htuofwIDAQABo0gwRjASBgNVHRMBAf8E CDAGAQH/AgECMB0GA1UdDgQWBBRGv5vz77jddvWi5RaUQmbohBHVNDARBglghkgB hvhCAQEEBAMCAAcwDQYJKoZIhvcNAQEEBQADgYEAFZkR8oUnfJ+f8DhjHkeOLvdS Kx2/7KrkDQ22L0+B5sgE546w5VesuDxdn7kETDkeN7vK9+Z1N5YvLHZRvgHBquDh 3yDSG1sKFIk6RDRk2epVTnQb9atQnDOfFjECGWsFv7naHdMRnXi4wnvvDzYbIQCM TwIBEf5EY8//MdQd8BY= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testca2.pem000066400000000000000000000030321241116057200307420ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIEUzCCAzugAwIBAgIBADANBgkqhkiG9w0BAQQFADB4MRMwEQYKCZImiZPyLGQB GRMDZ292MRQwEgYKCZImiZPyLGQBGRMEZm5hbDERMA8GA1UEChMIRmVybWlsYWIx IDAeBgNVBAsTF0NlcnRpZmljYXRlIEF1dGhvcml0aWVzMRYwFAYDVQQDEw1LZXJi ZXJpemVkIENBMB4XDTAzMDMyMDE4MzAxOFoXDTA0MDQyMzE4MzAxOFoweDETMBEG CgmSJomT8ixkARkTA2dvdjEUMBIGCgmSJomT8ixkARkTBGZuYWwxETAPBgNVBAoT CEZlcm1pbGFiMSAwHgYDVQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEWMBQG A1UEAxMNS2VyYmVyaXplZCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAN+TC+5elLW60X7bVI/F77kR7RZoI6ZAHgO2veY4jTbmvdVxwSicox9Tr5J8 HBTUDV97LLt76kpqzcqgcsIVPzK2SmLaexOrQk4+U/jCg3NRz6oBiesOaDOWAmct sh6KoJ+NocZ4yJfDiC7vTcj1GVTdq/nLrc6QWCC7lcEiI0+/58hUGm02v6wuBY6C nRnHun0JBQQ5suJDb07nGpstV/X9ATmSlD/MVKRpUx9GiDSIyY2Se2U3j7oRbcmQ KLnHrqukfU/YwvImA62ro1uy3i1hf3xVJUMLqTZ7ulRtBdGgpVM85F0Y8l9H7nYX NXeLCwVHn/np/qw2CvvYfQrn1msCAwEAAaOB5zCB5DAPBgNVHRMECDAGAQH/AgEA MB0GA1UdDgQWBBQSU9CdTNaeviBaLBcWzjLg1XZs2DAOBgNVHQ8BAf8EBAMCAYYw gaEGA1UdIASBmTCBljCBkwYJKwYBBO5DAQUBMIGFMEMGCCsGAQUFBwIBFjdodHRw Oi8vY29tcHV0aW5nLmZuYWwuZ292L3NlY3VyaXR5L2RvY3MvRk5BTC1DUC1DUFMu cGRmMD4GCCsGAQUFBwICMDIwDxYIRmVybWlsYWIwAwIBARofRmVybWlsYWIgS0NB IENlcnRpZmljYXRlIFBvbGljeTANBgkqhkiG9w0BAQQFAAOCAQEABAbj9o5tROS6 1mv5Dq5KjURfbqeWAuBpq38KZ8tGqdQarO3o5wzF0GqRRx1/osB5KXBKtiM/ou46 FOcRQVQPm1Isiru8FcengAZfv77eb4wfS9VBsCSGI5GVeVvnPfS++0zUwX8fWlwb liE6c6rPIfcTX8c01JOdPhsscfKyi5rSWPUMs0R/+CMLy4SPIPnBreDz3hzHDku1 Q1iwlWZCXBo/gSQyKTGIFLS13v/fgSJknc9G8ufJXJinUhcGGLg1KKyr3KG2yDVE cf7AQ902UZucFCVwFSeW55gkdWtsYqgLqgL4HWxK4qcp9kS2l/FycTK0adfTQOU7 /gNwjQxfcw== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testca3.pem000066400000000000000000000014461241116057200307520ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICJzCCAZCgAwIBAgIBADANBgkqhkiG9w0BAQQFADA2MQ0wCwYDVQQKEwRHcmlk MRQwEgYDVQQLEwtSYWNoYW5hVGVzdDEPMA0GA1UEAxMGVGVzdENBMB4XDTAzMDgw NjIxMzEzOVoXDTA4MDgwNDIxMzEzOVowNjENMAsGA1UEChMER3JpZDEUMBIGA1UE CxMLUmFjaGFuYVRlc3QxDzANBgNVBAMTBlRlc3RDQTCBnzANBgkqhkiG9w0BAQEF AAOBjQAwgYkCgYEA6NJwUv5Gs6jwP9hLeJorudM4t8fGDbNYWbAc2TiiudQiuY02 K8cpZK2ISeP0UBUx5gjwRtvJxH9hZAStiNFQJBUoffGMPl9jCsVOPXiSr18IdI/8 wwg/TYgth9azpKplj4tNFuWFyQi15mbKnLA9+TJ9ktGHXwlzFYKCI0A9D8UCAwEA AaNFMEMwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUQBa3sEMhgX2cZy4rHcy+ yNXc0nkwEQYJYIZIAYb4QgEBBAQDAgAHMA0GCSqGSIb3DQEBBAUAA4GBAHKMVoIB 0vvp3/u9CBiIebWy2cGnI5ubc/to33JTI/qxtrxb5DdItCIu104FX9T5fETa0aBY M2/hBTzm1BK2p4p0DpUsDKITFK3vHWx54Ie1lJmeVVUaxM872+3HOBihiIsDiRQM cCEiyt6DBCznzciukwSfvLkaMrVvSY75HAGy -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testca3.r0000066400000000000000000000006461241116057200305130ustar00rootroot00000000000000-----BEGIN X509 CRL----- MIIBEDB7MA0GCSqGSIb3DQEBBAUAMDYxDTALBgNVBAoTBEdyaWQxFDASBgNVBAsT C1JhY2hhbmFUZXN0MQ8wDQYDVQQDEwZUZXN0Q0EXDTAzMDgwNjIyMTAzOVoXDTA0 MDgwNTIyMTAzOVowFDASAgEBFw0wMzA4MDYyMjA5NTNaMA0GCSqGSIb3DQEBBAUA A4GBAIcijkOnSXZ8jgjaXhP1TEwOgE2Ft+xYrbE4CJyndaqg+CccCfVVIjCeyKRH aG8BRSwtAIbgopfqT4matUJ/47GyvoHClmgo0XWPzG/3X36EW7wNExzBMhiqlAxq q4TDaOe2lkdlAbysRbM2jxUvdoqr0oNVAkuJHH171nT53nu4 -----END X509 CRL----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testca3.rpem000066400000000000000000000006461241116057200311350ustar00rootroot00000000000000-----BEGIN X509 CRL----- MIIBEDB7MA0GCSqGSIb3DQEBBAUAMDYxDTALBgNVBAoTBEdyaWQxFDASBgNVBAsT C1JhY2hhbmFUZXN0MQ8wDQYDVQQDEwZUZXN0Q0EXDTAzMDgwNjIyMTAzOVoXDTA0 MDgwNTIyMTAzOVowFDASAgEBFw0wMzA4MDYyMjA5NTNaMA0GCSqGSIb3DQEBBAUA A4GBAIcijkOnSXZ8jgjaXhP1TEwOgE2Ft+xYrbE4CJyndaqg+CccCfVVIjCeyKRH aG8BRSwtAIbgopfqT4matUJ/47GyvoHClmgo0XWPzG/3X36EW7wNExzBMhiqlAxq q4TDaOe2lkdlAbysRbM2jxUvdoqr0oNVAkuJHH171nT53nu4 -----END X509 CRL----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testeec1.pem000066400000000000000000000035531241116057200311220ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIFTDCCBDSgAwIBAgIBGzANBgkqhkiG9w0BAQQFADBwMQswCQYDVQQGEwJVSzER MA8GA1UEChMIZVNjaWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMC Q0ExLTArBgkqhkiG9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51 azAeFw0wMjA4MDgxNjM5MjVaFw0wMzA4MDgxNjM5MjVaMIGBMQswCQYDVQQGEwJV SzERMA8GA1UEChMIZVNjaWVuY2UxETAPBgNVBAsTCEltcGVyaWFsMQ0wCwYDVQQH EwRMZVNDMRswGQYDVQQDExJ0aXRhbi5kb2MuaWMuYWMudWsxIDAeBgkqhkiG9w0B CQEWEXNqbjVAZG9jLmljLmFjLnVrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQCtifClcRfQ2YYDxfEDegOR+UquGzXQ/UYRaa0ABgWWQH+/ZExn0g45+DcUy+F+ XLSrAmwYxCr+OTw3oEVDYPKswdlQI9LavI+G4sliZ5D7lUog/X4RPHBhzJszhQWA V6OPAJAnNV2QlDHQtXO1p9BWujNkdKp4Z9HJ8GjAGL76cwIDAQABo4ICYTCCAl0w CQYDVR0TBAIwADARBglghkgBhvhCAQEEBAMCBkAwCwYDVR0PBAQDAgPoMC4GCWCG SAGG+EIBDQQhFh9VSyBlLVNjaWVuY2UgU2VydmVyIENlcnRpZmljYXRlMB0GA1Ud DgQWBBTV6dMZJ0CCU5USmAQXxsX4Xha/AjCBmgYDVR0jBIGSMIGPgBQCOKsRo5aA iw3TFSsIpY4w2rLaqKF0pHIwcDELMAkGA1UEBhMCVUsxETAPBgNVBAoTCGVTY2ll bmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMTAkNBMS0wKwYJKoZIhvcN AQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWuCAQAwHAYDVR0RBBUw E4ERc2puNUBkb2MuaWMuYWMudWswKQYDVR0SBCIwIIEeY2Etb3BlcmF0b3JAZ3Jp ZC1zdXBwb3J0LmFjLnVrMD0GCWCGSAGG+EIBBAQwFi5odHRwOi8vY2EuZ3JpZC1z dXBwb3J0LmFjLnVrL2NnaS1iaW4vaW1wb3J0Q1JMMD0GCWCGSAGG+EIBAwQwFi5o dHRwOi8vY2EuZ3JpZC1zdXBwb3J0LmFjLnVrL2NnaS1iaW4vaW1wb3J0Q1JMMDwG CWCGSAGG+EIBBwQvFi1odHRwOi8vY2EuZ3JpZC1zdXBwb3J0LmFjLnVrL2NnaS1i aW4vcmVuZXdVUkwwPwYDVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQtc3Vw cG9ydC5hYy51ay9jZ2ktYmluL2ltcG9ydENSTDANBgkqhkiG9w0BAQQFAAOCAQEA fOJfmY2D11uuTc6hhwWRipESFTdUgouTCnB4mqnLGldtl8chNO8yB1Pz4nGgkBAh KZLiyjQU/eH84tI47qYDKFk+cYlOdaO5KNMAP2Pi+Nqwq6NXqIlqt4k1n5tZ8TZ/ GAL5vJmmmTOVx+AAGOAILAVNZIazqdDNkjBX1hTO0tqLgDaEW7KF4OzIC7t3h6Ie BQkJWydv/9tGpTSTD/mPhXlUXaxXuqiRD/K2Q5l0LfP1LOOMLnXJJ1uvr58TJ1Gz HSxVMVc0Tgp3m4uL2Y9x6vsNqPMOdtmH3UYBV6ZvqUBuSEBmEBMiYk6nd/J1CQaF wisiVA43/DEepZJFqpsitA== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testeec2-private-enc.pem000066400000000000000000000017021241116057200333300ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,8BF1FF58816F480B G9UZoHBkwTBL/twhbxjB9JuNGWxgNZw/fuFolLvMc/dEPrXu27w6P2HZB66J3DWz S+vcOaGCKIYtWPQGx9d0oG9Bu051uE9slqCzOU3K+LmJelXl6jV0x/exhoUeoVPE zdobg1Az1U77Rve+CmMntgjdt6NVzs/Axp0eD+8RQF+gZwABy4uNymV5/v/7NR8d MCsKjM459hmFRZr40T1ZEF5vUJ4muNj0leyo5oGSKDOyDIdP4B08kkeVHKXptBv4 tc7ImnM8LJDSz27NRjawrF02So6DgVTp/12tbuQH8NhlKsxPNXi4m/8ylNgUh20e EBlDle1Q4Fi7yr+qe6A4fvz2k5ZnsMFx5NBP0wv7o8PZ16KFral4pR7m/7hHA7nm BNaiUHM5xBvd1pfGeWo2cmxR1IXlxi8kBB0P8tVBZyCALsOdH3yaWAA7oxxd7bqo LpgQGClK+YZwlQ3eUuq/PDH91o/OSNST3sdYflB4KmKP81NHu+8n9tI53owX56B3 LXF0bWgzCrDkoWBfKFlMBC3sN+tJcO7yQBKhwoDN2qwjm1t7mwM1SY0x4bb8pSo4 QxQ0xzIrUWxDBC2NglWdb7j6hRlQVI/itB6swLxMiRpwk8a0yAxvkCEU/YHYZ9/x t6I9qqEeA7+wb611DEYlAy8Aj5cnKhuy+WZ0HOYLU/YNTwIFq61BhEVZoDk51cDP K6xrWqWP4v3EnD0NI2F9p1mvzXJ4zE2e6CkSpxQ08bbEimbvoi60lPoWKY0ebovF AFNmg4+hHS0SIQcFFN6n3StcKr0m5DrGwxbR7Z3tRgE/c8UJ+PvPFw== -----END RSA PRIVATE KEY-----JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testeec2-private.pem000066400000000000000000000015661241116057200325750ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQCnHrsbUWnSbm/z2ULEjRsXWO0ZY3Fu39WPk5+oQ7ioACrygIYR CPqxAuonB6FNaKEwbhOjbTT7RVfUPpnu+xBcgCMFEZbKvZekFB7I2csUyFbNXCAV a3uJGUxk47CrC6zG4slXhce8cettxbwe+oqFsjBobmXbKhivnhzEecFXeQIDAQAB AoGBAJMH84AuWZb8+NwmSprYtnwNDdTna7Yrkh3WuIH2yvBr7V0bfFhieQThVpbu HJkZM6+DOR3wh8uGD6a5SP87vgDmi1i8XNfuaQmSFuRNyTNNiZyhpW2TXW8cyDIe uoO7EscPYh+AYFR6qPhpRyFcY5V1emceLL+0Cf/b6C7HQmkxAkEA4gZzbRlmH3sb n3kl2HL8CZVijDCOQDr1UW4ihVAYdXeJ4t9ecvOhuQU5CmAm+Doev0V78c7GgZis Smlr7XycFQJBAL1Ic5zEKec+3ejnVipXA097tKapgD+BzBdKydx/odAfyLs7fW3Y 35wJtQNAiUja+xqBIJT096Bs2dGbYpoyEtUCQGKDFUPz0gLekUeMceZJF3jF11Hq x9VO3SVEr18TbdWk6EAtwuivL0mI8TeIePOvwT70dfUKfpJ1jIJSOGwl55ECQQCe ar7oG31+nq0XOlZxRTXuFfjR69b8T+PCMsPTmbaR+6gCm/2ULAiqDa3DtQWxRiUW v6/HO2bsi22Z8lSJ/RKpAkAfUhvLrOH6gnVmyu4JbV/s6auRQUgOe7tSnuX+4FMy As25Hb6hN+U2WTyZ6f61b/1UyiPqQsTzoQ7RElseN4SN -----END RSA PRIVATE KEY-----JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testeec2.pem000066400000000000000000000027251241116057200311230ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIEIjCCAwqgAwIBAgICDdkwDQYJKoZIhvcNAQEEBQAweDETMBEGCgmSJomT8ixk ARkTA2dvdjEUMBIGCgmSJomT8ixkARkTBGZuYWwxETAPBgNVBAoTCEZlcm1pbGFi MSAwHgYDVQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGllczEWMBQGA1UEAxMNS2Vy YmVyaXplZCBDQTAeFw0wMzA0MjIxODAwMzNaFw0wMzA0MjQyMDAwMzJaMIGAMRMw EQYKCZImiZPyLGQBGRMDZ292MRQwEgYKCZImiZPyLGQBGRMEZm5hbDERMA8GA1UE ChMIRmVybWlsYWIxDzANBgNVBAsTBlBlb3BsZTEXMBUGA1UEAxMOVmlqYXkgLiBT ZWtocmkxFjAUBgoJkiaJk/IsZAEBEwZzZWtocmkwXDANBgkqhkiG9w0BAQEFAANL ADBIAkEAvmbWEDcx7tQYjLnLmN9u9KQ01J5MwuA9Ftk5j6HKNJboyiZuI3Aq2Bvd oSGb+3AlNlaVJ7rB+prZTtduAvBrsQIDAQABo4IBczCCAW8wDAYDVR0TAQH/BAIw ADAOBgNVHQ8BAf8EBAMCBaAwEQYJYIZIAYb4QgEBBAQDAgTwMDEGCWCGSAGG+EIB DQQkFiJDZXJ0aWZpY2F0ZSBpc3N1ZWQgYnkgRmVybWlsYWIgS0NBMB4GA1UdEgQX MBWBE25pZ2h0d2F0Y2hAZm5hbC5nb3YwTwYJYIZIAYb4QgEIBEIWQFVSTDpodHRw Oi8vY29tcHV0aW5nLmZuYWwuZ292L3NlY3VyaXR5L3BraS9GTkFMLUNlcnQtUG9s X0tDQS5wZGYwHwYDVR0jBBgwFoAUElPQnUzWnr4gWiwXFs4y4NV2bNgwHQYDVR0O BBYEFGVCSJQo5+4O2uzrmR/apzqms33/MBcGCSsGAQQBgXoqAQQKBAhGTkFMLkdP VjA/BgNVHREEODA2gQ9zZWtocmlAZm5hbC5nb3agIwYGKwYBBQICoBkwFxsIRk5B TC5HT1YCAQEwCBsGc2VraHJpMA0GCSqGSIb3DQEBBAUAA4IBAQAtt2jWSaMz4cSb axBoTD1e86zQDtTQoTw0hdU5VrJGRS4NCFIQBE20LxWIbjqUVAx3ByA30CiDaogM nCX2ODl0LoY0/lABsyNk9dvB8vTldcQnkqdRO5wxXzUr7Z1WvrdBq8x3qstvKXOo 5p+utcPqrna61riXvQoSHCYcSSX5uU5Sx04oXLP8kKo8YgbmUfd4W0Z0qOqUcnDo tLtrMSZi3so4PjupQOMv3ONppLYK6/QFFdM3TRX9GqHxVtpkZ09588zr+++qNfvV 3jqVFWtjLiMRIBm1Ch5hxZ3WB3xs0NqfD+v/+eR0fhYnchaoPfGwFVZGRqXEyItA gv90z1zN -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/testgsi3proxy.pem000066400000000000000000000015021241116057200322440ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICOzCCAeWgAwIBAgIDAKD/MA0GCSqGSIb3DQEBBAUAMIGAMRMwEQYKCZImiZPy LGQBGRMDZ292MRQwEgYKCZImiZPyLGQBGRMEZm5hbDERMA8GA1UEChMIRmVybWls YWIxDzANBgNVBAsTBlBlb3BsZTEXMBUGA1UEAxMOVmlqYXkgLiBTZWtocmkxFjAU BgoJkiaJk/IsZAEBEwZzZWtocmkwHhcNMDMwNDI0MjEwMDE4WhcNMDMwNDI1MDkw NTE4WjCBlTETMBEGCgmSJomT8ixkARkTA2dvdjEUMBIGCgmSJomT8ixkARkTBGZu YWwxETAPBgNVBAoTCEZlcm1pbGFiMQ8wDQYDVQQLEwZQZW9wbGUxFzAVBgNVBAMT DlZpamF5IC4gU2VraHJpMRYwFAYKCZImiZPyLGQBARMGc2VraHJpMRMwEQYDVQQD EwoxNjg2NjQwMTEwMFowDQYJKoZIhvcNAQEBBQADSQAwRgJBAIqwvOJ5ZOQsxRn1 FJsNVo88+Zk32PR7ba+LmPUQL9RR3upUk9plLFsRLrizgZcMtCTkxaOfSiBhE2y1 oCllH8MCARGjMzAxMB8GCisGAQQBm1ABgV4BAf8EDjAMMAoGCCsGAQUFBxUBMA4G A1UdDwEB/wQEAwIFoDANBgkqhkiG9w0BAQQFAANBAIU7rYHaqtqoau8mpO80Ci21 yvUwR4SVCqIkEgdYAmKenoGN8kp0C4Qm/WdhJSu+f64NZaaX6/0xFqLCpHHKCd8= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/user1ca1.pem000066400000000000000000000047071241116057200310330ustar00rootroot00000000000000Certificate: Data: Version: 3 (0x2) Serial Number: 3 (0x3) Signature Algorithm: md5WithRSAEncryption Issuer: O=test CA1, OU=simple ca, CN=Globus Test Validity Not Before: May 22 23:59:10 2006 GMT Not After : Feb 15 23:59:10 2009 GMT Subject: O=test CA1, OU=simple ca, CN=user1 Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:dd:e5:96:73:6d:6c:62:5f:21:af:33:58:4d:ae: 83:0d:f4:ab:ac:71:be:e1:e9:28:24:44:3b:4d:33: 4c:dd:60:31:54:5c:e8:0d:fc:53:a7:60:df:d6:11: 9e:79:4f:5e:01:bf:9e:88:63:c3:c2:a0:f9:b2:f4: 79:8e:73:dc:6c:15:96:ad:e3:10:9b:fd:21:39:35: b2:18:97:98:51:ef:f3:c1:4a:43:f0:a0:25:95:56: c1:2a:1a:3b:96:85:38:d0:2b:39:1f:2f:2c:69:18: 4c:28:5b:b9:48:88:03:f6:2a:aa:4f:ea:f6:ee:a3: 5a:a5:d9:f8:57:4a:b0:e6:9f Exponent: 65537 (0x10001) X509v3 extensions: Netscape Cert Type: SSL Client, SSL Server, S/MIME, Object Signing Signature Algorithm: md5WithRSAEncryption 83:68:16:35:70:b4:bf:e5:0c:0d:e6:6e:48:6d:ac:52:b9:28: a7:c7:2a:cb:3d:d5:88:72:e6:f2:0a:63:99:ca:ac:86:de:17: 1e:17:29:d8:31:a7:7e:6e:0f:63:ae:25:50:14:67:16:76:e1: 08:35:55:56:6e:61:a8:18:f7:19:83:3b:d8:20:6b:8b:94:88: 5a:4d:48:9e:32:92:b0:89:87:16:cd:e0:30:be:9a:08:e0:e0: 15:9e:36:d4:92:fb:0c:ca:aa:75:f8:65:13:c8:74:bb:c3:f7: 91:43:a1:99:f4:ed:ab:db:34:95:c0:e2:33:ac:02:55:22:35: 45:7f -----BEGIN CERTIFICATE----- MIIB/zCCAWigAwIBAgIBAzANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0 IENBMTESMBAGA1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdDAe Fw0wNjA1MjIyMzU5MTBaFw0wOTAyMTUyMzU5MTBaMDcxETAPBgNVBAoTCHRlc3Qg Q0ExMRIwEAYDVQQLEwlzaW1wbGUgY2ExDjAMBgNVBAMTBXVzZXIxMIGfMA0GCSqG SIb3DQEBAQUAA4GNADCBiQKBgQDd5ZZzbWxiXyGvM1hNroMN9Kuscb7h6SgkRDtN M0zdYDFUXOgN/FOnYN/WEZ55T14Bv56IY8PCoPmy9HmOc9xsFZat4xCb/SE5NbIY l5hR7/PBSkPwoCWVVsEqGjuWhTjQKzkfLyxpGEwoW7lIiAP2KqpP6vbuo1ql2fhX SrDmnwIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJKoZIhvcNAQEEBQAD gYEAg2gWNXC0v+UMDeZuSG2sUrkop8cqyz3ViHLm8gpjmcqsht4XHhcp2DGnfm4P Y64lUBRnFnbhCDVVVm5hqBj3GYM72CBri5SIWk1InjKSsImHFs3gML6aCODgFZ42 1JL7DMqqdfhlE8h0u8P3kUOhmfTtq9s0lcDiM6wCVSI1RX8= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/user1ca2.pem000066400000000000000000000047071241116057200310340ustar00rootroot00000000000000Certificate: Data: Version: 3 (0x2) Serial Number: 3 (0x3) Signature Algorithm: md5WithRSAEncryption Issuer: O=test CA2, OU=simple ca, CN=Globus Test Validity Not Before: May 23 01:10:19 2006 GMT Not After : May 23 01:10:19 2007 GMT Subject: O=test CA2, OU=simple ca, CN=user1 Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:f8:a4:b9:93:21:e0:ef:21:51:e2:2f:92:83:8f: e6:9f:69:3b:50:2f:34:3d:ba:33:da:a5:de:4c:84: 9f:af:45:11:04:b0:db:16:09:13:b9:97:a1:d6:9d: bb:19:ce:b7:5f:69:3f:7b:87:0a:57:05:00:8c:88: 2c:2f:82:d9:d9:6d:3c:bf:13:9d:75:16:ae:dc:91: e1:28:0b:47:cf:95:20:03:98:47:7e:da:f3:c7:e3: 01:81:b6:f9:36:ca:56:eb:4b:66:70:82:51:a8:c7: 1e:f5:44:ed:b8:ae:ad:68:93:51:ea:ca:92:b2:ca: e4:bf:25:52:a7:25:b0:c4:9d Exponent: 65537 (0x10001) X509v3 extensions: Netscape Cert Type: SSL Client, SSL Server, S/MIME, Object Signing Signature Algorithm: md5WithRSAEncryption 25:02:84:10:a3:de:1f:56:2a:41:48:58:ee:ab:9d:4f:88:ac: da:56:3b:62:00:a9:16:a1:e3:e3:81:03:c8:22:a3:d0:79:94: 76:d8:e7:62:0c:01:cc:50:e7:04:76:e8:6e:49:ed:d8:1f:93: 1d:ca:8b:52:7e:97:9f:cf:90:57:83:d0:03:97:fb:eb:cf:39: e2:2d:f3:e4:8e:32:91:6d:a7:10:54:38:09:0f:85:b5:f6:21: 25:7d:1f:2a:9e:c0:8d:52:67:fa:a7:d4:0f:5c:9e:e1:e1:18: 8a:91:21:87:f6:ed:92:16:a5:e7:f8:f5:07:1c:4a:d5:36:f2: 03:32 -----BEGIN CERTIFICATE----- MIIB/zCCAWigAwIBAgIBAzANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0 IENBMjESMBAGA1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdDAe Fw0wNjA1MjMwMTEwMTlaFw0wNzA1MjMwMTEwMTlaMDcxETAPBgNVBAoTCHRlc3Qg Q0EyMRIwEAYDVQQLEwlzaW1wbGUgY2ExDjAMBgNVBAMTBXVzZXIxMIGfMA0GCSqG SIb3DQEBAQUAA4GNADCBiQKBgQD4pLmTIeDvIVHiL5KDj+afaTtQLzQ9ujPapd5M hJ+vRREEsNsWCRO5l6HWnbsZzrdfaT97hwpXBQCMiCwvgtnZbTy/E511Fq7ckeEo C0fPlSADmEd+2vPH4wGBtvk2ylbrS2ZwglGoxx71RO24rq1ok1HqypKyyuS/JVKn JbDEnQIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJKoZIhvcNAQEEBQAD gYEAJQKEEKPeH1YqQUhY7qudT4is2lY7YgCpFqHj44EDyCKj0HmUdtjnYgwBzFDn BHbobknt2B+THcqLUn6Xn8+QV4PQA5f768854i3z5I4ykW2nEFQ4CQ+FtfYhJX0f Kp7AjVJn+qfUD1ye4eEYipEhh/btkhal5/j1BxxK1TbyAzI= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/user2ca1.pem000066400000000000000000000047071241116057200310340ustar00rootroot00000000000000Certificate: Data: Version: 3 (0x2) Serial Number: 4 (0x4) Signature Algorithm: md5WithRSAEncryption Issuer: O=test CA1, OU=simple ca, CN=Globus Test Validity Not Before: May 22 23:59:34 2006 GMT Not After : Feb 15 23:59:34 2009 GMT Subject: O=test CA1, OU=simple ca, CN=user2 Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:d6:3f:6f:0d:c2:12:4e:ec:09:26:42:19:01:76: 13:ff:4d:df:40:a0:ae:60:4c:7d:1e:54:93:31:6e: 1a:e5:c3:88:c7:2e:0a:6d:e4:88:13:82:7d:59:be: 01:b2:21:34:99:48:a1:e1:1e:e9:27:a7:e5:3f:3c: 63:f8:ad:7e:0c:94:12:1e:cf:b7:1f:e9:ff:9d:87: 74:ef:94:70:c3:73:f5:06:e7:82:e3:5b:fc:bd:f8: 8e:39:53:3a:c7:00:9d:1b:59:ce:9b:5e:c3:9f:b5: 6f:1d:60:38:36:14:c8:f3:f4:ce:5a:f6:f0:54:fd: d6:43:c8:c0:a7:f4:a1:2b:4b Exponent: 65537 (0x10001) X509v3 extensions: Netscape Cert Type: SSL Client, SSL Server, S/MIME, Object Signing Signature Algorithm: md5WithRSAEncryption ab:78:78:3c:c5:23:c0:8f:f0:d6:29:e6:ad:cc:e2:73:23:ba: a8:af:28:b8:ca:7c:99:40:32:20:dc:49:1c:32:15:db:bc:91: 52:42:e5:5a:50:01:8a:cd:75:56:0b:d0:8a:e2:86:e9:e8:46: 1f:d7:92:62:1b:88:a7:0e:f9:2c:69:ff:f1:33:d6:0d:cc:71: e3:e9:71:e2:52:31:b4:c4:97:4a:ee:d1:0c:44:16:2b:3c:3e: e2:86:12:c6:a9:cd:93:96:f3:b3:56:11:a4:95:e6:22:29:bf: 95:b5:43:65:b8:5b:0c:5f:ca:ae:8f:a4:d1:72:c3:ca:f4:35: 20:b6 -----BEGIN CERTIFICATE----- MIIB/zCCAWigAwIBAgIBBDANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0 IENBMTESMBAGA1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdDAe Fw0wNjA1MjIyMzU5MzRaFw0wOTAyMTUyMzU5MzRaMDcxETAPBgNVBAoTCHRlc3Qg Q0ExMRIwEAYDVQQLEwlzaW1wbGUgY2ExDjAMBgNVBAMTBXVzZXIyMIGfMA0GCSqG SIb3DQEBAQUAA4GNADCBiQKBgQDWP28NwhJO7AkmQhkBdhP/Td9AoK5gTH0eVJMx bhrlw4jHLgpt5IgTgn1ZvgGyITSZSKHhHuknp+U/PGP4rX4MlBIez7cf6f+dh3Tv lHDDc/UG54LjW/y9+I45UzrHAJ0bWc6bXsOftW8dYDg2FMjz9M5a9vBU/dZDyMCn 9KErSwIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJKoZIhvcNAQEEBQAD gYEAq3h4PMUjwI/w1inmrczicyO6qK8ouMp8mUAyINxJHDIV27yRUkLlWlABis11 VgvQiuKG6ehGH9eSYhuIpw75LGn/8TPWDcxx4+lx4lIxtMSXSu7RDEQWKzw+4oYS xqnNk5bzs1YRpJXmIim/lbVDZbhbDF/Kro+k0XLDyvQ1ILY= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/user2ca2.pem000066400000000000000000000047071241116057200310350ustar00rootroot00000000000000Certificate: Data: Version: 3 (0x2) Serial Number: 2 (0x2) Signature Algorithm: md5WithRSAEncryption Issuer: O=test CA2, OU=simple ca, CN=Globus Test Validity Not Before: May 23 01:10:11 2006 GMT Not After : May 23 01:10:11 2007 GMT Subject: O=test CA2, OU=simple ca, CN=user2 Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:b1:b2:ec:df:13:f2:59:78:68:42:46:2c:9f:88: 15:5d:49:a2:d6:54:d0:43:a4:05:c0:0e:e8:6c:aa: 28:5f:e9:3c:c9:f3:7e:86:3c:54:b5:67:0d:f0:11: 6e:fb:71:b7:84:b7:9f:68:84:22:05:a3:3a:b2:de: 55:86:8b:60:5a:72:8f:68:f6:86:66:8b:14:05:5c: c4:3f:84:5c:63:b0:67:08:18:9e:c2:54:24:a7:c0: f6:a8:31:5f:ab:03:5a:41:3c:0d:1d:a6:6b:a2:cd: dd:42:5a:e4:3e:a2:d6:a2:3a:94:fb:28:1d:54:02: 9d:c9:70:06:f6:7f:56:fa:b5 Exponent: 65537 (0x10001) X509v3 extensions: Netscape Cert Type: SSL Client, SSL Server, S/MIME, Object Signing Signature Algorithm: md5WithRSAEncryption c7:07:e7:c1:1c:29:e9:6f:d0:60:a7:a1:9f:f4:ff:ab:af:7c: 9d:6c:4e:78:25:70:2e:c9:f7:2e:f5:bc:e7:aa:6d:29:47:a7: 8a:9b:51:b4:09:26:f7:25:93:b7:85:1b:a7:6d:0d:00:d7:07: 43:53:a6:69:4a:99:91:5c:80:70:3f:a0:7e:57:d1:75:8e:94: 41:7c:4e:ee:74:4a:9f:b3:d2:f3:77:7a:e2:81:53:f7:44:ed: ee:02:d1:ac:dd:29:03:27:6e:d9:18:f9:61:b0:bc:81:f3:ce: 91:3c:8e:d8:96:fa:89:19:47:5f:39:03:fb:0d:47:61:8f:63: 3b:03 -----BEGIN CERTIFICATE----- MIIB/zCCAWigAwIBAgIBAjANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0 IENBMjESMBAGA1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdDAe Fw0wNjA1MjMwMTEwMTFaFw0wNzA1MjMwMTEwMTFaMDcxETAPBgNVBAoTCHRlc3Qg Q0EyMRIwEAYDVQQLEwlzaW1wbGUgY2ExDjAMBgNVBAMTBXVzZXIyMIGfMA0GCSqG SIb3DQEBAQUAA4GNADCBiQKBgQCxsuzfE/JZeGhCRiyfiBVdSaLWVNBDpAXADuhs qihf6TzJ836GPFS1Zw3wEW77cbeEt59ohCIFozqy3lWGi2Baco9o9oZmixQFXMQ/ hFxjsGcIGJ7CVCSnwPaoMV+rA1pBPA0dpmuizd1CWuQ+otaiOpT7KB1UAp3JcAb2 f1b6tQIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJKoZIhvcNAQEEBQAD gYEAxwfnwRwp6W/QYKehn/T/q698nWxOeCVwLsn3LvW856ptKUeniptRtAkm9yWT t4Ubp20NANcHQ1OmaUqZkVyAcD+gflfRdY6UQXxO7nRKn7PS83d64oFT90Tt7gLR rN0pAydu2Rj5YbC8gfPOkTyO2Jb6iRlHXzkD+w1HYY9jOwM= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/user3ca1.pem000066400000000000000000000047641241116057200310400ustar00rootroot00000000000000Certificate: Data: Version: 3 (0x2) Serial Number: 3 (0x3) Signature Algorithm: md5WithRSAEncryption Issuer: O=Test CA1, OU=simple ca, CN=Globus Test Validity Not Before: Nov 24 06:45:24 2003 GMT Not After : Nov 23 06:45:24 2004 GMT Subject: O=Test CA1, OU=simple ca, OU=mcs.anl.gov, CN=user3 Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:cd:40:24:8f:e1:4a:b7:61:08:2b:0f:58:c1:6f: 2a:af:fc:63:19:0a:16:05:b6:ff:95:87:78:40:21: 8d:7f:d1:2a:bc:f2:7d:3b:0f:32:85:5f:b6:ed:ca: 10:47:e3:58:5b:49:0c:91:bf:81:f5:ce:77:0f:13: fd:a6:37:51:59:6c:16:47:c7:f1:f6:90:c2:2a:cb: 69:72:5f:0d:30:5b:cf:fb:5e:f2:62:f7:7e:70:6e: 29:f0:2d:cf:91:2e:58:aa:0c:5a:7c:b0:f4:80:10: 59:99:ce:9c:2d:84:5e:fd:41:f2:fe:c6:d8:35:0c: 4d:c2:4d:1e:b6:04:60:dc:69 Exponent: 65537 (0x10001) X509v3 extensions: Netscape Cert Type: SSL Client, SSL Server, S/MIME, Object Signing Signature Algorithm: md5WithRSAEncryption 7d:ea:0b:60:b5:5f:81:99:3c:8d:c0:e4:6a:45:34:63:ea:f8: 36:e5:b9:45:05:4e:a9:a7:b6:6e:7d:9c:fc:c8:e3:e9:96:fb: 6e:9e:bf:d8:f9:4f:f7:f5:2d:5e:46:a6:e6:5d:2a:dd:5a:77: 00:41:29:c7:dd:83:61:b0:b7:61:4b:f7:79:03:66:9f:b9:8e: 87:ab:62:a6:40:91:bf:fd:58:de:b4:6b:5b:cf:15:25:0f:da: 1d:cd:81:ba:e8:88:f4:8c:d4:8f:e4:91:a2:77:c0:87:df:de: ea:99:fb:7b:fd:89:89:3c:44:cf:50:1b:a3:cf:40:ef:8c:c8: c4:4d -----BEGIN CERTIFICATE----- MIICFTCCAX6gAwIBAgIBAzANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwhUZXN0 IENBMTESMBAGA1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdDAe Fw0wMzExMjQwNjQ1MjRaFw0wNDExMjMwNjQ1MjRaME0xETAPBgNVBAoTCFRlc3Qg Q0ExMRIwEAYDVQQLEwlzaW1wbGUgY2ExFDASBgNVBAsTC21jcy5hbmwuZ292MQ4w DAYDVQQDEwV1c2VyMzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAzUAkj+FK t2EIKw9YwW8qr/xjGQoWBbb/lYd4QCGNf9EqvPJ9Ow8yhV+27coQR+NYW0kMkb+B 9c53DxP9pjdRWWwWR8fx9pDCKstpcl8NMFvP+17yYvd+cG4p8C3PkS5YqgxafLD0 gBBZmc6cLYRe/UHy/sbYNQxNwk0etgRg3GkCAwEAAaMVMBMwEQYJYIZIAYb4QgEB BAQDAgTwMA0GCSqGSIb3DQEBBAUAA4GBAH3qC2C1X4GZPI3A5GpFNGPq+DbluUUF Tqmntm59nPzI4+mW+26ev9j5T/f1LV5GpuZdKt1adwBBKcfdg2Gwt2FL93kDZp+5 joerYqZAkb/9WN60a1vPFSUP2h3NgbroiPSM1I/kkaJ3wIff3uqZ+3v9iYk8RM9Q G6PPQO+MyMRN -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/user3ca2.pem000066400000000000000000000047071241116057200310360ustar00rootroot00000000000000Certificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: md5WithRSAEncryption Issuer: O=test CA2, OU=simple ca, CN=Globus Test Validity Not Before: May 23 01:09:59 2006 GMT Not After : May 23 01:09:59 2007 GMT Subject: O=test CA2, OU=simple ca, CN=user3 Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:da:42:3d:c9:67:f7:04:18:59:bc:23:30:da:3b: 6d:26:cd:5e:a9:1b:89:b4:da:d2:77:e3:92:9c:ff: 8b:c3:01:06:bd:34:1b:ef:7e:86:58:5d:e0:92:f6: 06:c8:20:9e:9d:54:9a:a5:7e:2a:51:69:84:c0:70: 35:e1:f2:b6:cb:f0:73:cc:d8:6a:11:1d:7d:aa:7e: 78:c4:fa:57:0f:d8:e0:bc:62:30:68:bb:4b:6f:e0: fb:87:bd:f4:b0:e6:f3:bb:4f:4d:ad:26:0e:85:7e: a1:c0:69:b4:e6:d7:af:98:65:6b:0e:d6:8e:ba:cc: 7f:89:c2:48:25:dd:c6:b2:83 Exponent: 65537 (0x10001) X509v3 extensions: Netscape Cert Type: SSL Client, SSL Server, S/MIME, Object Signing Signature Algorithm: md5WithRSAEncryption 19:16:94:0b:71:ba:72:0d:54:88:ba:1e:00:1c:7f:eb:af:ff: 46:cb:2e:92:99:d3:8c:c0:e3:31:c0:44:e3:ed:fc:44:02:21: 0c:0f:7a:ae:5e:a6:82:52:9b:bd:aa:3e:7f:de:d6:45:0f:4a: 3e:1c:83:ab:79:a7:ad:97:40:84:be:37:55:09:56:ee:a7:ed: 75:50:c8:76:e9:90:c9:b7:87:01:44:88:c6:30:b8:a9:c4:a6: ac:0f:91:33:17:42:78:f0:26:d8:08:51:f1:81:db:a0:b6:94: d2:57:3a:f5:f1:5d:91:f8:03:d1:ad:c0:c4:70:63:70:8f:93: 94:69 -----BEGIN CERTIFICATE----- MIIB/zCCAWigAwIBAgIBATANBgkqhkiG9w0BAQQFADA9MREwDwYDVQQKEwh0ZXN0 IENBMjESMBAGA1UECxMJc2ltcGxlIGNhMRQwEgYDVQQDEwtHbG9idXMgVGVzdDAe Fw0wNjA1MjMwMTA5NTlaFw0wNzA1MjMwMTA5NTlaMDcxETAPBgNVBAoTCHRlc3Qg Q0EyMRIwEAYDVQQLEwlzaW1wbGUgY2ExDjAMBgNVBAMTBXVzZXIzMIGfMA0GCSqG SIb3DQEBAQUAA4GNADCBiQKBgQDaQj3JZ/cEGFm8IzDaO20mzV6pG4m02tJ345Kc /4vDAQa9NBvvfoZYXeCS9gbIIJ6dVJqlfipRaYTAcDXh8rbL8HPM2GoRHX2qfnjE +lcP2OC8YjBou0tv4PuHvfSw5vO7T02tJg6FfqHAabTm16+YZWsO1o66zH+Jwkgl 3caygwIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJKoZIhvcNAQEEBQAD gYEAGRaUC3G6cg1UiLoeABx/66//RssukpnTjMDjMcBE4+38RAIhDA96rl6mglKb vao+f97WRQ9KPhyDq3mnrZdAhL43VQlW7qftdVDIdumQybeHAUSIxjC4qcSmrA+R MxdCePAm2AhR8YHboLaU0lc69fFdkfgD0a3AxHBjcI+TlGk= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/ssl-proxies/src/test/resources/validatorTest/usercert.pem000066400000000000000000000014721241116057200312370ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICNTCCAZ6gAwIBAgICOfowDQYJKoZIhvcNAQEEBQAwRzELMAkGA1UEBhMCVVMx DzANBgNVBAoTBkdsb2J1czEnMCUGA1UEAxMeR2xvYnVzIENlcnRpZmljYXRpb24g QXV0aG9yaXR5MB4XDTAzMDQwOTE2MjcxMVoXDTA0MDQwODE2MjcxMVowYjELMAkG A1UEBhMCVVMxDzANBgNVBAoTBkdsb2J1czEkMCIGA1UEChMbQXJnb25uZSBOYXRp b25hbCBMYWJvcmF0b3J5MQwwCgYDVQQLEwNNQ1MxDjAMBgNVBAMTBWdhd29yMIGf MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSJNRipxO6Po8EpJpw1xjg3PeAshq+ ay8UJ3aNmlmO2LJZXcTezVEiCQozf+SyNCB4QHzHgL9dxiLf0E96m4FVgmN3tSkU V4Aa4AKD7V9WU0XRrV5uRN1RJ2Dtp83IVFL8BNef/l+s0Ylwq5Nq8A7jXkdbFcug eEdJYy1M8Cx8swIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBsAwDQYJKoZIhvcN AQEEBQADgYEAI1Rbppjx5fIAwNJgIaIUbZXCR8L7fwMVb2JsquzNApxpDm3Iaq0F 0wbLQfqdmxJ+R/VotS1OE7T4bNs7GnMI4fOP0Rh2m6IrRwzQZJZD8btRRKTnAKkc kKPXXvsRTRLRIsxOI2oy8PGGW54dbLbSnbXHhqZsLmgosaWzus6N6sg= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/test-utils/000077500000000000000000000000001241116057200201145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/pom.xml000066400000000000000000000020241241116057200214270ustar00rootroot00000000000000 parent org.jglobus 2.1.0 4.0.0 test-utils Test Utilities commons-io commons-io org.apache.httpcomponents httpclient commons-logging commons-logging compile log4j log4j compile JGlobus-JGlobus-Release-2.1.0/test-utils/src/000077500000000000000000000000001241116057200207035ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/000077500000000000000000000000001241116057200216275ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/java/000077500000000000000000000000001241116057200225505ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/java/org/000077500000000000000000000000001241116057200233375ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/java/org/globus/000077500000000000000000000000001241116057200246325ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/java/org/globus/gsi/000077500000000000000000000000001241116057200254145ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/java/org/globus/gsi/testutils/000077500000000000000000000000001241116057200274545ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/java/org/globus/gsi/testutils/DirSetupUtil.java000066400000000000000000000045501241116057200327200ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.testutils; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class DirSetupUtil { private Map map = new HashMap(); private String[] fileNames; private File tempDir; public DirSetupUtil(String[] inputFileNames) { this.fileNames = inputFileNames; } public void createTempDirectory() throws IOException { this.tempDir = File.createTempFile("temp", Long.toString(System.nanoTime())); if (!(tempDir.delete())) { throw new IOException( "Could not delete temp file: " + this.tempDir.getAbsolutePath()); } if (!(tempDir.mkdir())) { throw new IOException( "Could not create temp directory: " + this.tempDir.getAbsolutePath()); } } public void copy() throws Exception { for (String fileName : this.fileNames) { FileSetupUtil util = new FileSetupUtil(fileName); util.copyFileToTemp(this.tempDir); this.map.put(fileName, util); } } // Original file name. public FileSetupUtil getFileSetupUtil(String filename) { return this.map.get(filename); } public File getTempDirectory() { return this.tempDir; } public String getTempDirectoryName() { if (this.tempDir != null) { return this.tempDir.getAbsolutePath(); } return null; } public void delete() throws IOException { FileUtils.deleteDirectory(this.tempDir); } } JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/java/org/globus/gsi/testutils/FileSetupUtil.java000066400000000000000000000061731241116057200330640ustar00rootroot00000000000000/* * Copyright 1999-2010 University of Chicago * * 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 org.globus.gsi.testutils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * FILL ME * * @author ranantha@mcs.anl.gov */ public class FileSetupUtil { private String filename; private File tempFile; private Log logger = LogFactory.getLog(getClass()); private static final int SLEEP_LENGTH = 1000; public FileSetupUtil(String inputFileName) { this.filename = inputFileName; } public File getTempFile() { return this.tempFile; } public void copyFileToTemp() throws IOException { copyFileToTemp(null); } public void copyFileToTemp(File dir) throws IOException { ClassLoader loader = FileSetupUtil.class.getClassLoader(); int index = filename.lastIndexOf('.'); this.tempFile = File.createTempFile("globusSecurityTest", filename.substring(index, filename.length()), dir); InputStream in = loader.getResourceAsStream(this.filename); FileWriter writer = new FileWriter(this.tempFile); try { int c = in.read(); while (c != -1) { writer.write(c); c = in.read(); } } finally { in.close(); writer.close(); } } public String getAbsoluteFilename() { return this.tempFile.getAbsolutePath(); } public String getTempFilename() { return this.tempFile.getName(); } public URL getURL() { URL url = null; try { url = this.tempFile.toURI().toURL(); } catch (MalformedURLException e) { logger.info("This should not have happened", e); //This really shouldn't happen, so let's print in the random chance it does } return url; } public void deleteFile() { if (this.tempFile != null && !this.tempFile.delete()) { logger.info("File was not deleted: " + this.tempFile.getAbsolutePath()); } } public void modifyFile() throws InterruptedException, IOException { if (this.tempFile != null) { // FIXME: only way for modified time to have some delta Thread.sleep(SLEEP_LENGTH); FileWriter writer = new FileWriter(this.tempFile, true); try { writer.write("\n"); } finally { writer.close(); } } } } JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/java/org/globus/gsi/testutils/SecurityTest.java000066400000000000000000000001061241116057200327630ustar00rootroot00000000000000package org.globus.gsi.testutils; public interface SecurityTest { } JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/000077500000000000000000000000001241116057200236415ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/cacert.pem000066400000000000000000000016301241116057200256050ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICeTCCAeKgAwIBAgIBADANBgkqhkiG9w0BAQUFADA0MQ0wCwYDVQQKEwRBdXRv MRYwFAYDVQQLEw1KR2xvYnVzVGVzdENBMQswCQYDVQQDEwJDQTAeFw0xMTAzMTUw MTE4NTdaFw0xNjAzMTUwMTE5MDdaMDQxDTALBgNVBAoTBEF1dG8xFjAUBgNVBAsT DUpHbG9idXNUZXN0Q0ExCzAJBgNVBAMTAkNBMIGfMA0GCSqGSIb3DQEBAQUAA4GN ADCBiQKBgQCkfnJsLXlvbNFQB7k1i8A86R7e/9BSwYif/OG0bNhsnewgLekyrRa+ HmReo0cBc8+wvUexHEyBKhOCmpyCW4mzTvH6lVSQHb4Gef54tc4wZS/R6luGweRU zW8CWOOTCj0nJIviefkKHhB5v/beHmhP+i4T0Y08Rz4FBraq/uL9AQIDAQABo4Ga MIGXMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHGg7KW9MikplKFKhlCEtrs+ pnw0MFgGA1UdIwRRME+AFHGg7KW9MikplKFKhlCEtrs+pnw0oTQxDTALBgNVBAoT BEF1dG8xFjAUBgNVBAsTDUpHbG9idXNUZXN0Q0ExCzAJBgNVBAMTAkNBggEAMAsG A1UdDwQEAwIBBjANBgkqhkiG9w0BAQUFAAOBgQBFwAHr43BToa1G3zcSX7jykigw SBCOJgncdO7H4cYhP5xNrslzwo9J3iPFqT9Lgdfdw7b4i+ey9CektgiUHUK78EkS 4bM3L29V2bcEjLIXhWBzI18j2oIw+aybc5U/A0VgdPh9M1JpKT99FxzliWz541FR MQvlvnnX4vUr0Th0HQ== -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/crls/000077500000000000000000000000001241116057200246045ustar00rootroot00000000000000JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/crls/1c3f2ca8.r0000066400000000000000000000205431241116057200262650ustar00rootroot00000000000000-----BEGIN X509 CRL----- MIIYfzCCF2cCAQEwDQYJKoZIhvcNAQEFBQAwaTETMBEGCgmSJomT8ixkARkWA29y ZzEYMBYGCgmSJomT8ixkARkWCERPRUdyaWRzMSAwHgYDVQQLExdDZXJ0aWZpY2F0 ZSBBdXRob3JpdGllczEWMBQGA1UEAxMNRE9FR3JpZHMgQ0EgMRcNMDkwODA2MTU0 OTIxWhcNMDkwOTA1MTU0OTIxWjCCFrcwEwICZzoXDTA4MDkyNTEzNDQ1NlowPAID AIUmFw0wOTA3MDgxODQyMDlaMCYwCgYDVR0VBAMKAQMwGAYDVR0YBBEYDzIwMDkw NzA4MDcwMDAwWjAiAgMAgKQXDTA5MDUxMzIyMDU0OFowDDAKBgNVHRUEAwoBBTAw AgMAhR8XDTA5MDcwOTIxNDc0MFowGjAYBgNVHRgEERgPMjAwOTA3MDkwNTAwMDBa MBMCAnkgFw0wOTA3MTMxOTM2NTdaMC8CAnYfFw0wOTA0MDIxNzQ0MDBaMBowGAYD VR0YBBEYDzIwMDkwNDAyMDUwMDAwWjAUAgMAhQoXDTA5MDcwNzEyNTAwN1owLwIC ZxwXDTA4MDkxOTE4NDAyOFowGjAYBgNVHRgEERgPMjAwODA5MTkwNTAwMDBaMCIC AwCAhxcNMDkwNTE0MjAwMDIwWjAMMAoGA1UdFQQDCgEEMC8CAnYJFw0wOTAxMjcx NTM5MTJaMBowGAYDVR0YBBEYDzIwMDkwMTI3MDYwMDAwWjATAgJokRcNMDgxMDIw MjAxMDMzWjAvAgJ2BxcNMDkwMTIzMTkwMzQ2WjAaMBgGA1UdGAQRGA8yMDA5MDEy MzA1MDAwMFowIQICboQXDTA5MDMxODIwMjAzMlowDDAKBgNVHRUEAwoBBTA7AgJo hxcNMDgxMjEyMjIyODQ0WjAmMAoGA1UdFQQDCgEDMBgGA1UdGAQRGA8yMDA4MTAw NjA3MDAwMFowIQICboMXDTA5MDMxODIwMjAwOVowDDAKBgNVHRUEAwoBBTAiAgMA gHIXDTA5MDYyNTE0MjYyNFowDDAKBgNVHRUEAwoBATATAgJ0eBcNMDkwNjE5MTYz MDQ0WjAhAgJ0dxcNMDgxMjMwMjMxMzMwWjAMMAoGA1UdFQQDCgEFMBMCAmV/Fw0w ODA5MjUxMzUzMzBaMCICAwCH5BcNMDkwODA0MTU0OTIwWjAMMAoGA1UdFQQDCgEB MBMCAnRvFw0wODEyMzAxNDQ5NTZaMC8CAndtFw0wOTAyMTEyMDEwMTBaMBowGAYD VR0YBBEYDzIwMDkwMjExMDUwMDAwWjAiAgMAh+EXDTA5MDgwNDAwMjE0NFowDDAK BgNVHRUEAwoBBTAUAgMAgeEXDTA5MDYwNDIxMDM0MVowIQICZXMXDTA4MDgyNjIw NTgyNVowDDAKBgNVHRUEAwoBBDATAgJlchcNMDgwOTI1MTM1MzAwWjAUAgMAgd4X DTA5MDYwNDIxMTQwOFowEwICZXEXDTA4MDkyNTEzNTIzNVowEwICZW4XDTA4MDky NTEzNTIxMlowIgIDAIBaFw0wOTA1MTUxNDUzMzRaMAwwCgYDVR0VBAMKAQQwFAID AIHZFw0wOTA2MDQyMTE0NTFaMBQCAwCB2BcNMDkwNjA0MjEyMDEwWjATAgJlZhcN MDgwOTI1MTM1MTQ3WjAhAgJ6URcNMDkwNTE1MTQ1MDUwWjAMMAoGA1UdFQQDCgEE MCECAnLPFw0wOTA2MTkxNjMwMTNaMAwwCgYDVR0VBAMKAQUwIQICZVcXDTA5MDMz MDE5Mzc1NlowDDAKBgNVHRUEAwoBBDAvAgJ0TBcNMDkwMTE0MTcwMDIxWjAaMBgG A1UdGAQRGA8yMDA5MDExNDA2MDAwMFowIQICZVUXDTA4MDgyNTE5MTE0NlowDDAK BgNVHRUEAwoBAzA7AgJ3SBcNMDkwMjEwMTcwNzAwWjAmMAoGA1UdFQQDCgEDMBgG A1UdGAQRGA8yMDA5MDIxMDA1MDAwMFowLwICfUQXDTA5MDQxMzE2NTkwOFowGjAY BgNVHRgEERgPMjAwOTA0MTMwNTAwMDBaMBQCAwCGPhcNMDkwNzI0MDA0MzI5WjAv AgJj0xcNMDgwODEyMjA1NTA1WjAaMBgGA1UdGAQRGA8yMDA4MDgxMjA1MDAwMFow LwICdEUXDTA4MTIyMzIyMDQzOFowGjAYBgNVHRgEERgPMjAwODEyMjMwNjAwMDBa MCICAwCAORcNMDkwNjA1MjE0NDMwWjAMMAoGA1UdFQQDCgEFMBQCAwCHshcNMDkw ODAzMjAzMTEzWjA7AgJyvxcNMDkwMjA5MTkyMzI0WjAmMAoGA1UdFQQDCgEEMBgG A1UdGAQRGA8yMDA4MDIwOTA2MDAwMFowIQICejYXDTA5MDMxNjIwMTQxMlowDDAK BgNVHRUEAwoBBTATAgJxOBcNMDgxMTE3MTY1MzIzWjAhAgJ3NBcNMDkwMjI1MjI1 NzU4WjAMMAoGA1UdFQQDCgEFMDsCAnoyFw0wOTAzMTYxODIwMTNaMCYwCgYDVR0V BAMKAQQwGAYDVR0YBBEYDzIwMDkwMzE2MDUwMDAwWjA7AgJ6MRcNMDkwMzE2MTgx OTIxWjAmMAoGA1UdFQQDCgEEMBgGA1UdGAQRGA8yMDA5MDMxNjA1MDAwMFowOwIC cTEXDTA4MTIxMjIyMTkwOVowJjAKBgNVHRUEAwoBAzAYBgNVHRgEERgPMjAwODEx MTcwODAwMDBaMC8CAncrFw0wOTA0MTAxODUwNDZaMBowGAYDVR0YBBEYDzIwMDkw NDEwMDUwMDAwWjAvAgJ3KBcNMDkwMzEyMjAxNjMwWjAaMBgGA1UdGAQRGA8yMDA5 MDMxMjA0MDAwMFowLwICcSkXDTA5MDExNDIwMzkzN1owGjAYBgNVHRgEERgPMjAw OTAxMTQwNjAwMDBaMCECAnKjFw0wODEyMTYyMjIwNDlaMAwwCgYDVR0VBAMKAQUw OwICdx8XDTA5MDIwOTE3NTc1N1owJjAKBgNVHRUEAwoBBDAYBgNVHRgEERgPMjAw OTAyMDkwNjAwMDBaMDsCAnceFw0wOTAyMDkxNzU2MTVaMCYwCgYDVR0VBAMKAQQw GAYDVR0YBBEYDzIwMDkwMjA5MDYwMDAwWjATAgJ9GRcNMDkwNDA4MTkxNDE1WjA7 AgJmpxcNMDkwMjA1MDIwNTM1WjAmMAoGA1UdFQQDCgEEMBgGA1UdGAQRGA8yMDA5 MDIwMTA1MDAwMFowEwICaCMXDTA4MTIxMzE3NTA0N1owOwICcpoXDTA5MDQyMDIy NTYzMlowJjAKBgNVHRUEAwoBATAYBgNVHRgEERgPMjAwOTA0MTcwNjAwMDBaMC8C AnuIFw0wOTAzMjUxOTE2NDNaMBowGAYDVR0YBBEYDzIwMDkwMzI1MDUwMDAwWjAv AgJ7hhcNMDkwMzI1MTc0MjA5WjAaMBgGA1UdGAQRGA8yMDA5MDMyNTA1MDAwMFow EwICZo8XDTA4MDkyNTEzNTUzNVowEwICZo4XDTA4MDkyNTEzNTUwNFowEwICZo0X DTA4MDkyNTEzNTQzM1owLwICe30XDTA5MDMyNDE4NTkwMFowGjAYBgNVHRgEERgP MjAwOTAzMjQwNTAwMDBaMC8CAm4CFw0wOTAzMzAyMTMxNThaMBowGAYDVR0YBBEY DzIwMDkwMzMwMDUwMDAwWjATAgJ1ehcNMDkwMTE1MjExMjU0WjAvAgJt/hcNMDgx MDE2MTUyODM0WjAaMBgGA1UdGAQRGA8yMDA4MTAxNTA2MDAwMFowOwICcnoXDTA5 MDcyODIxMjg1NlowJjAKBgNVHRUEAwoBATAYBgNVHRgEERgPMjAwOTA3MjcwNzAw MDBaMDsCAnJ5Fw0wOTA3MjgyMTI4NTZaMCYwCgYDVR0VBAMKAQEwGAYDVR0YBBEY DzIwMDkwNzI3MDcwMDAwWjATAgJmfhcNMDgwOTI1MTM1NDEwWjAhAgJ/7BcNMDkw NTA4MjIwMDIxWjAMMAoGA1UdFQQDCgEEMDACAwCEaRcNMDkwNzI4MjExOTE2WjAa MBgGA1UdGAQRGA8yMDA5MDcyNzA3MDAwMFowEwICZPkXDTA4MDkyNTEzNTEwN1ow LwICbfMXDTA5MDcyODIxMjIwNFowGjAYBgNVHRgEERgPMjAwOTA3MjcwNzAwMDBa MBMCAmT4Fw0wODA5MjUxMzUwMzBaMC8CAm3yFw0wOTA3MjgyMTIyMDRaMBowGAYD VR0YBBEYDzIwMDkwNzI3MDcwMDAwWjAvAgJ27BcNMDkwMjExMjAxMTE2WjAaMBgG A1UdGAQRGA8yMDA5MDIxMTA1MDAwMFowEwICZPcXDTA5MDcyMDE2MTAzN1owLwIC dWoXDTA5MDIxOTE4MzkwNlowGjAYBgNVHRgEERgPMjAwOTAyMTkwNjAwMDBaMBQC AwCF3hcNMDkwNzIwMTYxMTI1WjAvAgJ54xcNMDkwNDMwMTUxMDQ3WjAaMBgGA1Ud GAQRGA8yMDA5MDQzMDA0MDAwMFowEwICeeIXDTA5MDMxNTE3Mjk0N1owFAIDAIXX Fw0wOTA3MjExMzI2MzRaMCICAwCC1xcNMDkwNjA5MTU1NDU5WjAMMAoGA1UdFQQD CgEBMC8CAm9SFw0wOTAxMTQyMDM5MTJaMBowGAYDVR0YBBEYDzIwMDkwMTE0MDYw MDAwWjA7AgJyThcNMDgxMjA3MjIwMzAyWjAmMAoGA1UdFQQDCgEBMBgGA1UdGAQR GA8yMDA4MTIwNjA4MDAwMFowLwICZNYXDTA5MDIyNDIxMTE1M1owGjAYBgNVHRgE ERgPMjAwOTAyMjQwNjAwMDBaMBQCAwCEOxcNMDkwNjI5MTg0ODA5WjAhAgJkzhcN MDgwODE1MjMxNzAzWjAMMAoGA1UdFQQDCgEFMC8CAnJFFw0wODEyMTcxODQwMjda MBowGAYDVR0YBBEYDzIwMDgxMjE3MDUwMDAwWjATAgJkyhcNMDgwODE3MDAwNTU3 WjAvAgJyPRcNMDkwMTIwMTgxOTExWjAaMBgGA1UdGAQRGA8yMDA5MDEyMDA1MDAw MFowEwICZMQXDTA4MDkyNTEzNDk0M1owOwICZ8AXDTA4MTIwNjE1MjI0OFowJjAK BgNVHRUEAwoBATAYBgNVHRgEERgPMjAwODA5MjMwNTAwMDBaMDsCAm87Fw0wOTA0 MTQxOTU5MDZaMCYwCgYDVR0VBAMKAQQwGAYDVR0YBBEYDzIwMDkwNDE0MDQwMDAw WjAvAgJyNxcNMDgxMjA1MTM1NjUwWjAaMBgGA1UdGAQRGA8yMDA4MTIwNTA1MDAw MFowOwICV0kXDTA4MDMzMTIzMjgwOVowJjAKBgNVHRUEAwoBBDAYBgNVHRgEERgP MjAwODAzMzEwNzAwMDBaMDsCAnU0Fw0wOTAxMjIxODQxMjRaMCYwCgYDVR0VBAMK AQQwGAYDVR0YBBEYDzIwMDkwMTIxMDgwMDAwWjA7AgJnsxcNMDgwOTI0MjI1NDMy WjAmMAoGA1UdFQQDCgEFMBgGA1UdGAQRGA8yMDA4MDkyMjA3MDAwMFowLwICZLIX DTA5MDExMzE2MTQ0NVowGjAYBgNVHRgEERgPMjAwOTAxMTMwNjAwMDBaMDsCAnUk Fw0wOTA2MTUxOTUwMzlaMCYwCgYDVR0VBAMKAQEwGAYDVR0YBBEYDzIwMDkwNjEy MDQwMDAwWjAvAgJ7GxcNMDkwMzIwMTgxMzQ4WjAaMBgGA1UdGAQRGA8yMDA5MDMy MDA1MDAwMFowLwICZKkXDTA5MDIyNDIxMTEyOVowGjAYBgNVHRgEERgPMjAwOTAy MjQwNjAwMDBaMBMCAmSlFw0wODA5MDgxOTA2NTNaMBMCAngUFw0wOTAyMTkxOTUz MzFaMDsCAm8XFw0wODEwMzAxNjM4MzVaMCYwCgYDVR0VBAMKAQMwGAYDVR0YBBEY DzIwMDgxMDMwMDUwMDAwWjAvAgJ5jhcNMDkwMzEyMjAxNzAyWjAaMBgGA1UdGAQR GA8yMDA5MDMxMjA0MDAwMFowEwICchIXDTA5MDQwNzIzMDIwN1owLwICfgcXDTA5 MDQyNzE1MzU1NVowGjAYBgNVHRgEERgPMjAwOTA0MjcwNTAwMDBaMC8CAn4GFw0w OTA0MjcxNTM1MzhaMBowGAYDVR0YBBEYDzIwMDkwNDI3MDUwMDAwWjAvAgJklhcN MDgwODExMjAwMzA4WjAaMBgGA1UdGAQRGA8yMDA4MDgxMTA1MDAwMFowLwICZJUX DTA5MDQxMDE2MjYyNVowGjAYBgNVHRgEERgPMjAwOTA0MTAwNTAwMDBaMCECAnIJ Fw0wODEyMDEyMjUzMjVaMAwwCgYDVR0VBAMKAQUwLwICcIQXDTA4MTExMjE1MTYx OVowGjAYBgNVHRgEERgPMjAwODExMTIwNjAwMDBaMBMCAnICFw0wOTAxMDkxOTEy MzRaMBMCAnIBFw0wOTAxMDkxOTEyMzRaMC8CAnT/Fw0wOTAxMDkxNDM0MjdaMBow GAYDVR0YBBEYDzIwMDkwMTA5MDYwMDAwWjATAgJ5eRcNMDkwMzA2MTk1MTI4WjAT AgJ5eBcNMDkwMzA2MTk1MDUyWjATAgJ5dxcNMDkwMzA2MTk0OTA5WjATAgJ5dhcN MDkwMzA2MTk0OTU1WjATAgJ5dRcNMDkwMzA2MTk0ODIwWjATAgJ5dBcNMDkwMzA2 MTk0NTE0WjATAgJ5cxcNMDkwMzA2MTk0NzIyWjATAgJ5chcNMDkwMzA2MTk0NjE4 WjATAgJ5cRcNMDkwMzA2MTk0NDE2WjATAgJ5cBcNMDkwMzA2MTk0MjQ5WjAUAgMA hWYXDTA5MDcxMDE1MjI0NVowFAIDAIVkFw0wOTA3MTAxNTE5MDJaMCICAwCCZBcN MDkwNjA5MTU1MjQ1WjAMMAoGA1UdFQQDCgEBMBMCAmR3Fw0wODA5MjUxMzQ3NTla MDACAwCFWRcNMDkwNzIyMTg0MjE3WjAaMBgGA1UdGAQRGA8yMDA5MDcyMjA0MDAw MFowLwICdOIXDTA5MDEwOTE5MDU0MlowGjAYBgNVHRgEERgPMjAwOTAxMDkwNTAw MDBaMC8CAnxXFw0wOTA0MDMxODA3MzVaMBowGAYDVR0YBBEYDzIwMDkwNDAzMDUw MDAwWjAiAgMAgNMXDTA5MDUxODIxMDEyN1owDDAKBgNVHRUEAwoBBTAUAgMAg80X DTA5MDYyMjE5NDUyNVowLwICcFgXDTA4MTExMTIwMTA1MFowGjAYBgNVHRgEERgP MjAwODExMTEwNjAwMDBaMC8CAmRfFw0wODA4MDcxNTE3MTRaMBowGAYDVR0YBBEY DzIwMDgwODA3MDUwMDAwWjAvAgJl2RcNMDkwMTI0MTY0ODU3WjAaMBgGA1UdGAQR GA8yMDA5MDEyNDA1MDAwMFowLwICd80XDTA5MDIxMjIyMjY0NFowGjAYBgNVHRgE ERgPMjAwOTAyMTIwNTAwMDBaMDsCAnfGFw0wOTAyMTIxNzUzMDlaMCYwCgYDVR0V BAMKAQQwGAYDVR0YBBEYDzIwMDkwMjEyMDYwMDAwWjAvAgJnShcNMDgxMTE3MTcz NzIyWjAaMBgGA1UdGAQRGA8yMDA4MTExNzA2MDAwMFowPAIDAII3Fw0wOTA2MTkx OTE4MDdaMCYwCgYDVR0VBAMKAQEwGAYDVR0YBBEYDzIwMDkwNjE5MDQwMDAwWjAU AgMAg7UXDTA5MDYyMjEzMzc1MlowFAIDAIO0Fw0wOTA2MjIxMzM4MDdaMBQCAwCG rhcNMDkwNzMxMjAyNDUxWjA8AgMAhScXDTA5MDcwODIwMjgyNlowJjAKBgNVHRUE AwoBAzAYBgNVHRgEERgPMjAwOTA3MDgwNzAwMDBaoA8wDTALBgNVHRQEBAICCpQw DQYJKoZIhvcNAQEFBQADggEBAAojoY5/evh2vL1OC0aqZXQJC9+X3tkpgvdjndrs LZwj7kEYEw19mPDjcvQfx2LEJlh6i/ub8fsBzDIAoq9zeaPv39hWRX8hwWwJPNnF dPwnugu2YfnspwTAkIUzrWzNyKOYi8LCuK0VE7G9j4dk6n/zQfttPFCRSwgfSCYY Ghc1w7TfG+o2fAz6nCamVYF+p9lErCalnpXbEkYkLUpRU4ZKiwI+c8MJF0R4vCwQ 5yoBCAHznd0T2LWOh2rgcLALwLD6MAXLvuOXEyCSa9U/afeTuyWZo1/aqdfcAzSO ctQSl/0Jwuq6KFtARuNRkAbHSXHH3ZYj7xPfKy3vF9K39aY= -----END X509 CRL----- JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/globus_ca.signing_policy000066400000000000000000000002421241116057200305340ustar00rootroot00000000000000#TestCA1.signing_policy access_id_CA X509 '/O=Auto/OU=JGlobusTestCA/CN=CA' pos_rights globus CA:sign cond_subjects globus '"/*"' JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/invalidcert.pem000066400000000000000000000013611241116057200266510ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIB/zCCAWigAwIBAgIBADANBgkqhkiG9w0BAQUFADAwMQ0wCwYDVQQKEwRBdXRv MRIwEAYDVQQLEwlJbnZhbGlkQ0ExCzAJBgNVBAMTAkNBMB4XDTExMDMxNDE5NDky MVoXDTE2MDMxNDE5NDkzMVowOTENMAsGA1UEChMEQXV0bzESMBAGA1UECxMJSW52 YWxpZENBMRQwEgYDVQQDEwtqZ2xvYnVzLm9yZzCBnzANBgkqhkiG9w0BAQEFAAOB jQAwgYkCgYEApWvtl3+u8dn2r15/wQ2e4TUTcsCdE8VEHeponZjL6nQrEsCWFS62 LTngIACWCoG+w1veVnWmipjsld0nxeAL+1Qx+5erpol0z1rS3EgvwKbIHt2iZAD6 rz8aTaLoocYMtAMqUi2kY9PlXFIBKWA5F7GDry5A04wBY9Yr9xaHMVsCAwEAAaMg MB4wDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBLAwDQYJKoZIhvcNAQEFBQAD gYEABboxuPVoN+++6rZtaNSJRYK9LAcyMyhxuNz2IxOIsn7Pziem5CfPPdTdcoVy Rqcgz7nhPPP6eoPkGRl9uoixMR9ZcohYpt5OkZf0FKRD2zWm75ZtFwhxVziPBjEy OSUeEbgqXU5v/ug7AqNm2sdL2HjvsU9cGQnm3jcEq2/orng= -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/invalidkey.pem000066400000000000000000000015671241116057200265140ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQCla+2Xf67x2favXn/BDZ7hNRNywJ0TxUQd6midmMvqdCsSwJYV LrYtOeAgAJYKgb7DW95WdaaKmOyV3SfF4Av7VDH7l6umiXTPWtLcSC/Apsge3aJk APqvPxpNouihxgy0AypSLaRj0+VcUgEpYDkXsYOvLkDTjAFj1iv3FocxWwIDAQAB AoGAftaZr/90Wfdhwif4V0OlXlM/HU75Yi5ww2t4WdbODHCUkmVe7tEJWPY2lvM8 GMRRTCRGAA9n6n/FcEfJ9lyLciF2kHyUWKNVJlPCxgW/Atyp8QHOGEnxjeBWAgrC i9Pgam3cTcxTtluVCZBR8IuV+5aQRw/AqqBpS+Hm5fGJoSECQQD8aPhdEkhu8kyY sB3Yx6dcsg7BIghGFkrpIPKpLfodDsixxx/LPJ02JKYQOIXZr6hWoW8Es8VKfYQh yo7VeyfxAkEAp8Y7N0X15hGhVeYm4jBgwXMYC23xBaIelWE+e8q63Sw/EaHRuYHc ZLVe+jmRTiDxPBAtxXJo77GmntzdyQ4aCwJALM6tmEgQl7Fnq4tIIR2ANlJdkCds dJSsg6oXqbTBu7rOIdEJcdi2x8/Fswd1q2klZwuNW7ZWBZ02gZElvfv44QJAPohx S9HErGMH2kd1WLslZRUr8h6hRjM96Pmc23EdoxA51a2VyOnxJow/gU5xrUg0AeoZ 1U0mdaimbPHvrF+YLwJAA7b/Tfjo4gTva14o8GkEcDcvK0IWaHEBnL0duXLw3aIh J6hBpTHDu+IQ04gVXpzPXFywF65A6T5o8ccqOosyqA== -----END RSA PRIVATE KEY----- JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/invalidkeystore.properties000066400000000000000000000013171241116057200311750ustar00rootroot00000000000000# # Copyright 1999-2010 University of Chicago # # 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. # # Name of certificate file certificateFilename=classpath:/invalidcert.pem # Name of key file keyFilename=classpath:/invalidkey.pemJGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/mykeystore.properties000066400000000000000000000016251241116057200301760ustar00rootroot00000000000000# # Copyright 1999-2010 University of Chicago # # 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. # # Properties file as input to the keystore (PEMFilebasedKeystore) # Name of proxy file #proxyFilename=/Users/ranantha/work/sos/gitRepository/Globus-Security/integratioon-example/target/classes/proxy.pem # Name of certificate file certificateFilename=classpath:/usercert.pem # Name of key file keyFilename=classpath:/userkey.pem JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/mytruststore.properties000066400000000000000000000011611241116057200305620ustar00rootroot00000000000000# # Copyright 1999-2010 University of Chicago # # 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. # directory_list=classpath:/cacert.pemJGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/usercert.pem000066400000000000000000000013711241116057200262020ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICBjCCAW+gAwIBAgIBADANBgkqhkiG9w0BAQUFADA0MQ0wCwYDVQQKEwRBdXRv MRYwFAYDVQQLEw1KR2xvYnVzVGVzdENBMQswCQYDVQQDEwJDQTAeFw0xMTAzMTUw MTIzMzdaFw0xNjAzMTUwMTIzNDdaMDwxDTALBgNVBAoTBEF1dG8xFjAUBgNVBAsT DUpHbG9idXNUZXN0Q0ExEzARBgNVBAMTCmdsb2J1cy5vcmcwgZ8wDQYJKoZIhvcN AQEBBQADgY0AMIGJAoGBAI7a/QhZuFGUCvvznueSxdFaKlTxcAWG790jm56417qK 1tktcNmoX3mzuY0yu5vVQ/6Mk7NWHTnijGfjdONLF5ImTY9SsXzEFgPCcXZUgJ4R xkfl+PGLj/OBN4NCXYsF09W21DGa6d5ZCFS3hOjjGge+gQUHdP2gDh9hw0m2I/4t AgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgSwMA0GCSqGSIb3 DQEBBQUAA4GBACRaJHra+dtyb1h2k4tUa019+sPkFV1y5IPWIxRs+fKV7JQrd42W jrHPimRU8TJ/2b4aNCLXRTK2qHhbQ72+WKrH78aI2gYQK6AuDuy2WNNwPOnHg4uG vJaczITE2FsUqXr4AVOxFyJsnljXfx05zD0zHbNqg+qqtpLxFuO3McQy -----END CERTIFICATE----- JGlobus-JGlobus-Release-2.1.0/test-utils/src/main/resources/userkey.pem000066400000000000000000000015671241116057200260440ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQCO2v0IWbhRlAr7857nksXRWipU8XAFhu/dI5ueuNe6itbZLXDZ qF95s7mNMrub1UP+jJOzVh054oxn43TjSxeSJk2PUrF8xBYDwnF2VICeEcZH5fjx i4/zgTeDQl2LBdPVttQxmuneWQhUt4To4xoHvoEFB3T9oA4fYcNJtiP+LQIDAQAB AoGAdOw3/gWxHtQUyXL0tIUk89zgmPWjwmJXIKBsVtTjfQL2JntSylNNEcdQL4k+ lKVRKZ7VpQrukNokIUPB/+cOOogWFKGqGW3Tmi/3UvbnKWQZB9kanupC9HqxfS2O 5vhuWT3W20/B6/0P4Nkv4V6OHr4+hsn4LYbaBO4fCuRw8eECQQDuG//QZ8IGw+oE jQ4yKzPk082EUMra2JqHO3dArkWh+bFdvTMJWKDSOP1Al4MZDmQkFgfWMYVOUaUC qSolGoMHAkEAmZbK60CNJwS1bLadSi8UhXAccoVUmRybsGHf82yCju62mO1Vgxwz CCWZ7oFL6Qzpc95icdTm2znrxEyrXeUkKwJAdyeT0Jrbwb7wsO5VmE1+XpiPVBOK MBIM4nejqb6MIg5t79bqX1b2w7y5H0Wy2SsWeeh8a3fEmfjJdpdo+8BUqQJAQT3z 3rDiBOQUKST9dajAH9q6ys7mW8/yNp+s4RuD7jFq8VVH0NTmvJw0YkMcOtgYRvb9 fHtCwXc+NnmXBeCzVwJADEv5Y58PeUBZFSlGNNsWoFIdTN7J3yVpAtFFwgnG2xiA DZfEG6OzgkQ87eikamg4SspAvorUgKf3IgV9C4dgPg== -----END RSA PRIVATE KEY-----