id
stringlengths 27
31
| content
stringlengths 14
287k
| max_stars_repo_path
stringlengths 52
57
|
|---|---|---|
crossvul-java_data_good_5809_0
|
package org.jboss.seam.remoting;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jboss.seam.contexts.RemotingLifecycle;
import org.jboss.seam.core.ConversationPropagation;
import org.jboss.seam.core.Manager;
import org.jboss.seam.log.LogProvider;
import org.jboss.seam.log.Logging;
import org.jboss.seam.remoting.wrapper.Wrapper;
import org.jboss.seam.servlet.ContextualHttpServletRequest;
import org.jboss.seam.util.XML;
/**
* Unmarshals the calls from an HttpServletRequest, executes them in order and
* marshals the responses.
*
* @author Shane Bryzak
*/
public class ExecutionHandler extends BaseRequestHandler implements RequestHandler
{
private static final LogProvider log = Logging.getLogProvider(ExecutionHandler.class);
private static final byte[] HEADER_OPEN = "<header>".getBytes();
private static final byte[] HEADER_CLOSE = "</header>".getBytes();
private static final byte[] CONVERSATION_ID_TAG_OPEN = "<conversationId>".getBytes();
private static final byte[] CONVERSATION_ID_TAG_CLOSE = "</conversationId>".getBytes();
private static final byte[] CONTEXT_TAG_OPEN = "<context>".getBytes();
private static final byte[] CONTEXT_TAG_CLOSE = "</context>".getBytes();
/**
* The entry point for handling a request.
*
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws Exception
*/
public void handle(HttpServletRequest request, final HttpServletResponse response)
throws Exception
{
// We're sending an XML response, so set the response content type to text/xml
response.setContentType("text/xml");
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int read = request.getInputStream().read(buffer);
while (read != -1)
{
out.write(buffer, 0, read);
read = request.getInputStream().read(buffer);
}
String requestData = new String(out.toByteArray());
log.debug("Processing remote request: " + requestData);
// Parse the incoming request as XML
SAXReader xmlReader = XML.getSafeSaxReader();
Document doc = xmlReader.read( new StringReader(requestData) );
final Element env = doc.getRootElement();
final RequestContext ctx = unmarshalContext(env);
// TODO - we really want to extract the page context from our request
RemotingLifecycle.restorePageContext();
new ContextualHttpServletRequest(request)
{
@Override
public void process() throws Exception
{
// Extract the calls from the request
List<Call> calls = unmarshalCalls(env);
// Execute each of the calls
for (Call call : calls)
{
call.execute();
}
// Store the conversation ID in the outgoing context
ctx.setConversationId( Manager.instance().getCurrentConversationId() );
// Package up the response
marshalResponse(calls, ctx, response.getOutputStream());
}
@Override
protected void restoreConversationId()
{
ConversationPropagation.instance().setConversationId( ctx.getConversationId() );
}
@Override
protected void handleConversationPropagation() {}
}.run();
}
/**
* Unmarshals the context from the request envelope header.
*
* @param env Element
* @return RequestContext
*/
private RequestContext unmarshalContext(Element env)
{
RequestContext ctx = new RequestContext();
Element header = env.element("header");
if (header != null)
{
Element context = header.element("context");
if (context != null)
{
Element convId = context.element("conversationId");
if (convId != null)
{
ctx.setConversationId(convId.getText());
}
}
}
return ctx;
}
/**
* Unmarshal the request into a list of Calls.
*
* @param env Element
* @throws Exception
*/
private List<Call> unmarshalCalls(Element env) throws Exception
{
try
{
List<Call> calls = new ArrayList<Call>();
List<Element> callElements = env.element("body").elements("call");
for (Element e : callElements)
{
Call call = new Call(e.attributeValue("id"),
e.attributeValue("component"),
e.attributeValue("method"));
// First reconstruct all the references
Element refsNode = e.element("refs");
Iterator iter = refsNode.elementIterator("ref");
while (iter.hasNext())
{
call.getContext().createWrapperFromElement((Element) iter.next());
}
// Now unmarshal the ref values
for (Wrapper w : call.getContext().getInRefs().values())
{
w.unmarshal();
}
Element paramsNode = e.element("params");
// Then process the param values
iter = paramsNode.elementIterator("param");
while (iter.hasNext())
{
Element param = (Element) iter.next();
call.addParameter(call.getContext().createWrapperFromElement(
(Element) param.elementIterator().next()));
}
calls.add(call);
}
return calls;
}
catch (Exception ex)
{
log.error("Error unmarshalling calls from request", ex);
throw ex;
}
}
/**
* Write the results to the output stream.
*
* @param calls List The list of calls to write
* @param out OutputStream The stream to write to
* @throws IOException
*/
private void marshalResponse(List<Call> calls, RequestContext ctx, OutputStream out)
throws IOException
{
out.write(ENVELOPE_TAG_OPEN);
if (ctx.getConversationId() != null)
{
out.write(HEADER_OPEN);
out.write(CONTEXT_TAG_OPEN);
out.write(CONVERSATION_ID_TAG_OPEN);
out.write(ctx.getConversationId().getBytes());
out.write(CONVERSATION_ID_TAG_CLOSE);
out.write(CONTEXT_TAG_CLOSE);
out.write(HEADER_CLOSE);
}
out.write(BODY_TAG_OPEN);
for (Call call : calls)
{
MarshalUtils.marshalResult(call, out);
}
out.write(BODY_TAG_CLOSE);
out.write(ENVELOPE_TAG_CLOSE);
out.flush();
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_5809_0
|
crossvul-java_data_good_3055_1
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.
*/
package hudson.search;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import hudson.model.FreeStyleProject;
import hudson.model.ListView;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import hudson.model.User;
import hudson.model.View;
import hudson.security.ACL;
import hudson.security.AuthorizationStrategy;
import hudson.security.GlobalMatrixAuthorizationStrategy;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.MockFolder;
import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
/**
* @author Kohsuke Kawaguchi
*/
public class SearchTest {
@Rule public JenkinsRule j = new JenkinsRule();
/**
* No exact match should result in a failure status code.
*/
@Test
public void testFailure() throws Exception {
try {
j.search("no-such-thing");
fail("404 expected");
} catch (FailingHttpStatusCodeException e) {
assertEquals(404,e.getResponse().getStatusCode());
}
}
/**
* Makes sure the script doesn't execute.
*/
@Issue("JENKINS-3415")
@Test
public void testXSS() throws Exception {
try {
WebClient wc = j.createWebClient();
wc.setAlertHandler(new AlertHandler() {
public void handleAlert(Page page, String message) {
throw new AssertionError();
}
});
wc.search("<script>alert('script');</script>");
fail("404 expected");
} catch (FailingHttpStatusCodeException e) {
assertEquals(404,e.getResponse().getStatusCode());
}
}
@Test
public void testSearchByProjectName() throws Exception {
final String projectName = "testSearchByProjectName";
j.createFreeStyleProject(projectName);
Page result = j.search(projectName);
assertNotNull(result);
j.assertGoodStatus(result);
// make sure we've fetched the testSearchByDisplayName project page
String contents = result.getWebResponse().getContentAsString();
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", projectName)));
}
@Issue("JENKINS-24433")
@Test
public void testSearchByProjectNameBehindAFolder() throws Exception {
FreeStyleProject myFreeStyleProject = j.createFreeStyleProject("testSearchByProjectName");
MockFolder myMockFolder = j.createFolder("my-folder-1");
Page result = j.createWebClient().goTo(myMockFolder.getUrl() + "search?q="+ myFreeStyleProject.getName());
assertNotNull(result);
j.assertGoodStatus(result);
URL resultUrl = result.getUrl();
assertTrue(resultUrl.toString().equals(j.getInstance().getRootUrl() + myFreeStyleProject.getUrl()));
}
@Issue("JENKINS-24433")
@Test
public void testSearchByProjectNameInAFolder() throws Exception {
MockFolder myMockFolder = j.createFolder("my-folder-1");
FreeStyleProject myFreeStyleProject = myMockFolder.createProject(FreeStyleProject.class, "my-job-1");
Page result = j.createWebClient().goTo(myMockFolder.getUrl() + "search?q=" + myFreeStyleProject.getFullName());
assertNotNull(result);
j.assertGoodStatus(result);
URL resultUrl = result.getUrl();
assertTrue(resultUrl.toString().equals(j.getInstance().getRootUrl() + myFreeStyleProject.getUrl()));
}
@Test
public void testSearchByDisplayName() throws Exception {
final String displayName = "displayName9999999";
FreeStyleProject project = j.createFreeStyleProject("testSearchByDisplayName");
project.setDisplayName(displayName);
Page result = j.search(displayName);
assertNotNull(result);
j.assertGoodStatus(result);
// make sure we've fetched the testSearchByDisplayName project page
String contents = result.getWebResponse().getContentAsString();
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", displayName)));
}
@Test
public void testSearch2ProjectsWithSameDisplayName() throws Exception {
// create 2 freestyle projects with the same display name
final String projectName1 = "projectName1";
final String projectName2 = "projectName2";
final String projectName3 = "projectName3";
final String displayName = "displayNameFoo";
final String otherDisplayName = "otherDisplayName";
FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
project1.setDisplayName(displayName);
FreeStyleProject project2 = j.createFreeStyleProject(projectName2);
project2.setDisplayName(displayName);
FreeStyleProject project3 = j.createFreeStyleProject(projectName3);
project3.setDisplayName(otherDisplayName);
// make sure that on search we get back one of the projects, it doesn't
// matter which one as long as the one that is returned has displayName
// as the display name
Page result = j.search(displayName);
assertNotNull(result);
j.assertGoodStatus(result);
// make sure we've fetched the testSearchByDisplayName project page
String contents = result.getWebResponse().getContentAsString();
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", displayName)));
assertFalse(contents.contains(otherDisplayName));
}
@Test
public void testProjectNamePrecedesDisplayName() throws Exception {
final String project1Name = "foo";
final String project1DisplayName = "project1DisplayName";
final String project2Name = "project2Name";
final String project2DisplayName = project1Name;
final String project3Name = "project3Name";
final String project3DisplayName = "project3DisplayName";
// create 1 freestyle project with the name foo
FreeStyleProject project1 = j.createFreeStyleProject(project1Name);
project1.setDisplayName(project1DisplayName);
// create another with the display name foo
FreeStyleProject project2 = j.createFreeStyleProject(project2Name);
project2.setDisplayName(project2DisplayName);
// create a third project and make sure it's not picked up by search
FreeStyleProject project3 = j.createFreeStyleProject(project3Name);
project3.setDisplayName(project3DisplayName);
// search for foo
Page result = j.search(project1Name);
assertNotNull(result);
j.assertGoodStatus(result);
// make sure we get the project with the name foo
String contents = result.getWebResponse().getContentAsString();
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", project1DisplayName)));
// make sure projects 2 and 3 were not picked up
assertFalse(contents.contains(project2Name));
assertFalse(contents.contains(project3Name));
assertFalse(contents.contains(project3DisplayName));
}
@Test
public void testGetSuggestionsHasBothNamesAndDisplayNames() throws Exception {
final String projectName = "project name";
final String displayName = "display name";
FreeStyleProject project1 = j.createFreeStyleProject(projectName);
project1.setDisplayName(displayName);
WebClient wc = j.createWebClient();
Page result = wc.goTo("search/suggest?query=name", "application/json");
assertNotNull(result);
j.assertGoodStatus(result);
String content = result.getWebResponse().getContentAsString();
System.out.println(content);
JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
assertNotNull(jsonContent);
JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
assertNotNull(jsonArray);
assertEquals(2, jsonArray.size());
boolean foundProjectName = false;
boolean foundDispayName = false;
for(Object suggestion : jsonArray) {
JSONObject jsonSuggestion = (JSONObject)suggestion;
String name = (String)jsonSuggestion.get("name");
if(projectName.equals(name)) {
foundProjectName = true;
}
else if(displayName.equals(name)) {
foundDispayName = true;
}
}
assertTrue(foundProjectName);
assertTrue(foundDispayName);
}
@Issue("JENKINS-24433")
@Test
public void testProjectNameBehindAFolderDisplayName() throws Exception {
final String projectName1 = "job-1";
final String displayName1 = "job-1 display";
final String projectName2 = "job-2";
final String displayName2 = "job-2 display";
FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
project1.setDisplayName(displayName1);
MockFolder myMockFolder = j.createFolder("my-folder-1");
FreeStyleProject project2 = myMockFolder.createProject(FreeStyleProject.class, projectName2);
project2.setDisplayName(displayName2);
WebClient wc = j.createWebClient();
Page result = wc.goTo(myMockFolder.getUrl() + "search/suggest?query=" + projectName1, "application/json");
assertNotNull(result);
j.assertGoodStatus(result);
String content = result.getWebResponse().getContentAsString();
JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
assertNotNull(jsonContent);
JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
assertNotNull(jsonArray);
assertEquals(2, jsonArray.size());
boolean foundDisplayName = false;
for(Object suggestion : jsonArray) {
JSONObject jsonSuggestion = (JSONObject)suggestion;
String name = (String)jsonSuggestion.get("name");
if(projectName1.equals(name)) {
foundDisplayName = true;
}
}
assertTrue(foundDisplayName);
}
@Issue("JENKINS-24433")
@Test
public void testProjectNameInAFolderDisplayName() throws Exception {
final String projectName1 = "job-1";
final String displayName1 = "job-1 display";
final String projectName2 = "job-2";
final String displayName2 = "my-folder-1 job-2";
FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
project1.setDisplayName(displayName1);
MockFolder myMockFolder = j.createFolder("my-folder-1");
FreeStyleProject project2 = myMockFolder.createProject(FreeStyleProject.class, projectName2);
project2.setDisplayName(displayName2);
WebClient wc = j.createWebClient();
Page result = wc.goTo(myMockFolder.getUrl() + "search/suggest?query=" + projectName2, "application/json");
assertNotNull(result);
j.assertGoodStatus(result);
String content = result.getWebResponse().getContentAsString();
JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
assertNotNull(jsonContent);
JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
assertNotNull(jsonArray);
assertEquals(1, jsonArray.size());
boolean foundDisplayName = false;
for(Object suggestion : jsonArray) {
JSONObject jsonSuggestion = (JSONObject)suggestion;
String name = (String)jsonSuggestion.get("name");
if(displayName2.equals(name)) {
foundDisplayName = true;
}
}
assertTrue(foundDisplayName);
}
/**
* Disable/enable status shouldn't affect the search
*/
@Issue("JENKINS-13148")
@Test
public void testDisabledJobShouldBeSearchable() throws Exception {
FreeStyleProject p = j.createFreeStyleProject("foo-bar");
assertTrue(suggest(j.jenkins.getSearchIndex(), "foo").contains(p));
p.disable();
assertTrue(suggest(j.jenkins.getSearchIndex(), "foo").contains(p));
}
/**
* All top-level jobs should be searchable, not just jobs in the current view.
*/
@Issue("JENKINS-13148")
@Test
public void testCompletionOutsideView() throws Exception {
FreeStyleProject p = j.createFreeStyleProject("foo-bar");
ListView v = new ListView("empty1",j.jenkins);
ListView w = new ListView("empty2",j.jenkins);
j.jenkins.addView(v);
j.jenkins.addView(w);
j.jenkins.setPrimaryView(w);
// new view should be empty
assertFalse(v.contains(p));
assertFalse(w.contains(p));
assertFalse(j.jenkins.getPrimaryView().contains(p));
assertTrue(suggest(j.jenkins.getSearchIndex(),"foo").contains(p));
}
@Issue("SECURITY-385")
@Test
public void testInaccessibleViews() throws IOException {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
GlobalMatrixAuthorizationStrategy strategy = new GlobalMatrixAuthorizationStrategy();
strategy.add(Jenkins.READ, "alice");
j.jenkins.setAuthorizationStrategy(strategy);
j.jenkins.addView(new ListView("foo", j.jenkins));
// SYSTEM can see all the views
assertEquals("two views exist", 2, Jenkins.getInstance().getViews().size());
List<SearchItem> results = new ArrayList<>();
j.jenkins.getSearchIndex().suggest("foo", results);
assertEquals("nonempty results list", 1, results.size());
// Alice can't
assertFalse("no permission", j.jenkins.getView("foo").getACL().hasPermission(User.get("alice").impersonate(), View.READ));
ACL.impersonate(User.get("alice").impersonate(), new Runnable() {
@Override
public void run() {
assertEquals("no visible views", 0, Jenkins.getInstance().getViews().size());
List<SearchItem> results = new ArrayList<>();
j.jenkins.getSearchIndex().suggest("foo", results);
assertEquals("empty results list", Collections.emptyList(), results);
}
});
}
@Test
public void testSearchWithinFolders() throws Exception {
MockFolder folder1 = j.createFolder("folder1");
FreeStyleProject p1 = folder1.createProject(FreeStyleProject.class, "myjob");
MockFolder folder2 = j.createFolder("folder2");
FreeStyleProject p2 = folder2.createProject(FreeStyleProject.class, "myjob");
List<SearchItem> suggest = suggest(j.jenkins.getSearchIndex(), "myjob");
assertTrue(suggest.contains(p1));
assertTrue(suggest.contains(p2));
}
private List<SearchItem> suggest(SearchIndex index, String term) {
List<SearchItem> result = new ArrayList<SearchItem>();
index.suggest(term, result);
return result;
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_3055_1
|
crossvul-java_data_good_3053_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* 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.
*/
package jenkins.model;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.Lookup;
import hudson.Main;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import jenkins.util.SystemProperties;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.init.TermMilestone;
import hudson.init.TerminatorFinder;
import hudson.lifecycle.Lifecycle;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.logging.LogRecorderManager;
import hudson.markup.EscapedMarkupFormatter;
import hudson.markup.MarkupFormatter;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.LoadStatistics;
import hudson.model.ManagementLink;
import hudson.model.Messages;
import hudson.model.ModifiableViewGroup;
import hudson.model.NoFingerprintMatch;
import hudson.model.Node;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.FederatedLoginService;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.NamingThreadFactory;
import hudson.util.PluginServletFilter;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import java.util.Objects;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.install.InstallState;
import jenkins.install.InstallUtil;
import jenkins.install.SetupWizard;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.JenkinsJVM;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import jenkins.util.xml.XMLUtils;
import net.jcip.annotations.GuardedBy;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Milestone;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.ReactorListener;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static hudson.Util.*;
import static hudson.init.InitMilestone.*;
import hudson.init.Initializer;
import hudson.util.LogTaskListener;
import static java.util.logging.Level.*;
import static javax.servlet.http.HttpServletResponse.*;
import org.kohsuke.stapler.WebMethod;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Jenkins whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* The Jenkins instance startup type i.e. NEW, UPGRADE etc
*/
private transient InstallState installState = InstallState.UNKNOWN;
/**
* If we're in the process of an initial setup,
* this will be set
*/
private transient SetupWizard setupWizard;
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Jenkins.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Jenkins.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
@GuardedBy("Jenkins.class")
private transient boolean cleanUpStarted;
private volatile List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Jenkins system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Legacy store of the set of installed cluster nodes.
* @deprecated in favour of {@link Nodes}
*/
@Deprecated
protected transient volatile NodeList slaves;
/**
* The holder of the set of installed cluster nodes.
*
* @since 1.607
*/
private transient final Nodes nodes = new Nodes(this);
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient final Object tcpSlaveAgentListenerLock = new Object();
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort = SystemProperties.getInteger(Jenkins.class.getName()+".slaveAgentPort",0);
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and agents.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* agents and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Jenkins.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
@CheckForNull Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public @CheckForNull Jenkins getInstance() {
return theInstance;
}
};
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstanceOrNull()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
* @deprecated use {@link #getInstance()}
*/
@Deprecated
@Nonnull
public static Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Gets the {@link Jenkins} singleton.
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
* @since 1.653
*/
@CheckForNull
public static Jenkins getInstanceOrNull() {
return HOLDER.getInstance();
}
/**
* Gets the {@link Jenkins} singleton. In certain rare cases you may have code that is intended to run before
* Jenkins starts or while Jenkins is being shut-down. For those rare cases use {@link #getInstanceOrNull()}.
* In other cases you may have code that might end up running on a remote JVM and not on the Jenkins master,
* for those cases you really should rewrite your code so that when the {@link Callable} is sent over the remoting
* channel it uses a {@code writeReplace} method or similar to ensure that the {@link Jenkins} class is not being
* loaded into the remote class loader
* @return The instance.
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
*/
@CLIResolver
@Nonnull
public static Jenkins getInstance() {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
if(SystemProperties.getBoolean(Jenkins.class.getName()+".enableExceptionOnNullInstance")) {
// TODO: remove that second block around 2.20 (that is: ~20 versions to battle test it)
// See https://github.com/jenkinsci/jenkins/pull/2297#issuecomment-216710150
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
}
return instance;
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = UpdateCenter.createUpdateCenter(null);
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
private transient final boolean oldJenkinsJVM;
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root, context, null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
oldJenkinsJVM = JenkinsJVM.isJenkinsJVM(); // capture to restore in cleanUp()
JenkinsJVMAccess._setJenkinsJVM(true); // set it for unit tests as they will not have gone through WebAppMain
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with agents
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = PluginManager.createDefault(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
setupWizard = new SetupWizard();
InstallUtil.proceedToNextStateFrom(InstallState.UNKNOWN);
launchTcpSlaveAgentListener();
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c, new LogTaskListener(LOGGER, INFO));
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Maintains backwards compatibility. Invoked by XStream when this object is de-serialized.
*/
@SuppressWarnings({"unused"})
private Object readResolve() {
if (jdks == null) {
jdks = new ArrayList<>();
}
return this;
}
/**
* Get the Jenkins {@link jenkins.install.InstallState install state}.
* @return The Jenkins {@link jenkins.install.InstallState install state}.
*/
@Nonnull
@Restricted(NoExternalUse.class)
public InstallState getInstallState() {
if (installState == null || installState.name() == null) {
return InstallState.UNKNOWN;
}
return installState;
}
/**
* Update the current install state. This will invoke state.initializeState()
* when the state has been transitioned.
*/
@Restricted(NoExternalUse.class)
public void setInstallState(@Nonnull InstallState newState) {
InstallState prior = installState;
installState = newState;
if (!prior.equals(newState)) {
newState.initializeState();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
if (milestone==PLUGINS_PREPARED) {
// set up Guice to enable injection as early as possible
// before this milestone, ExtensionList.ensureLoaded() won't actually try to locate instances
ExtensionList.lookup(ExtensionFinder.class).getComponents();
}
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
launchTcpSlaveAgentListener();
}
private void launchTcpSlaveAgentListener() throws IOException {
synchronized(tcpSlaveAgentListenerLock) {
// shutdown previous agent if the port has changed
if (tcpSlaveAgentListener != null && tcpSlaveAgentListener.configuredPort != slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
}
if (slaveAgentPort != -1 && tcpSlaveAgentListener == null) {
String administrativeMonitorId = getClass().getName() + ".tcpBind";
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
// remove previous monitor in case of previous error
for (Iterator<AdministrativeMonitor> it = AdministrativeMonitor.all().iterator(); it.hasNext(); ) {
AdministrativeMonitor am = it.next();
if (administrativeMonitorId.equals(am.id)) {
it.remove();
}
}
} catch (BindException e) {
LOGGER.log(Level.WARNING, String.format("Failed to listen to incoming agent connections through JNLP port %s. Change the JNLP port number", slaveAgentPort), e);
new AdministrativeError(administrativeMonitorId,
"Failed to listen to incoming agent connections through JNLP",
"Failed to listen to incoming agent connections through JNLP. <a href='configureSecurity'>Change the JNLP port number</a> to solve the problem.", e);
}
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
@Deprecated
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
@Deprecated
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName, SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
@Deprecated
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Jenkins by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName, SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/** @deprecated Use {@link SCMListener#all} instead. */
@Deprecated
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public @Nonnull MarkupFormatter getMarkupFormatter() {
MarkupFormatter f = markupFormatter;
return f != null ? f : new EscapedMarkupFormatter();
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Jenkins.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(), Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
/**
* Completely replaces views.
*
* <p>
* This operation is NOT provided as an atomic operation, but rather
* the sole purpose of this is to define a setter for this to help
* introspecting code, such as system-config-dsl plugin
*/
// even if we want to offer this atomic operation, CopyOnWriteArrayList
// offers no such operation
public void setViews(Collection<View> views) throws IOException {
BulkChange bc = new BulkChange(this);
try {
this.views.clear();
for (View v : views) {
addView(v);
}
} finally {
bc.commit();
}
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view, oldName, newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Jenkins.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Jenkins forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
@Override public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return lhs.getName().compareTo(rhs.getName());
}
});
return r;
}
@CLIResolver
public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public List<JDK> getJDKs() {
return jdks;
}
/**
* Replaces all JDK installations with those from the given collection.
*
* Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to
* set JDK installations from external code.
*/
@Restricted(NoExternalUse.class)
public void setJDKs(Collection<? extends JDK> jdks) {
this.jdks = new ArrayList<JDK>(jdks);
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the agent node of the give name, hooked under this Jenkins.
*/
public @CheckForNull Node getNode(String name) {
return nodes.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return nodes.getNodes();
}
/**
* Get the {@link Nodes} object that handles maintaining individual {@link Node}s.
* @return The Nodes object.
*/
@Restricted(NoExternalUse.class)
public Nodes getNodesObject() {
// TODO replace this with something better when we properly expose Nodes.
return nodes;
}
/**
* Adds one more {@link Node} to Jenkins.
*/
public void addNode(Node n) throws IOException {
nodes.addNode(n);
}
/**
* Removes a {@link Node} from Jenkins.
*/
public void removeNode(@Nonnull Node n) throws IOException {
nodes.removeNode(n);
}
/**
* Saves an existing {@link Node} on disk, called by {@link Node#save()}. This method is preferred in those cases
* where you need to determine atomically that the node being saved is actually in the list of nodes.
*
* @param n the node to be updated.
* @return {@code true}, if the node was updated. {@code false}, if the node was not in the list of nodes.
* @throws IOException if the node could not be persisted.
* @see Nodes#updateNode
* @since 1.634
*/
public boolean updateNode(Node n) throws IOException {
return nodes.updateNode(n);
}
public void setNodes(final List<? extends Node> n) throws IOException {
nodes.setNodes(n);
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
/*package*/ void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
// do essentially what expandVariablesForDirectory does, without an Item
String replacedValue = expandVariablesForDirectory(value,
"doCheckRawBuildsDir-Marker:foo",
Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo");
File replacedFile = new File(replacedValue);
if (!replacedFile.isAbsolute()) {
return FormValidation.error(value + " does not resolve to an absolute path");
}
if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) {
return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects");
}
if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) {
// make sure platform can handle colon
try {
File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar");
tmp.delete();
} catch (IOException e) {
return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead");
}
}
File d = new File(replacedValue);
if (!d.isDirectory()) {
// if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to
d = d.getParentFile();
while (!d.exists()) {
d = d.getParentFile();
}
if (!d.canWrite()) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
}
return FormValidation.ok();
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}.
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link #getRootUrlFromRequest}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /}
* @since 1.66
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public @Nullable String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}.
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* <p>Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy which has not been fully configured.
* Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set.
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a>
* shows some examples of configuration.
* @since 1.263
*/
public @Nonnull String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
int index = host.indexOf(':');
int port = req.getServerPort();
if (index == -1) {
// Almost everyone else except Nginx put the host and port in separate headers
buf.append(host);
} else {
// Nginx uses the same spec as for the Host header, i.e. hostanme:port
buf.append(host.substring(0, index));
if (index + 1 < host.length()) {
try {
port = Integer.parseInt(host.substring(index + 1));
} catch (NumberFormatException e) {
// ignore
}
}
// but if a user has configured Nginx with an X-Forwarded-Port, that will win out.
}
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath()));
}
@Restricted(NoExternalUse.class)
static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) {
return Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(),
"ITEM_ROOTDIR", itemRootDir,
"ITEM_FULLNAME", itemFullName, // legacy, deprecated
"ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
@Restricted(NoExternalUse.class)
public void setRawBuildsDir(String buildsDir) {
this.buildsDir = buildsDir;
}
@Override public @Nonnull FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new MasterToSlaveCallable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Jenkins would have to have crumb in it to protect
* Jenkins from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes in Jenkins.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
IdStrategy oldUserIdStrategy = this.securityRealm == null
? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load
: this.securityRealm.getUserIdStrategy();
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) {
User.rekey();
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
* @see ExtensionList#lookup
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Jenkins is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
if (this.numExecutors != n) {
this.numExecutors = n;
updateComputerList();
save();
}
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override public TopLevelItem getItem(String name) throws AccessDeniedException {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
* @throws AccessDeniedException as per {@link ItemGroup#getItem}
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean), {@link User#getById(String, boolean)}
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Jenkins by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(job, oldName, newName);
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
}
@Override public boolean canAdd(TopLevelItem item) {
return true;
}
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
items.put(name, item);
return item;
}
@Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException {
items.remove(item.getName());
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private void loadConfig() throws IOException {
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles();
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
loadConfig();
// if we are loading old data that doesn't have this field
if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) {
nodes.setNodes(slaves);
slaves = null;
} else {
nodes.load();
}
clouds.setOwner(Jenkins.this);
}
});
for (final File subdir : subdirs) {
g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
if(!Items.getConfigFile(subdir).exists()) {
//Does not have job config file, so it is not a jenkins job hence skip it
return;
}
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : nodes.getNodes())
// Note that not all labels are visible until the agents have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Jenkins and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
if (theInstance != this && theInstance != null) {
LOGGER.log(Level.WARNING, "This instance is no longer the singleton, ignoring cleanUp()");
return;
}
synchronized (Jenkins.class) {
if (cleanUpStarted) {
LOGGER.log(Level.WARNING, "Jenkins.cleanUp() already started, ignoring repeated cleanUp()");
return;
}
cleanUpStarted = true;
}
try {
LOGGER.log(Level.INFO, "Stopping Jenkins");
final List<Throwable> errors = new ArrayList<>();
fireBeforeShutdown(errors);
_cleanUpRunTerminators(errors);
terminating = true;
final Set<Future<?>> pending = _cleanUpDisconnectComputers(errors);
_cleanUpShutdownUDPBroadcast(errors);
_cleanUpCloseDNSMulticast(errors);
_cleanUpInterruptReloadThread(errors);
_cleanUpShutdownTriggers(errors);
_cleanUpShutdownTimer(errors);
_cleanUpShutdownTcpSlaveAgent(errors);
_cleanUpShutdownPluginManager(errors);
_cleanUpPersistQueue(errors);
_cleanUpShutdownThreadPoolForLoad(errors);
_cleanUpAwaitDisconnects(errors, pending);
_cleanUpPluginServletFilters(errors);
_cleanUpReleaseAllLoggers(errors);
LOGGER.log(Level.INFO, "Jenkins stopped");
if (!errors.isEmpty()) {
StringBuilder message = new StringBuilder("Unexpected issues encountered during cleanUp: ");
Iterator<Throwable> iterator = errors.iterator();
message.append(iterator.next().getMessage());
while (iterator.hasNext()) {
message.append("; ");
message.append(iterator.next().getMessage());
}
iterator = errors.iterator();
RuntimeException exception = new RuntimeException(message.toString(), iterator.next());
while (iterator.hasNext()) {
exception.addSuppressed(iterator.next());
}
throw exception;
}
} finally {
theInstance = null;
if (JenkinsJVM.isJenkinsJVM()) {
JenkinsJVMAccess._setJenkinsJVM(oldJenkinsJVM);
}
}
}
private void fireBeforeShutdown(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Notifying termination");
for (ItemListener l : ItemListener.all()) {
try {
l.onBeforeShutdown();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(Level.WARNING, "ItemListener " + l + ": " + e.getMessage(), e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "ItemListener " + l + ": " + e.getMessage(), e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpRunTerminators(List<Throwable> errors) {
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
}, new ReactorListener() {
final Level level = Level.parse(Configuration.getStringConfigParameter("termLogLevel", "FINE"));
public void onTaskStarted(Task t) {
LOGGER.log(level, "Started " + t.getDisplayName());
}
public void onTaskCompleted(Task t) {
LOGGER.log(level, "Completed " + t.getDisplayName());
}
public void onTaskFailed(Task t, Throwable err, boolean fatal) {
LOGGER.log(SEVERE, "Failed " + t.getDisplayName(), err);
}
public void onAttained(Milestone milestone) {
Level lv = level;
String s = "Attained " + milestone.toString();
if (milestone instanceof TermMilestone) {
lv = Level.INFO; // noteworthy milestones --- at least while we debug problems further
s = milestone.toString();
}
LOGGER.log(lv, s);
}
});
} catch (InterruptedException | ReactorException | IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
errors.add(e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to execute termination", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to execute termination", e);
// save for later
errors.add(e);
}
}
private Set<Future<?>> _cleanUpDisconnectComputers(final List<Throwable> errors) {
LOGGER.log(Level.INFO, "Starting node disconnection");
final Set<Future<?>> pending = new HashSet<Future<?>>();
// JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Computer c : computers.values() ) {
try {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(Level.WARNING, "Could not disconnect " + c + ": " + e.getMessage(), e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Could not disconnect " + c + ": " + e.getMessage(), e);
// save for later
errors.add(e);
}
}
}
});
return pending;
}
private void _cleanUpShutdownUDPBroadcast(List<Throwable> errors) {
if(udpBroadcastThread!=null) {
LOGGER.log(Level.FINE, "Shutting down {0}", udpBroadcastThread.getName());
try {
udpBroadcastThread.shutdown();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shutdown UDP Broadcast Thread", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shutdown UDP Broadcast Thread", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpCloseDNSMulticast(List<Throwable> errors) {
if(dnsMultiCast!=null) {
LOGGER.log(Level.FINE, "Closing DNS Multicast service");
try {
dnsMultiCast.close();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpInterruptReloadThread(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Interrupting reload thread");
try {
interruptReloadThread();
} catch (SecurityException e) {
LOGGER.log(WARNING, "Not permitted to interrupt reload thread", e);
errors.add(e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to interrupt reload thread", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to interrupt reload thread", e);
// save for later
errors.add(e);
}
}
private void _cleanUpShutdownTriggers(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Shutting down triggers");
try {
final java.util.Timer timer = Trigger.timer;
if (timer != null) {
final CountDownLatch latch = new CountDownLatch(1);
timer.schedule(new TimerTask() {
@Override
public void run() {
timer.cancel();
latch.countDown();
}
}, 0);
if (latch.await(10, TimeUnit.SECONDS)) {
LOGGER.log(Level.FINE, "Triggers shut down successfully");
} else {
timer.cancel();
LOGGER.log(Level.INFO, "Gave up waiting for triggers to finish running");
}
}
Trigger.timer = null;
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shut down triggers", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shut down triggers", e);
// save for later
errors.add(e);
}
}
private void _cleanUpShutdownTimer(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Shutting down timer");
try {
Timer.shutdown();
} catch (SecurityException e) {
LOGGER.log(WARNING, "Not permitted to shut down Timer", e);
errors.add(e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shut down Timer", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shut down Timer", e);
// save for later
errors.add(e);
}
}
private void _cleanUpShutdownTcpSlaveAgent(List<Throwable> errors) {
if(tcpSlaveAgentListener!=null) {
LOGGER.log(FINE, "Shutting down TCP/IP slave agent listener");
try {
tcpSlaveAgentListener.shutdown();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shut down TCP/IP slave agent listener", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shut down TCP/IP slave agent listener", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpShutdownPluginManager(List<Throwable> errors) {
if(pluginManager!=null) {// be defensive. there could be some ugly timing related issues
LOGGER.log(Level.INFO, "Stopping plugin manager");
try {
pluginManager.stop();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to stop plugin manager", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to stop plugin manager", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpPersistQueue(List<Throwable> errors) {
if(getRootDir().exists()) {
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
LOGGER.log(Level.INFO, "Persisting build queue");
try {
getQueue().save();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to persist build queue", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to persist build queue", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpShutdownThreadPoolForLoad(List<Throwable> errors) {
LOGGER.log(FINE, "Shuting down Jenkins load thread pool");
try {
threadPoolForLoad.shutdown();
} catch (SecurityException e) {
LOGGER.log(WARNING, "Not permitted to shut down Jenkins load thread pool", e);
errors.add(e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shut down Jenkins load thread pool", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shut down Jenkins load thread pool", e);
// save for later
errors.add(e);
}
}
private void _cleanUpAwaitDisconnects(List<Throwable> errors, Set<Future<?>> pending) {
if (!pending.isEmpty()) {
LOGGER.log(Level.INFO, "Waiting for node disconnection completion");
}
for (Future<?> f : pending) {
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection cleanly", e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection within 10 seconds", e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection", e);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Unexpected error while waiting for remote computer connection disconnect", e);
errors.add(e);
}
}
}
private void _cleanUpPluginServletFilters(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Stopping filters");
try {
PluginServletFilter.cleanUp();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to stop filters", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to stop filters", e);
// save for later
errors.add(e);
}
}
private void _cleanUpReleaseAllLoggers(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Releasing all loggers");
try {
LogFactory.releaseAll();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to release all loggers", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to release all loggers", e);
// save for later
errors.add(e);
}
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if (Objects.equals(a.getUrlName(), token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
@RequirePOST
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
@RequirePOST // TODO does not seem to work on _either_ overload!
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
@RequirePOST
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
long waitUntil = timeout;
if (timeout > 0) waitUntil += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < waitUntil)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
@RequirePOST // TODO the cancel link needs to be updated accordingly
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all agents (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang agents.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r));
}
@RequirePOST
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
@RequirePOST
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if(".".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName("."));
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
* Used only by {@link LegacySecurityRealm}.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
// TODO fire something in SecurityListener?
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String user = getAuthentication().getName();
securityRealm.doLogout(req, rsp);
SecurityListener.fireLoggedOut(user);
}
/**
* Serves jar files for JNLP agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
LOGGER.log(Level.WARNING, "Reloading Jenkins as requested by {0}", getAuthentication().getName());
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
* Beware that this calls neither {@link ItemListener#onLoaded} nor {@link Initializer}s.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
queue.save();
executeReactor(null, loadTasks());
User.reload();
queue.load();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
@RequirePOST
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,FilePath.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Jenkins, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Jenkins for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException | IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
@Extension @Restricted(NoExternalUse.class)
public static class MasterRestartNotifyier extends RestartListener {
@Override
public void onRestart() {
Computer computer = Jenkins.getInstance().toComputer();
if (computer == null) return;
RestartCause cause = new RestartCause();
for (ComputerListener listener: ComputerListener.all()) {
listener.onOffline(computer, cause);
}
}
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return true;
}
private static class RestartCause extends OfflineCause.SimpleOfflineCause {
protected RestartCause() {
super(Messages._Jenkins_IsRestarting());
}
}
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
@RequirePOST
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
@RequirePOST
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static @Nonnull Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
if (channel == null) {
throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if (getSecurityRealm().allowsSignup()) {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
return;
}
req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
@RequirePOST
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
@RequirePOST
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!JDK.isDefaultName(value))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
@Deprecated
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
}, 500, TimeUnit.MILLISECONDS);
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* If set, a currently active setup wizard - e.g. installation
*
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public SetupWizard getSetupWizard() {
return setupWizard;
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
for (String name : ALWAYS_READABLE_PATHS) {
if (rest.startsWith(name)) {
return this;
}
}
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
if (rest.matches("/computer/[^/]+/slave-agent[.]jnlp")
&& "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))) {
return this;
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
String url = a.getUrlName();
if (url == null) continue;
names.add(url);
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
@Override
public Boolean isUnix() {
return !Functions.isWindows();
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@WebMethod(name="config.xml")
@Override
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return FilePath.localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
@RequirePOST
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*
* @deprecated as of 1.558
* Use {@link FilePath#localChannel}
*/
@Deprecated
public static final LocalChannel localChannel = FilePath.localChannel;
}
/**
* Shortcut for {@code Jenkins.getInstanceOrNull()?.lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstanceOrNull();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Jenkins.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM;
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver = UNCOMPUTED_VERSION;
if(Main.isDevelopmentMode && "${build.version}".equals(ver)) {
// in dev mode, unable to get version (ahem Eclipse)
try {
File dir = new File(".").getAbsoluteFile();
while(dir != null) {
File pom = new File(dir, "pom.xml");
if (pom.exists() && "pom".equals(XMLUtils.getValue("/project/artifactId", pom))) {
pom = pom.getCanonicalFile();
LOGGER.info("Reading version from: " + pom.getAbsolutePath());
ver = XMLUtils.getValue("/project/version", pom);
break;
}
dir = dir.getParentFile();
}
LOGGER.info("Jenkins is in dev mode, using version: " + ver);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Unable to read Jenkins version: " + e.getMessage(), e);
}
}
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals(UNCOMPUTED_VERSION) || SystemProperties.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* The version number before it is "computed" (by a call to computeVersion()).
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public static final String UNCOMPUTED_VERSION = "?";
/**
* Version number of this Jenkins.
*/
public static String VERSION = UNCOMPUTED_VERSION;
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
public @CheckForNull static VersionNumber getVersion() {
return toVersion(VERSION);
}
/**
* Get the stored version of Jenkins, as stored by
* {@link #doConfigSubmit(org.kohsuke.stapler.StaplerRequest, org.kohsuke.stapler.StaplerResponse)}.
* <p>
* Parses the version into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public @CheckForNull static VersionNumber getStoredVersion() {
return toVersion(Jenkins.getActiveInstance().version);
}
/**
* Parses a version string into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
private static @CheckForNull VersionNumber toVersion(@CheckForNull String versionString) {
if (versionString == null) {
return null;
}
try {
return new VersionNumber(versionString);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = versionString.indexOf(' ');
if (idx > 0) {
return new VersionNumber(versionString.substring(0,idx));
}
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* @deprecated No longer used.
*/
@Deprecated
public static boolean FLYWEIGHT_SUPPORT = true;
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch an agent when Jenkins is initialized or a new agent computer is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* Urls that are always visible without READ permission.
*
* <p>See also:{@link #getUnprotectedRootActions}.
*/
private static final ImmutableSet<String> ALWAYS_READABLE_PATHS = ImmutableSet.of(
"/login",
"/logout",
"/accessDenied",
"/adjuncts/",
"/error",
"/oops",
"/signup",
"/tcpSlaveAgentListener",
"/federatedLoginService/",
"/securityRealm"
);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS;
static {
try {
ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
XSTREAM = XSTREAM2 = new XStream2();
XSTREAM.alias("jenkins", Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk", JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
XSTREAM2.addCriticalField(Jenkins.class, "securityRealm");
XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy");
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS != null;
assert ADMINISTER != null;
} catch (RuntimeException | Error e) {
// when loaded on an agent and this fails, subsequent NoClassDefFoundError will fail to chain the cause.
// see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847
// As we don't know where the first exception will go, let's also send this to logging so that
// we have a known place to look at.
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
}
}
private static final class JenkinsJVMAccess extends JenkinsJVM {
private static void _setJenkinsJVM(boolean jenkinsJVM) {
JenkinsJVM.setJenkinsJVM(jenkinsJVM);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_3053_0
|
crossvul-java_data_bad_5809_2
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_5809_2
|
crossvul-java_data_good_2096_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, David Calavera, Seiji Sogabe
*
* 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.
*/
package hudson.security;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import hudson.Extension;
import hudson.Util;
import hudson.diagnosis.OldDataMonitor;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import hudson.model.ManagementLink;
import hudson.model.ModelObject;
import hudson.model.User;
import hudson.model.UserProperty;
import hudson.model.UserPropertyDescriptor;
import hudson.security.FederatedLoginService.FederatedIdentity;
import hudson.security.captcha.CaptchaSupport;
import hudson.util.PluginServletFilter;
import hudson.util.Protector;
import hudson.util.Scrambler;
import hudson.util.XStream2;
import net.sf.json.JSONObject;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.encoding.PasswordEncoder;
import org.acegisecurity.providers.encoding.ShaPasswordEncoder;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.tools.ant.taskdefs.email.Mailer;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.dao.DataAccessException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link SecurityRealm} that performs authentication by looking up {@link User}.
*
* <p>
* Implements {@link AccessControlled} to satisfy view rendering, but in reality the access control
* is done against the {@link jenkins.model.Jenkins} object.
*
* @author Kohsuke Kawaguchi
*/
public class HudsonPrivateSecurityRealm extends AbstractPasswordBasedSecurityRealm implements ModelObject, AccessControlled {
/**
* If true, sign up is not allowed.
* <p>
* This is a negative switch so that the default value 'false' remains compatible with older installations.
*/
private final boolean disableSignup;
/**
* If true, captcha will be enabled.
*/
private final boolean enableCaptcha;
@Deprecated
public HudsonPrivateSecurityRealm(boolean allowsSignup) {
this(allowsSignup, false, (CaptchaSupport) null);
}
@DataBoundConstructor
public HudsonPrivateSecurityRealm(boolean allowsSignup, boolean enableCaptcha, CaptchaSupport captchaSupport) {
this.disableSignup = !allowsSignup;
this.enableCaptcha = enableCaptcha;
setCaptchaSupport(captchaSupport);
if(!allowsSignup && !hasSomeUser()) {
// if Hudson is newly set up with the security realm and there's no user account created yet,
// insert a filter that asks the user to create one
try {
PluginServletFilter.addFilter(CREATE_FIRST_USER_FILTER);
} catch (ServletException e) {
throw new AssertionError(e); // never happen because our Filter.init is no-op
}
}
}
@Override
public boolean allowsSignup() {
return !disableSignup;
}
/**
* Checks if captcha is enabled on user signup.
*
* @return true if captcha is enabled on signup.
*/
public boolean isEnableCaptcha() {
return enableCaptcha;
}
/**
* Computes if this Hudson has some user accounts configured.
*
* <p>
* This is used to check for the initial
*/
private static boolean hasSomeUser() {
for (User u : User.getAll())
if(u.getProperty(Details.class)!=null)
return true;
return false;
}
/**
* This implementation doesn't support groups.
*/
@Override
public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
throw new UsernameNotFoundException(groupname);
}
@Override
public Details loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
User u = User.get(username,false);
Details p = u!=null ? u.getProperty(Details.class) : null;
if(p==null)
throw new UsernameNotFoundException("Password is not set: "+username);
if(p.getUser()==null)
throw new AssertionError();
return p;
}
@Override
protected Details authenticate(String username, String password) throws AuthenticationException {
Details u = loadUserByUsername(username);
if (!u.isPasswordCorrect(password)) {
String message;
try {
message = ResourceBundle.getBundle("org.acegisecurity.messages").getString("AbstractUserDetailsAuthenticationProvider.badCredentials");
} catch (MissingResourceException x) {
message = "Bad credentials";
}
throw new BadCredentialsException(message);
}
return u;
}
/**
* Show the sign up page with the data from the identity.
*/
@Override
public HttpResponse commenceSignup(final FederatedIdentity identity) {
// store the identity in the session so that we can use this later
Stapler.getCurrentRequest().getSession().setAttribute(FEDERATED_IDENTITY_SESSION_KEY,identity);
return new ForwardToView(this,"signupWithFederatedIdentity.jelly") {
@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
SignupInfo si = new SignupInfo(identity);
si.errorMessage = Messages.HudsonPrivateSecurityRealm_WouldYouLikeToSignUp(identity.getPronoun(),identity.getIdentifier());
req.setAttribute("data", si);
super.generateResponse(req, rsp, node);
}
};
}
/**
* Creates an account and associates that with the given identity. Used in conjunction
* with {@link #commenceSignup(FederatedIdentity)}.
*/
public User doCreateAccountWithFederatedIdentity(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
User u = _doCreateAccount(req,rsp,"signupWithFederatedIdentity.jelly");
if (u!=null)
((FederatedIdentity)req.getSession().getAttribute(FEDERATED_IDENTITY_SESSION_KEY)).addTo(u);
return u;
}
private static final String FEDERATED_IDENTITY_SESSION_KEY = HudsonPrivateSecurityRealm.class.getName()+".federatedIdentity";
/**
* Creates an user account. Used for self-registration.
*/
public User doCreateAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
return _doCreateAccount(req, rsp, "signup.jelly");
}
private User _doCreateAccount(StaplerRequest req, StaplerResponse rsp, String formView) throws ServletException, IOException {
if(!allowsSignup())
throw HttpResponses.error(SC_UNAUTHORIZED,new Exception("User sign up is prohibited"));
boolean firstUser = !hasSomeUser();
User u = createAccount(req, rsp, enableCaptcha, formView);
if(u!=null) {
if(firstUser)
tryToMakeAdmin(u); // the first user should be admin, or else there's a risk of lock out
loginAndTakeBack(req, rsp, u);
}
return u;
}
/**
* Lets the current user silently login as the given user and report back accordingly.
*/
private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u) throws ServletException, IOException {
// ... and let him login
Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1"));
a = this.getSecurityComponents().manager.authenticate(a);
SecurityContextHolder.getContext().setAuthentication(a);
// then back to top
req.getView(this,"success.jelly").forward(req,rsp);
}
/**
* Creates an user account. Used by admins.
*
* This version behaves differently from {@link #doCreateAccount(StaplerRequest, StaplerResponse)} in that
* this is someone creating another user.
*/
public void doCreateAccountByAdmin(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(Jenkins.ADMINISTER);
if(createAccount(req, rsp, false, "addUser.jelly")!=null) {
rsp.sendRedirect("."); // send the user back to the listing page
}
}
/**
* Creates a first admin user account.
*
* <p>
* This can be run by anyone, but only to create the very first user account.
*/
public void doCreateFirstAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if(hasSomeUser()) {
rsp.sendError(SC_UNAUTHORIZED,"First user was already created");
return;
}
User u = createAccount(req, rsp, false, "firstUser.jelly");
if (u!=null) {
tryToMakeAdmin(u);
loginAndTakeBack(req, rsp, u);
}
}
/**
* Try to make this user a super-user
*/
private void tryToMakeAdmin(User u) {
AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy();
if (as instanceof GlobalMatrixAuthorizationStrategy) {
GlobalMatrixAuthorizationStrategy ma = (GlobalMatrixAuthorizationStrategy) as;
ma.add(Jenkins.ADMINISTER,u.getId());
}
}
/**
* @return
* null if failed. The browser is already redirected to retry by the time this method returns.
* a valid {@link User} object if the user creation was successful.
*/
private User createAccount(StaplerRequest req, StaplerResponse rsp, boolean selfRegistration, String formView) throws ServletException, IOException {
// form field validation
// this pattern needs to be generalized and moved to stapler
SignupInfo si = new SignupInfo(req);
if(selfRegistration && !validateCaptcha(si.captcha))
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_TextNotMatchWordInImage();
if(si.password1 != null && !si.password1.equals(si.password2))
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_PasswordNotMatch();
if(!(si.password1 != null && si.password1.length() != 0))
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_PasswordRequired();
if(si.username==null || si.username.length()==0)
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameRequired();
else {
User user = User.get(si.username, false);
if (null != user)
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameAlreadyTaken();
}
if(si.fullname==null || si.fullname.length()==0)
si.fullname = si.username;
if(si.email==null || !si.email.contains("@"))
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_InvalidEmailAddress();
if(si.errorMessage!=null) {
// failed. ask the user to try again.
req.setAttribute("data",si);
req.getView(this, formView).forward(req,rsp);
return null;
}
// register the user
User user = createAccount(si.username,si.password1);
user.setFullName(si.fullname);
try {
// legacy hack. mail support has moved out to a separate plugin
Class<?> up = Jenkins.getInstance().pluginManager.uberClassLoader.loadClass("hudson.tasks.Mailer$UserProperty");
Constructor<?> c = up.getDeclaredConstructor(String.class);
user.addProperty((UserProperty)c.newInstance(si.email));
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to set the e-mail address",e);
}
user.save();
return user;
}
/**
* Creates a new user account by registering a password to the user.
*/
public User createAccount(String userName, String password) throws IOException {
User user = User.get(userName);
user.addProperty(Details.fromPlainPassword(password));
return user;
}
/**
* This is used primarily when the object is listed in the breadcrumb, in the user management screen.
*/
public String getDisplayName() {
return "User Database";
}
public ACL getACL() {
return Jenkins.getInstance().getACL();
}
public void checkPermission(Permission permission) {
Jenkins.getInstance().checkPermission(permission);
}
public boolean hasPermission(Permission permission) {
return Jenkins.getInstance().hasPermission(permission);
}
/**
* All users who can login to the system.
*/
public List<User> getAllUsers() {
List<User> r = new ArrayList<User>();
for (User u : User.getAll()) {
if(u.getProperty(Details.class)!=null)
r.add(u);
}
Collections.sort(r);
return r;
}
/**
* This is to map users under the security realm URL.
* This in turn helps us set up the right navigation breadcrumb.
*/
public User getUser(String id) {
return User.get(id);
}
// TODO
private static final GrantedAuthority[] TEST_AUTHORITY = {AUTHENTICATED_AUTHORITY};
public static final class SignupInfo {
public String username,password1,password2,fullname,email,captcha;
/**
* To display an error message, set it here.
*/
public String errorMessage;
public SignupInfo() {
}
public SignupInfo(StaplerRequest req) {
req.bindParameters(this);
}
public SignupInfo(FederatedIdentity i) {
this.username = i.getNickname();
this.fullname = i.getFullName();
this.email = i.getEmailAddress();
}
}
/**
* {@link UserProperty} that provides the {@link UserDetails} view of the User object.
*
* <p>
* When a {@link User} object has this property on it, it means the user is configured
* for log-in.
*
* <p>
* When a {@link User} object is re-configured via the UI, the password
* is sent to the hidden input field by using {@link Protector}, so that
* the same password can be retained but without leaking information to the browser.
*/
public static final class Details extends UserProperty implements InvalidatableUserDetails {
/**
* Hashed password.
*/
private /*almost final*/ String passwordHash;
/**
* @deprecated Scrambled password.
* Field kept here to load old (pre 1.283) user records,
* but now marked transient so field is no longer saved.
*/
private transient String password;
private Details(String passwordHash) {
this.passwordHash = passwordHash;
}
static Details fromHashedPassword(String hashed) {
return new Details(hashed);
}
static Details fromPlainPassword(String rawPassword) {
return new Details(PASSWORD_ENCODER.encodePassword(rawPassword,null));
}
public GrantedAuthority[] getAuthorities() {
// TODO
return TEST_AUTHORITY;
}
public String getPassword() {
return passwordHash;
}
public boolean isPasswordCorrect(String candidate) {
return PASSWORD_ENCODER.isPasswordValid(getPassword(),candidate,null);
}
public String getProtectedPassword() {
// put session Id in it to prevent a replay attack.
return Protector.protect(Stapler.getCurrentRequest().getSession().getId()+':'+getPassword());
}
public String getUsername() {
return user.getId();
}
/*package*/ User getUser() {
return user;
}
public boolean isAccountNonExpired() {
return true;
}
public boolean isAccountNonLocked() {
return true;
}
public boolean isCredentialsNonExpired() {
return true;
}
public boolean isEnabled() {
return true;
}
public boolean isInvalid() {
return user==null;
}
public static class ConverterImpl extends XStream2.PassthruConverter<Details> {
public ConverterImpl(XStream2 xstream) { super(xstream); }
@Override protected void callback(Details d, UnmarshallingContext context) {
// Convert to hashed password and report to monitor if we load old data
if (d.password!=null && d.passwordHash==null) {
d.passwordHash = PASSWORD_ENCODER.encodePassword(Scrambler.descramble(d.password),null);
OldDataMonitor.report(context, "1.283");
}
}
}
@Extension
public static final class DescriptorImpl extends UserPropertyDescriptor {
public String getDisplayName() {
// this feature is only when HudsonPrivateSecurityRealm is enabled
if(isEnabled())
return Messages.HudsonPrivateSecurityRealm_Details_DisplayName();
else
return null;
}
@Override
public Details newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String pwd = Util.fixEmpty(req.getParameter("user.password"));
String pwd2= Util.fixEmpty(req.getParameter("user.password2"));
if(!Util.fixNull(pwd).equals(Util.fixNull(pwd2)))
throw new FormException("Please confirm the password by typing it twice","user.password2");
String data = Protector.unprotect(pwd);
if(data!=null) {
String prefix = Stapler.getCurrentRequest().getSession().getId() + ':';
if(data.startsWith(prefix))
return Details.fromHashedPassword(data.substring(prefix.length()));
}
return Details.fromPlainPassword(Util.fixNull(pwd));
}
@Override
public boolean isEnabled() {
return Jenkins.getInstance().getSecurityRealm() instanceof HudsonPrivateSecurityRealm;
}
public UserProperty newInstance(User user) {
return null;
}
}
}
/**
* Displays "manage users" link in the system config if {@link HudsonPrivateSecurityRealm}
* is in effect.
*/
@Extension
public static final class ManageUserLinks extends ManagementLink {
public String getIconFileName() {
if(Jenkins.getInstance().getSecurityRealm() instanceof HudsonPrivateSecurityRealm)
return "user.png";
else
return null; // not applicable now
}
public String getUrlName() {
return "securityRealm/";
}
public String getDisplayName() {
return Messages.HudsonPrivateSecurityRealm_ManageUserLinks_DisplayName();
}
@Override
public String getDescription() {
return Messages.HudsonPrivateSecurityRealm_ManageUserLinks_Description();
}
}
/**
* {@link PasswordEncoder} based on SHA-256 and random salt generation.
*
* <p>
* The salt is prepended to the hashed password and returned. So the encoded password is of the form
* <tt>SALT ':' hash(PASSWORD,SALT)</tt>.
*
* <p>
* This abbreviates the need to store the salt separately, which in turn allows us to hide the salt handling
* in this little class. The rest of the Acegi thinks that we are not using salt.
*/
/*package*/ static final PasswordEncoder CLASSIC = new PasswordEncoder() {
private final PasswordEncoder passwordEncoder = new ShaPasswordEncoder(256);
public String encodePassword(String rawPass, Object _) throws DataAccessException {
return hash(rawPass);
}
public boolean isPasswordValid(String encPass, String rawPass, Object _) throws DataAccessException {
// pull out the sale from the encoded password
int i = encPass.indexOf(':');
if(i<0) return false;
String salt = encPass.substring(0,i);
return encPass.substring(i+1).equals(passwordEncoder.encodePassword(rawPass,salt));
}
/**
* Creates a hashed password by generating a random salt.
*/
private String hash(String password) {
String salt = generateSalt();
return salt+':'+passwordEncoder.encodePassword(password,salt);
}
/**
* Generates random salt.
*/
private String generateSalt() {
StringBuilder buf = new StringBuilder();
SecureRandom sr = new SecureRandom();
for( int i=0; i<6; i++ ) {// log2(52^6)=34.20... so, this is about 32bit strong.
boolean upper = sr.nextBoolean();
char ch = (char)(sr.nextInt(26) + 'a');
if(upper) ch=Character.toUpperCase(ch);
buf.append(ch);
}
return buf.toString();
}
};
/**
* {@link PasswordEncoder} that uses jBCrypt.
*/
private static final PasswordEncoder JBCRYPT_ENCODER = new PasswordEncoder() {
public String encodePassword(String rawPass, Object _) throws DataAccessException {
return BCrypt.hashpw(rawPass,BCrypt.gensalt());
}
public boolean isPasswordValid(String encPass, String rawPass, Object _) throws DataAccessException {
return BCrypt.checkpw(rawPass,encPass);
}
};
/**
* Combines {@link #JBCRYPT_ENCODER} and {@link #CLASSIC} into one so that we can continue
* to accept {@link #CLASSIC} format but new encoding will always done via {@link #JBCRYPT_ENCODER}.
*/
public static final PasswordEncoder PASSWORD_ENCODER = new PasswordEncoder() {
/*
CLASSIC encoder outputs "salt:hash" where salt is [a-z]+, so we use unique prefix '#jbcyrpt"
to designate JBCRYPT-format hash.
'#' is neither in base64 nor hex, which makes it a good choice.
*/
public String encodePassword(String rawPass, Object salt) throws DataAccessException {
return JBCRYPT_HEADER+JBCRYPT_ENCODER.encodePassword(rawPass,salt);
}
public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException {
if (encPass.startsWith(JBCRYPT_HEADER))
return JBCRYPT_ENCODER.isPasswordValid(encPass.substring(JBCRYPT_HEADER.length()),rawPass,salt);
else
return CLASSIC.isPasswordValid(encPass,rawPass,salt);
}
private static final String JBCRYPT_HEADER = "#jbcrypt:";
};
@Extension
public static final class DescriptorImpl extends Descriptor<SecurityRealm> {
public String getDisplayName() {
return Messages.HudsonPrivateSecurityRealm_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/security/private-realm.html";
}
}
private static final Filter CREATE_FIRST_USER_FILTER = new Filter() {
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if(req.getRequestURI().equals(req.getContextPath()+"/")) {
if (needsToCreateFirstUser()) {
((HttpServletResponse)response).sendRedirect("securityRealm/firstUser");
} else {// the first user already created. the role of this filter is over.
PluginServletFilter.removeFilter(this);
chain.doFilter(request,response);
}
} else
chain.doFilter(request,response);
}
private boolean needsToCreateFirstUser() {
return !hasSomeUser()
&& Jenkins.getInstance().getSecurityRealm() instanceof HudsonPrivateSecurityRealm;
}
public void destroy() {
}
};
private static final Logger LOGGER = Logger.getLogger(HudsonPrivateSecurityRealm.class.getName());
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_2096_0
|
crossvul-java_data_good_972_0
|
package com.fasterxml.jackson.databind.jsontype.impl;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
/**
* Helper class used to encapsulate rules that determine subtypes that
* are invalid to use, even with default typing, mostly due to security
* concerns.
* Used by <code>BeanDeserializerFacotry</code>
*
* @since 2.8.11
*/
public class SubTypeValidator
{
protected final static String PREFIX_SPRING = "org.springframework.";
protected final static String PREFIX_C3P0 = "com.mchange.v2.c3p0.";
/**
* Set of well-known "nasty classes", deserialization of which is considered dangerous
* and should (and is) prevented by default.
*/
protected final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES;
static {
Set<String> s = new HashSet<String>();
// Courtesy of [https://github.com/kantega/notsoserial]:
// (and wrt [databind#1599])
s.add("org.apache.commons.collections.functors.InvokerTransformer");
s.add("org.apache.commons.collections.functors.InstantiateTransformer");
s.add("org.apache.commons.collections4.functors.InvokerTransformer");
s.add("org.apache.commons.collections4.functors.InstantiateTransformer");
s.add("org.codehaus.groovy.runtime.ConvertedClosure");
s.add("org.codehaus.groovy.runtime.MethodClosure");
s.add("org.springframework.beans.factory.ObjectFactory");
s.add("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl");
s.add("org.apache.xalan.xsltc.trax.TemplatesImpl");
// [databind#1680]: may or may not be problem, take no chance
s.add("com.sun.rowset.JdbcRowSetImpl");
// [databind#1737]; JDK provided
s.add("java.util.logging.FileHandler");
s.add("java.rmi.server.UnicastRemoteObject");
// [databind#1737]; 3rd party
//s.add("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor"); // deprecated by [databind#1855]
s.add("org.springframework.beans.factory.config.PropertyPathFactoryBean");
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // deprecated by [databind#1931]
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // - "" -
// [databind#1855]: more 3rd party
s.add("org.apache.tomcat.dbcp.dbcp2.BasicDataSource");
s.add("com.sun.org.apache.bcel.internal.util.ClassLoader");
// [databind#2032]: more 3rd party; data exfiltration via xml parsed ext entities
s.add("org.apache.ibatis.parsing.XPathParser");
// [databind#2052]: Jodd-db, with jndi/ldap lookup
s.add("jodd.db.connection.DataSourceConnectionProvider");
// [databind#2058]: Oracle JDBC driver, with jndi/ldap lookup
s.add("oracle.jdbc.connector.OracleManagedConnectionFactory");
s.add("oracle.jdbc.rowset.OracleJDBCRowSet");
// [databind#1899]: more 3rd party
s.add("org.hibernate.jmx.StatisticsService");
s.add("org.apache.ibatis.datasource.jndi.JndiDataSourceFactory");
// [databind#2097]: some 3rd party, one JDK-bundled
s.add("org.slf4j.ext.EventData");
s.add("flex.messaging.util.concurrent.AsynchBeansWorkManagerExecutor");
s.add("com.sun.deploy.security.ruleset.DRSHelper");
s.add("org.apache.axis2.jaxws.spi.handler.HandlerResolverImpl");
// [databind#2186]: yet more 3rd party gadgets
s.add("org.jboss.util.propertyeditor.DocumentEditor");
s.add("org.apache.openjpa.ee.RegistryManagedRuntime");
s.add("org.apache.openjpa.ee.JNDIManagedRuntime");
s.add("org.apache.axis2.transport.jms.JMSOutTransportInfo");
// [databind#2326] (2.7.9.6): one more 3rd party gadget
s.add("com.mysql.cj.jdbc.admin.MiniAdmin");
// [databind#2334]: logback-core
s.add("ch.qos.logback.core.db.DriverManagerConnectionSource");
// [databind#2341]: jdom/jdom2
s.add("org.jdom.transform.XSLTransformer");
s.add("org.jdom2.transform.XSLTransformer");
// [databind#2387]: EHCache
s.add("net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup");
// [databind#2389]: logback/jndi
s.add("ch.qos.logback.core.db.JNDIConnectionSource");
DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);
}
/**
* Set of class names of types that are never to be deserialized.
*/
protected Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES;
private final static SubTypeValidator instance = new SubTypeValidator();
protected SubTypeValidator() { }
public static SubTypeValidator instance() { return instance; }
public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
main_check:
do {
if (_cfgIllegalClassNames.contains(full)) {
break;
}
// 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
// for some Spring framework types
// 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
if (raw.isInterface()) {
;
} else if (full.startsWith(PREFIX_SPRING)) {
for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){
String name = cls.getSimpleName();
// looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
if ("AbstractPointcutAdvisor".equals(name)
// ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts
|| "AbstractApplicationContext".equals(name)) {
break main_check;
}
}
} else if (full.startsWith(PREFIX_C3P0)) {
// [databind#1737]; more 3rd party
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
// [databind#1931]; more 3rd party
// com.mchange.v2.c3p0.ComboPooledDataSource
// com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource
if (full.endsWith("DataSource")) {
break main_check;
}
}
return;
} while (false);
throw JsonMappingException.from(ctxt,
String.format("Illegal type (%s) to deserialize: prevented for security reasons", full));
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_972_0
|
crossvul-java_data_bad_3043_0
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.saml.common.util;
import org.keycloak.saml.common.ErrorCodes;
import org.keycloak.saml.common.PicketLinkLogger;
import org.keycloak.saml.common.PicketLinkLoggerFactory;
import org.keycloak.saml.common.constants.GeneralConstants;
import org.keycloak.saml.common.constants.JBossSAMLConstants;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.exceptions.ConfigurationException;
import org.keycloak.saml.common.exceptions.ParsingException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.InputStream;
/**
* Utility for the stax based parser
*
* @author Anil.Saldhana@redhat.com
* @since Feb 8, 2010
*/
public class StaxParserUtil {
private static final PicketLinkLogger logger = PicketLinkLoggerFactory.getLogger();
public static void validate(InputStream doc, InputStream sch) throws ParsingException {
try {
XMLEventReader xmlEventReader = StaxParserUtil.getXMLEventReader(doc);
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(sch));
Validator validator = schema.newValidator();
validator.validate(new StAXSource(xmlEventReader));
} catch (Exception e) {
throw logger.parserException(e);
}
}
/**
* Bypass an entire XML element block from startElement to endElement
*
* @param xmlEventReader
* @param tag Tag of the XML element that we need to bypass
*
* @throws org.keycloak.saml.common.exceptions.ParsingException
*/
public static void bypassElementBlock(XMLEventReader xmlEventReader, String tag) throws ParsingException {
while (xmlEventReader.hasNext()) {
EndElement endElement = getNextEndElement(xmlEventReader);
if (endElement == null)
return;
if (StaxParserUtil.matches(endElement, tag))
return;
}
}
/**
* Advances reader if character whitespace encountered
*
* @param xmlEventReader
* @param xmlEvent
* @return
*/
public static boolean wasWhitespacePeeked(XMLEventReader xmlEventReader, XMLEvent xmlEvent) {
if (xmlEvent.isCharacters()) {
Characters chars = xmlEvent.asCharacters();
String data = chars.getData();
if (data == null || data.trim().equals("")) {
try {
xmlEventReader.nextEvent();
return true;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
}
return false;
}
/**
* Given an {@code Attribute}, get its trimmed value
*
* @param attribute
*
* @return
*/
public static String getAttributeValue(Attribute attribute) {
String str = trim(attribute.getValue());
str = StringUtil.getSystemPropertyAsString(str);
return str;
}
/**
* Get the Attribute value
*
* @param startElement
* @param tag localpart of the qname of the attribute
*
* @return
*/
public static String getAttributeValue(StartElement startElement, String tag) {
String result = null;
Attribute attr = startElement.getAttributeByName(new QName(tag));
if (attr != null)
result = getAttributeValue(attr);
return result;
}
/**
* Get the Attribute value
*
* @param startElement
* @param tag localpart of the qname of the attribute
*
* @return false if attribute not set
*/
public static boolean getBooleanAttributeValue(StartElement startElement, String tag) {
return getBooleanAttributeValue(startElement, tag, false);
}
/**
* Get the Attribute value
*
* @param startElement
* @param tag localpart of the qname of the attribute
*
* @return false if attribute not set
*/
public static boolean getBooleanAttributeValue(StartElement startElement, String tag, boolean defaultValue) {
String result = null;
Attribute attr = startElement.getAttributeByName(new QName(tag));
if (attr != null)
result = getAttributeValue(attr);
if (result == null) return defaultValue;
return Boolean.valueOf(result);
}
/**
* Given that the {@code XMLEventReader} is in {@code XMLStreamConstants.START_ELEMENT} mode, we parse into a DOM
* Element
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static Element getDOMElement(XMLEventReader xmlEventReader) throws ParsingException {
Transformer transformer = null;
final String JDK_TRANSFORMER_PROPERTY = "picketlink.jdk.transformer";
boolean useJDKTransformer = Boolean.parseBoolean(SecurityActions.getSystemProperty(JDK_TRANSFORMER_PROPERTY, "false"));
try {
if (useJDKTransformer) {
transformer = TransformerUtil.getTransformer();
} else {
transformer = TransformerUtil.getStaxSourceToDomResultTransformer();
}
Document resultDocument = DocumentUtil.createDocument();
DOMResult domResult = new DOMResult(resultDocument);
Source source = new StAXSource(xmlEventReader);
TransformerUtil.transform(transformer, source, domResult);
Document doc = (Document) domResult.getNode();
return doc.getDocumentElement();
} catch (ConfigurationException e) {
throw logger.parserException(e);
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Get the element text.
*
* @param xmlEventReader
*
* @return A <b>trimmed</b> string value
*
* @throws ParsingException
*/
public static String getElementText(XMLEventReader xmlEventReader) throws ParsingException {
String str = null;
try {
str = xmlEventReader.getElementText().trim();
str = StringUtil.getSystemPropertyAsString(str);
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
return str;
}
/**
* Get the XML event reader
*
* @param is
*
* @return
*/
public static XMLEventReader getXMLEventReader(InputStream is) {
XMLInputFactory xmlInputFactory;
XMLEventReader xmlEventReader = null;
try {
xmlInputFactory = XML_INPUT_FACTORY.get();
xmlEventReader = xmlInputFactory.createXMLEventReader(is);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return xmlEventReader;
}
/**
* Given a {@code Location}, return a formatted string [lineNum,colNum]
*
* @param location
*
* @return
*/
public static String getLineColumnNumber(Location location) {
StringBuilder builder = new StringBuilder("[");
builder.append(location.getLineNumber()).append(",").append(location.getColumnNumber()).append("]");
return builder.toString();
}
/**
* Get the next xml event
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static XMLEvent getNextEvent(XMLEventReader xmlEventReader) throws ParsingException {
try {
return xmlEventReader.nextEvent();
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Get the next {@code StartElement }
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static StartElement getNextStartElement(XMLEventReader xmlEventReader) throws ParsingException {
try {
while (xmlEventReader.hasNext()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if (xmlEvent == null || xmlEvent.isStartElement())
return (StartElement) xmlEvent;
}
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
return null;
}
/**
* Get the next {@code EndElement}
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static EndElement getNextEndElement(XMLEventReader xmlEventReader) throws ParsingException {
try {
while (xmlEventReader.hasNext()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if (xmlEvent == null || xmlEvent.isEndElement())
return (EndElement) xmlEvent;
}
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
return null;
}
/**
* Return the name of the start element
*
* @param startElement
*
* @return
*/
public static String getStartElementName(StartElement startElement) {
return trim(startElement.getName().getLocalPart());
}
/**
* Return the name of the end element
*
* @param endElement
*
* @return
*/
public static String getEndElementName(EndElement endElement) {
return trim(endElement.getName().getLocalPart());
}
/**
* Given a start element, obtain the xsi:type defined
*
* @param startElement
*
* @return
*
* @throws RuntimeException if xsi:type is missing
*/
public static String getXSITypeValue(StartElement startElement) {
Attribute xsiType = startElement.getAttributeByName(new QName(JBossSAMLURIConstants.XSI_NSURI.get(),
JBossSAMLConstants.TYPE.get()));
if (xsiType == null)
throw logger.parserExpectedXSI(ErrorCodes.EXPECTED_XSI);
return StaxParserUtil.getAttributeValue(xsiType);
}
/**
* Return whether the next event is going to be text
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static boolean hasTextAhead(XMLEventReader xmlEventReader) throws ParsingException {
XMLEvent event = peek(xmlEventReader);
return event.getEventType() == XMLEvent.CHARACTERS;
}
/**
* Match that the start element with the expected tag
*
* @param startElement
* @param tag
*
* @return boolean if the tags match
*/
public static boolean matches(StartElement startElement, String tag) {
String elementTag = getStartElementName(startElement);
return tag.equals(elementTag);
}
/**
* Match that the end element with the expected tag
*
* @param endElement
* @param tag
*
* @return boolean if the tags match
*/
public static boolean matches(EndElement endElement, String tag) {
String elementTag = getEndElementName(endElement);
return tag.equals(elementTag);
}
/**
* Peek at the next event
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static XMLEvent peek(XMLEventReader xmlEventReader) throws ParsingException {
try {
return xmlEventReader.peek();
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Peek the next {@code StartElement }
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static StartElement peekNextStartElement(XMLEventReader xmlEventReader) throws ParsingException {
try {
while (true) {
XMLEvent xmlEvent = xmlEventReader.peek();
if (xmlEvent == null || xmlEvent.isStartElement())
return (StartElement) xmlEvent;
else
xmlEvent = xmlEventReader.nextEvent();
}
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Peek the next {@code EndElement}
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static EndElement peekNextEndElement(XMLEventReader xmlEventReader) throws ParsingException {
try {
while (true) {
XMLEvent xmlEvent = xmlEventReader.peek();
if (xmlEvent == null || xmlEvent.isEndElement())
return (EndElement) xmlEvent;
else
xmlEvent = xmlEventReader.nextEvent();
}
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Given a string, trim it
*
* @param str
*
* @return
*
* @throws {@code IllegalArgumentException} if the passed str is null
*/
public static final String trim(String str) {
if (str == null)
throw logger.nullArgumentError("String to trim");
return str.trim();
}
/**
* Validate that the start element has the expected tag
*
* @param startElement
* @param tag
*
* @throws RuntimeException mismatch
*/
public static void validate(StartElement startElement, String tag) {
String foundElementTag = getStartElementName(startElement);
if (!tag.equals(foundElementTag))
throw logger.parserExpectedTag(tag, foundElementTag);
}
/**
* Validate that the end element has the expected tag
*
* @param endElement
* @param tag
*
* @throws RuntimeException mismatch
*/
public static void validate(EndElement endElement, String tag) {
String elementTag = getEndElementName(endElement);
if (!tag.equals(elementTag))
throw new RuntimeException(logger.parserExpectedEndTag("</" + tag + ">. Found </" + elementTag + ">"));
}
private static final ThreadLocal<XMLInputFactory> XML_INPUT_FACTORY = new ThreadLocal<XMLInputFactory>() {
@Override
protected XMLInputFactory initialValue() {
return getXMLInputFactory();
}
};
private static XMLInputFactory getXMLInputFactory() {
boolean tccl_jaxp = SystemPropertiesUtil.getSystemProperty(GeneralConstants.TCCL_JAXP, "false")
.equalsIgnoreCase("true");
ClassLoader prevTCCL = SecurityActions.getTCCL();
try {
if (tccl_jaxp) {
SecurityActions.setTCCL(StaxParserUtil.class.getClassLoader());
}
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
return xmlInputFactory;
} finally {
if (tccl_jaxp) {
SecurityActions.setTCCL(prevTCCL);
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_3043_0
|
crossvul-java_data_bad_4347_3
|
/*
* Copyright (c) 2020 Ubique Innovation AG <https://www.ubique.ch>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.jsonwebtoken.Jwts;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dpppt.backend.sdk.data.gaen.FakeKeyService;
import org.dpppt.backend.sdk.data.gaen.GAENDataService;
import org.dpppt.backend.sdk.model.gaen.*;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention;
import org.dpppt.backend.sdk.ws.security.ValidateRequest;
import org.dpppt.backend.sdk.ws.security.ValidateRequest.InvalidDateException;
import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature;
import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature.ProtoSignatureWrapper;
import org.dpppt.backend.sdk.ws.util.ValidationUtils;
import org.dpppt.backend.sdk.ws.util.ValidationUtils.BadBatchReleaseTimeException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.Callable;
@Controller
@RequestMapping("/v1/gaen")
@Tag(name = "GAEN", description = "The GAEN endpoint for the mobile clients")
/**
* The GaenController defines the API endpoints for the mobile clients to access the GAEN functionality of the
* red backend.
* Clients can send new Exposed Keys, or request the existing Exposed Keys.
*/
public class GaenController {
private static final Logger logger = LoggerFactory.getLogger(GaenController.class);
private static final String FAKE_CODE = "112358132134";
private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER =
DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
.withZoneUTC().withLocale(Locale.ENGLISH);
// releaseBucketDuration is used to delay the publishing of Exposed Keys by splitting the database up into batches of keys
// in releaseBucketDuration duration. The current batch is never published, only previous batches are published.
private final Duration releaseBucketDuration;
private final Duration requestTime;
private final ValidateRequest validateRequest;
private final ValidationUtils validationUtils;
private final GAENDataService dataService;
private final FakeKeyService fakeKeyService;
private final Duration exposedListCacheControl;
private final PrivateKey secondDayKey;
private final ProtoSignature gaenSigner;
public GaenController(GAENDataService dataService, FakeKeyService fakeKeyService, ValidateRequest validateRequest,
ProtoSignature gaenSigner, ValidationUtils validationUtils, Duration releaseBucketDuration, Duration requestTime,
Duration exposedListCacheControl, PrivateKey secondDayKey) {
this.dataService = dataService;
this.fakeKeyService = fakeKeyService;
this.releaseBucketDuration = releaseBucketDuration;
this.validateRequest = validateRequest;
this.requestTime = requestTime;
this.validationUtils = validationUtils;
this.exposedListCacheControl = exposedListCacheControl;
this.secondDayKey = secondDayKey;
this.gaenSigner = gaenSigner;
}
@PostMapping(value = "/exposed")
@Loggable
@ResponseRetention(time = "application.response.retention.time.exposed")
@Transactional
@Operation(description = "Send exposed keys to server - includes a fix for the fact that GAEN doesn't give access to the current day's exposed key")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed keys have been stored in the database"),
@ApiResponse(responseCode = "400", description =
"- Invalid base64 encoding in GaenRequest" +
"- negative rolling period" +
"- fake claim with non-fake keys"),
@ApiResponse(responseCode = "403", description = "Authentication failed") })
public @ResponseBody Callable<ResponseEntity<String>> addExposed(
@Valid @RequestBody @Parameter(description = "The GaenRequest contains the SecretKey from the guessed infection date, the infection date itself, and some authentication data to verify the test result") GaenRequest gaenRequest,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server") Object principal) {
var now = Instant.now().toEpochMilli();
if (!this.validateRequest.isValid(principal)) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
List<GaenKey> nonFakeKeys = new ArrayList<>();
for (var key : gaenRequest.getGaenKeys()) {
if (!validationUtils.isValidBase64Key(key.getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (this.validateRequest.isFakeRequest(principal, key)
|| hasNegativeRollingPeriod(key)
|| hasInvalidKeyDate(principal, key)) {
continue;
}
if (key.getRollingPeriod().equals(0)) {
//currently only android seems to send 0 which can never be valid, since a non used key should not be submitted
//default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since
//this should not happen
key.setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod);
if (userAgent.toLowerCase().contains("ios")) {
logger.error("Received a rolling period of 0 for an iOS User-Agent");
}
}
nonFakeKeys.add(key);
}
if (principal instanceof Jwt && ((Jwt) principal).containsClaim("fake")
&& ((Jwt) principal).getClaimAsString("fake").equals("1")) {
Jwt token = (Jwt) principal;
if (FAKE_CODE.equals(token.getSubject())) {
logger.info("Claim is fake - subject: {}", token.getSubject());
} else if (!nonFakeKeys.isEmpty()) {
return () -> ResponseEntity.badRequest().body("Claim is fake but list contains non fake keys");
}
}
if (!nonFakeKeys.isEmpty()) {
dataService.upsertExposees(nonFakeKeys);
}
var delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes);
var delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()),
ZoneOffset.UTC);
var nowDay = LocalDate.now(ZoneOffset.UTC);
if (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) {
return () -> ResponseEntity.badRequest().body("delayedKeyDate date must be between yesterday and tomorrow");
}
var responseBuilder = ResponseEntity.ok();
if (principal instanceof Jwt) {
var originalJWT = (Jwt) principal;
var jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now()))
.setIssuer("dpppt-sdk-backend").setSubject(originalJWT.getSubject())
.setExpiration(Date
.from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48))))
.claim("scope", "currentDayExposed").claim("delayedKeyDate", gaenRequest.getDelayedKeyDate());
if (originalJWT.containsClaim("fake")) {
jwtBuilder.claim("fake", originalJWT.getClaim("fake"));
}
String jwt = jwtBuilder.signWith(secondDayKey).compact();
responseBuilder.header("Authorization", "Bearer " + jwt);
responseBuilder.header("X-Exposed-Token", "Bearer " + jwt);
}
Callable<ResponseEntity<String>> cb = () -> {
normalizeRequestTime(now);
return responseBuilder.body("OK");
};
return cb;
}
@PostMapping(value = "/exposednextday")
@Loggable
@Transactional
@Operation(description = "Allows the client to send the last exposed key of the infection to the backend server. The JWT must come from a previous call to /exposed")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed key has been stored in the backend"),
@ApiResponse(responseCode = "400", description =
"- Ivnalid base64 encoded Temporary Exposure Key" +
"- TEK-date does not match delayedKeyDAte claim in Jwt" +
"- TEK has negative rolling period"),
@ApiResponse(responseCode = "403", description = "No delayedKeyDate claim in authentication") })
public @ResponseBody Callable<ResponseEntity<String>> addExposedSecond(
@Valid @RequestBody @Parameter(description = "The last exposed key of the user") GaenSecondDay gaenSecondDay,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate") Object principal) {
var now = Instant.now().toEpochMilli();
if (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (principal instanceof Jwt && !((Jwt) principal).containsClaim("delayedKeyDate")) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body("claim does not contain delayedKeyDate");
}
if (principal instanceof Jwt) {
var jwt = (Jwt) principal;
var claimKeyDate = Integer.parseInt(jwt.getClaimAsString("delayedKeyDate"));
if (!gaenSecondDay.getDelayedKey().getRollingStartNumber().equals(claimKeyDate)) {
return () -> ResponseEntity.badRequest().body("keyDate does not match claim keyDate");
}
}
if (!this.validateRequest.isFakeRequest(principal, gaenSecondDay.getDelayedKey())) {
if (gaenSecondDay.getDelayedKey().getRollingPeriod().equals(0)) {
// currently only android seems to send 0 which can never be valid, since a non used key should not be submitted
// default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since
// this should not happen
gaenSecondDay.getDelayedKey().setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod);
if(userAgent.toLowerCase().contains("ios")) {
logger.error("Received a rolling period of 0 for an iOS User-Agent");
}
} else if(gaenSecondDay.getDelayedKey().getRollingPeriod() < 0) {
return () -> ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rolling Period MUST NOT be negative.");
}
List<GaenKey> keys = new ArrayList<>();
keys.add(gaenSecondDay.getDelayedKey());
dataService.upsertExposees(keys);
}
return () -> {
normalizeRequestTime(now);
return ResponseEntity.ok().body("OK");
};
}
@GetMapping(value = "/exposed/{keyDate}", produces = "application/zip")
@Loggable
@Operation(description = "Request the exposed key from a given date")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"),
@ApiResponse(responseCode = "400", description =
"- invalid starting key date, doesn't point to midnight UTC" +
"- _publishedAfter_ is not at the beginning of a batch release time, currently 2h")})
public @ResponseBody ResponseEntity<byte[]> getExposedKeys(
@PathVariable @Parameter(description = "Requested date for Exposed Keys retrieval, in milliseconds since Unix epoch (1970-01-01). It must indicate the beginning of a TEKRollingPeriod, currently midnight UTC.", example = "1593043200000") long keyDate,
@RequestParam(required = false) @Parameter(description = "Restrict returned Exposed Keys to dates after this parameter. Given in milliseconds since Unix epoch (1970-01-01).", example = "1593043200000") Long publishedafter)
throws BadBatchReleaseTimeException, IOException, InvalidKeyException, SignatureException,
NoSuchAlgorithmException {
if (!validationUtils.isValidKeyDate(keyDate)) {
return ResponseEntity.notFound().build();
}
if (publishedafter != null && !validationUtils.isValidBatchReleaseTime(publishedafter)) {
return ResponseEntity.notFound().build();
}
long now = System.currentTimeMillis();
// calculate exposed until bucket
long publishedUntil = now - (now % releaseBucketDuration.toMillis());
DateTime dateTime = new DateTime(publishedUntil + releaseBucketDuration.toMillis() - 1, DateTimeZone.UTC);
var exposedKeys = dataService.getSortedExposedForKeyDate(keyDate, publishedafter, publishedUntil);
exposedKeys = fakeKeyService.fillUpKeys(exposedKeys, publishedafter, keyDate);
if (exposedKeys.isEmpty()) {
return ResponseEntity.noContent()//.cacheControl(CacheControl.maxAge(exposedListCacheControl))
.header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil))
.header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime))
.build();
}
ProtoSignatureWrapper payload = gaenSigner.getPayload(exposedKeys);
return ResponseEntity.ok()//.cacheControl(CacheControl.maxAge(exposedListCacheControl))
.header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil))
.header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime))
.body(payload.getZip());
}
@GetMapping(value = "/buckets/{dayDateStr}")
@Loggable
@Operation(description = "Request the available release batch times for a given day")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"),
@ApiResponse(responseCode = "400", description = "invalid starting key date, points outside of the retention range")})
public @ResponseBody ResponseEntity<DayBuckets> getBuckets(
@PathVariable @Parameter(description = "Starting date for exposed key retrieval, as ISO-8601 format", example = "2020-06-27") String dayDateStr) {
var atStartOfDay = LocalDate.parse(dayDateStr).atStartOfDay().toInstant(ZoneOffset.UTC)
.atOffset(ZoneOffset.UTC);
var end = atStartOfDay.plusDays(1);
var now = Instant.now().atOffset(ZoneOffset.UTC);
if (!validationUtils.isDateInRange(atStartOfDay)) {
return ResponseEntity.notFound().build();
}
var relativeUrls = new ArrayList<String>();
var dayBuckets = new DayBuckets();
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
dayBuckets.setDay(dayDateStr).setRelativeUrls(relativeUrls).setDayTimestamp(atStartOfDay.toInstant().toEpochMilli());
while (atStartOfDay.toInstant().toEpochMilli() < Math.min(now.toInstant().toEpochMilli(),
end.toInstant().toEpochMilli())) {
relativeUrls.add(controllerMapping + "/exposed" + "/" + atStartOfDay.toInstant().toEpochMilli());
atStartOfDay = atStartOfDay.plus(this.releaseBucketDuration);
}
return ResponseEntity.ok(dayBuckets);
}
private void normalizeRequestTime(long now) {
long after = Instant.now().toEpochMilli();
long duration = after - now;
try {
Thread.sleep(Math.max(requestTime.minusMillis(duration).toMillis(), 0));
} catch (Exception ex) {
logger.error("Couldn't equalize request time: {}", ex.toString());
}
}
private boolean hasNegativeRollingPeriod(GaenKey key) {
Integer rollingPeriod = key.getRollingPeriod();
if (key.getRollingPeriod() < 0) {
logger.error("Detected key with negative rolling period {}", rollingPeriod);
return true;
} else {
return false;
}
}
private boolean hasInvalidKeyDate(Object principal, GaenKey key) {
try {
this.validateRequest.getKeyDate(principal, key);
}
catch (InvalidDateException invalidDate) {
logger.error(invalidDate.getLocalizedMessage());
return true;
}
return false;
}
@ExceptionHandler({IllegalArgumentException.class, InvalidDateException.class, JsonProcessingException.class,
MethodArgumentNotValidException.class, BadBatchReleaseTimeException.class, DateTimeParseException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Object> invalidArguments(Exception ex) {
logger.error("Exception ({}): {}", ex.getClass().getSimpleName(), ex.getMessage(), ex);
return ResponseEntity.badRequest().build();
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_4347_3
|
crossvul-java_data_good_4348_2
|
/*
* Copyright (c) 2020 Ubique Innovation AG <https://www.ubique.ch>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.jsonwebtoken.Jwts;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dpppt.backend.sdk.data.gaen.FakeKeyService;
import org.dpppt.backend.sdk.data.gaen.GAENDataService;
import org.dpppt.backend.sdk.model.gaen.*;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention;
import org.dpppt.backend.sdk.ws.security.ValidateRequest;
import org.dpppt.backend.sdk.ws.security.ValidateRequest.InvalidDateException;
import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature;
import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature.ProtoSignatureWrapper;
import org.dpppt.backend.sdk.ws.util.ValidationUtils;
import org.dpppt.backend.sdk.ws.util.ValidationUtils.BadBatchReleaseTimeException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.Callable;
@Controller
@RequestMapping("/v1/gaen")
@Tag(name = "GAEN", description = "The GAEN endpoint for the mobile clients")
/**
* The GaenController defines the API endpoints for the mobile clients to access the GAEN functionality of the
* red backend.
* Clients can send new Exposed Keys, or request the existing Exposed Keys.
*/
public class GaenController {
private static final Logger logger = LoggerFactory.getLogger(GaenController.class);
private static final String FAKE_CODE = "112358132134";
private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER =
DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
.withZoneUTC().withLocale(Locale.ENGLISH);
// releaseBucketDuration is used to delay the publishing of Exposed Keys by splitting the database up into batches of keys
// in releaseBucketDuration duration. The current batch is never published, only previous batches are published.
private final Duration releaseBucketDuration;
private final Duration requestTime;
private final ValidateRequest validateRequest;
private final ValidationUtils validationUtils;
private final GAENDataService dataService;
private final FakeKeyService fakeKeyService;
private final Duration exposedListCacheControl;
private final PrivateKey secondDayKey;
private final ProtoSignature gaenSigner;
public GaenController(GAENDataService dataService, FakeKeyService fakeKeyService, ValidateRequest validateRequest,
ProtoSignature gaenSigner, ValidationUtils validationUtils, Duration releaseBucketDuration, Duration requestTime,
Duration exposedListCacheControl, PrivateKey secondDayKey) {
this.dataService = dataService;
this.fakeKeyService = fakeKeyService;
this.releaseBucketDuration = releaseBucketDuration;
this.validateRequest = validateRequest;
this.requestTime = requestTime;
this.validationUtils = validationUtils;
this.exposedListCacheControl = exposedListCacheControl;
this.secondDayKey = secondDayKey;
this.gaenSigner = gaenSigner;
}
@PostMapping(value = "/exposed")
@Loggable
@ResponseRetention(time = "application.response.retention.time.exposed")
@Transactional
@Operation(description = "Send exposed keys to server - includes a fix for the fact that GAEN doesn't give access to the current day's exposed key")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed keys have been stored in the database"),
@ApiResponse(responseCode = "400", description =
"- Invalid base64 encoding in GaenRequest" +
"- negative rolling period" +
"- fake claim with non-fake keys"),
@ApiResponse(responseCode = "403", description = "Authentication failed") })
public @ResponseBody Callable<ResponseEntity<String>> addExposed(
@Valid @RequestBody @Parameter(description = "The GaenRequest contains the SecretKey from the guessed infection date, the infection date itself, and some authentication data to verify the test result") GaenRequest gaenRequest,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server") Object principal) {
var now = Instant.now().toEpochMilli();
if (!this.validateRequest.isValid(principal)) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
List<GaenKey> nonFakeKeys = new ArrayList<>();
for (var key : gaenRequest.getGaenKeys()) {
if (!validationUtils.isValidBase64Key(key.getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (this.validateRequest.isFakeRequest(principal, key)
|| hasNegativeRollingPeriod(key)
|| hasInvalidKeyDate(principal, key)) {
continue;
}
if (key.getRollingPeriod().equals(0)) {
//currently only android seems to send 0 which can never be valid, since a non used key should not be submitted
//default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since
//this should not happen
key.setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod);
if (userAgent.toLowerCase().contains("ios")) {
logger.error("Received a rolling period of 0 for an iOS User-Agent");
}
}
nonFakeKeys.add(key);
}
if (principal instanceof Jwt && ((Jwt) principal).containsClaim("fake")
&& ((Jwt) principal).getClaimAsString("fake").equals("1")) {
Jwt token = (Jwt) principal;
if (FAKE_CODE.equals(token.getSubject())) {
logger.info("Claim is fake - subject: {}", token.getSubject());
} else if (!nonFakeKeys.isEmpty()) {
return () -> ResponseEntity.badRequest().body("Claim is fake but list contains non fake keys");
}
}
if (!nonFakeKeys.isEmpty()) {
dataService.upsertExposees(nonFakeKeys);
}
var delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes);
var delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()),
ZoneOffset.UTC);
var nowDay = LocalDate.now(ZoneOffset.UTC);
if (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) {
return () -> ResponseEntity.badRequest().body("delayedKeyDate date must be between yesterday and tomorrow");
}
var responseBuilder = ResponseEntity.ok();
if (principal instanceof Jwt) {
var originalJWT = (Jwt) principal;
var jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now()))
.setIssuer("dpppt-sdk-backend").setSubject(originalJWT.getSubject())
.setExpiration(Date
.from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48))))
.claim("scope", "currentDayExposed").claim("delayedKeyDate", gaenRequest.getDelayedKeyDate());
if (originalJWT.containsClaim("fake")) {
jwtBuilder.claim("fake", originalJWT.getClaim("fake"));
}
String jwt = jwtBuilder.signWith(secondDayKey).compact();
responseBuilder.header("Authorization", "Bearer " + jwt);
responseBuilder.header("X-Exposed-Token", "Bearer " + jwt);
}
Callable<ResponseEntity<String>> cb = () -> {
normalizeRequestTime(now);
return responseBuilder.body("OK");
};
return cb;
}
@PostMapping(value = "/exposednextday")
@Loggable
@Transactional
@Operation(description = "Allows the client to send the last exposed key of the infection to the backend server. The JWT must come from a previous call to /exposed")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed key has been stored in the backend"),
@ApiResponse(responseCode = "400", description =
"- Ivnalid base64 encoded Temporary Exposure Key" +
"- TEK-date does not match delayedKeyDAte claim in Jwt" +
"- TEK has negative rolling period"),
@ApiResponse(responseCode = "403", description = "No delayedKeyDate claim in authentication") })
public @ResponseBody Callable<ResponseEntity<String>> addExposedSecond(
@Valid @RequestBody @Parameter(description = "The last exposed key of the user") GaenSecondDay gaenSecondDay,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate") Object principal) {
var now = Instant.now().toEpochMilli();
if (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (principal instanceof Jwt && !((Jwt) principal).containsClaim("delayedKeyDate")) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body("claim does not contain delayedKeyDate");
}
if (principal instanceof Jwt) {
var jwt = (Jwt) principal;
var claimKeyDate = Integer.parseInt(jwt.getClaimAsString("delayedKeyDate"));
if (!gaenSecondDay.getDelayedKey().getRollingStartNumber().equals(claimKeyDate)) {
return () -> ResponseEntity.badRequest().body("keyDate does not match claim keyDate");
}
}
if (!this.validateRequest.isFakeRequest(principal, gaenSecondDay.getDelayedKey())) {
if (gaenSecondDay.getDelayedKey().getRollingPeriod().equals(0)) {
// currently only android seems to send 0 which can never be valid, since a non used key should not be submitted
// default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since
// this should not happen
gaenSecondDay.getDelayedKey().setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod);
if(userAgent.toLowerCase().contains("ios")) {
logger.error("Received a rolling period of 0 for an iOS User-Agent");
}
} else if(gaenSecondDay.getDelayedKey().getRollingPeriod() < 0) {
return () -> ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rolling Period MUST NOT be negative.");
}
List<GaenKey> keys = new ArrayList<>();
keys.add(gaenSecondDay.getDelayedKey());
dataService.upsertExposees(keys);
}
return () -> {
normalizeRequestTime(now);
return ResponseEntity.ok().body("OK");
};
}
@GetMapping(value = "/exposed/{keyDate}", produces = "application/zip")
@Loggable
@Operation(description = "Request the exposed key from a given date")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"),
@ApiResponse(responseCode = "400", description =
"- invalid starting key date, doesn't point to midnight UTC" +
"- _publishedAfter_ is not at the beginning of a batch release time, currently 2h")})
public @ResponseBody ResponseEntity<byte[]> getExposedKeys(
@PathVariable @Parameter(description = "Requested date for Exposed Keys retrieval, in milliseconds since Unix epoch (1970-01-01). It must indicate the beginning of a TEKRollingPeriod, currently midnight UTC.", example = "1593043200000") long keyDate,
@RequestParam(required = false) @Parameter(description = "Restrict returned Exposed Keys to dates after this parameter. Given in milliseconds since Unix epoch (1970-01-01).", example = "1593043200000") Long publishedafter)
throws BadBatchReleaseTimeException, IOException, InvalidKeyException, SignatureException,
NoSuchAlgorithmException {
if (!validationUtils.isValidKeyDate(keyDate)) {
return ResponseEntity.notFound().build();
}
if (publishedafter != null && !validationUtils.isValidBatchReleaseTime(publishedafter)) {
return ResponseEntity.notFound().build();
}
long now = System.currentTimeMillis();
// calculate exposed until bucket
long publishedUntil = now - (now % releaseBucketDuration.toMillis());
DateTime dateTime = new DateTime(publishedUntil + releaseBucketDuration.toMillis() - 1, DateTimeZone.UTC);
var exposedKeys = dataService.getSortedExposedForKeyDate(keyDate, publishedafter, publishedUntil);
exposedKeys = fakeKeyService.fillUpKeys(exposedKeys, publishedafter, keyDate);
if (exposedKeys.isEmpty()) {
return ResponseEntity.noContent()//.cacheControl(CacheControl.maxAge(exposedListCacheControl))
.header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil))
.header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime))
.build();
}
ProtoSignatureWrapper payload = gaenSigner.getPayload(exposedKeys);
return ResponseEntity.ok()//.cacheControl(CacheControl.maxAge(exposedListCacheControl))
.header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil))
.header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime))
.body(payload.getZip());
}
@GetMapping(value = "/buckets/{dayDateStr}")
@Loggable
@Operation(description = "Request the available release batch times for a given day")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"),
@ApiResponse(responseCode = "400", description = "invalid starting key date, points outside of the retention range")})
public @ResponseBody ResponseEntity<DayBuckets> getBuckets(
@PathVariable @Parameter(description = "Starting date for exposed key retrieval, as ISO-8601 format", example = "2020-06-27") String dayDateStr) {
var atStartOfDay = LocalDate.parse(dayDateStr).atStartOfDay().toInstant(ZoneOffset.UTC)
.atOffset(ZoneOffset.UTC);
var end = atStartOfDay.plusDays(1);
var now = Instant.now().atOffset(ZoneOffset.UTC);
if (!validationUtils.isDateInRange(atStartOfDay)) {
return ResponseEntity.notFound().build();
}
var relativeUrls = new ArrayList<String>();
var dayBuckets = new DayBuckets();
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
dayBuckets.setDay(dayDateStr).setRelativeUrls(relativeUrls).setDayTimestamp(atStartOfDay.toInstant().toEpochMilli());
while (atStartOfDay.toInstant().toEpochMilli() < Math.min(now.toInstant().toEpochMilli(),
end.toInstant().toEpochMilli())) {
relativeUrls.add(controllerMapping + "/exposed" + "/" + atStartOfDay.toInstant().toEpochMilli());
atStartOfDay = atStartOfDay.plus(this.releaseBucketDuration);
}
return ResponseEntity.ok(dayBuckets);
}
private void normalizeRequestTime(long now) {
long after = Instant.now().toEpochMilli();
long duration = after - now;
try {
Thread.sleep(Math.max(requestTime.minusMillis(duration).toMillis(), 0));
} catch (Exception ex) {
logger.error("Couldn't equalize request time: {}", ex.toString());
}
}
private boolean hasNegativeRollingPeriod(GaenKey key) {
Integer rollingPeriod = key.getRollingPeriod();
if (key.getRollingPeriod() < 0) {
logger.error("Detected key with negative rolling period {}", rollingPeriod);
return true;
} else {
return false;
}
}
private boolean hasInvalidKeyDate(Object principal, GaenKey key) {
try {
this.validateRequest.getKeyDate(principal, key);
}
catch (InvalidDateException invalidDate) {
logger.error(invalidDate.getLocalizedMessage());
return true;
}
return false;
}
@ExceptionHandler({IllegalArgumentException.class, InvalidDateException.class, JsonProcessingException.class,
MethodArgumentNotValidException.class, BadBatchReleaseTimeException.class, DateTimeParseException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Object> invalidArguments(Exception ex) {
logger.error("Exception ({}): {}", ex.getClass().getSimpleName(), ex.getMessage(), ex);
return ResponseEntity.badRequest().build();
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_4348_2
|
crossvul-java_data_bad_3055_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* 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.
*/
package jenkins.model;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.init.TerminatorFinder;
import hudson.lifecycle.Lifecycle;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.logging.LogRecorderManager;
import hudson.markup.EscapedMarkupFormatter;
import hudson.markup.MarkupFormatter;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.LoadStatistics;
import hudson.model.ManagementLink;
import hudson.model.Messages;
import hudson.model.ModifiableViewGroup;
import hudson.model.NoFingerprintMatch;
import hudson.model.Node;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.NamingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static hudson.Util.*;
import static hudson.init.InitMilestone.*;
import hudson.util.LogTaskListener;
import static java.util.logging.Level.*;
import static javax.servlet.http.HttpServletResponse.*;
import org.kohsuke.stapler.WebMethod;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Jenkins whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Jenkins.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Jenkins.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Jenkins system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Legacy store of the set of installed cluster nodes.
* @deprecated in favour of {@link Nodes}
*/
@Deprecated
protected transient volatile NodeList slaves;
/**
* The holder of the set of installed cluster nodes.
*
* @since 1.607
*/
private transient final Nodes nodes = new Nodes(this);
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Jenkins.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
@CheckForNull Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public @CheckForNull Jenkins getInstance() {
return theInstance;
}
};
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstance()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
*/
public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Gets the {@link Jenkins} singleton.
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
*/
@CLIResolver
@CheckForNull
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c, new LogTaskListener(LOGGER, INFO));
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
@Deprecated
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
@Deprecated
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
@Deprecated
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Jenkins by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/** @deprecated Use {@link SCMListener#all} instead. */
@Deprecated
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public @Nonnull MarkupFormatter getMarkupFormatter() {
MarkupFormatter f = markupFormatter;
return f != null ? f : new EscapedMarkupFormatter();
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Jenkins.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Jenkins.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Jenkins forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
@Override public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return lhs.getName().compareTo(rhs.getName());
}
});
return r;
}
@CLIResolver
public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public synchronized List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Replaces all JDK installations with those from the given collection.
*
* Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to
* set JDK installations from external code.
*/
@Restricted(NoExternalUse.class)
public synchronized void setJDKs(Collection<? extends JDK> jdks) {
this.jdks = new ArrayList<JDK>(jdks);
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Jenkins.
*/
public @CheckForNull Node getNode(String name) {
return nodes.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return nodes.getNodes();
}
/**
* Get the {@link Nodes} object that handles maintaining individual {@link Node}s.
* @return The Nodes object.
*/
@Restricted(NoExternalUse.class)
public Nodes getNodesObject() {
// TODO replace this with something better when we properly expose Nodes.
return nodes;
}
/**
* Adds one more {@link Node} to Jenkins.
*/
public void addNode(Node n) throws IOException {
nodes.addNode(n);
}
/**
* Removes a {@link Node} from Jenkins.
*/
public void removeNode(@Nonnull Node n) throws IOException {
nodes.removeNode(n);
}
public void setNodes(final List<? extends Node> n) throws IOException {
nodes.setNodes(n);
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
/*package*/ void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
// do essentially what expandVariablesForDirectory does, without an Item
String replacedValue = expandVariablesForDirectory(value,
"doCheckRawBuildsDir-Marker:foo",
Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo");
File replacedFile = new File(replacedValue);
if (!replacedFile.isAbsolute()) {
return FormValidation.error(value + " does not resolve to an absolute path");
}
if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) {
return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects");
}
if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) {
// make sure platform can handle colon
try {
File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar");
tmp.delete();
} catch (IOException e) {
return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead");
}
}
File d = new File(replacedValue);
if (!d.isDirectory()) {
// if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to
d = d.getParentFile();
while (!d.exists()) {
d = d.getParentFile();
}
if (!d.canWrite()) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
}
return FormValidation.ok();
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}.
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link #getRootUrlFromRequest}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /}
* @since 1.66
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public @Nullable String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}.
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* <p>Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy which has not been fully configured.
* Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set.
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a>
* shows some examples of configuration.
* @since 1.263
*/
public @Nonnull String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
int index = host.indexOf(':');
int port = req.getServerPort();
if (index == -1) {
// Almost everyone else except Nginx put the host and port in separate headers
buf.append(host);
} else {
// Nginx uses the same spec as for the Host header, i.e. hostanme:port
buf.append(host.substring(0, index));
if (index + 1 < host.length()) {
try {
port = Integer.parseInt(host.substring(index + 1));
} catch (NumberFormatException e) {
// ignore
}
}
// but if a user has configured Nginx with an X-Forwarded-Port, that will win out.
}
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath()));
}
@Restricted(NoExternalUse.class)
static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) {
return Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(),
"ITEM_ROOTDIR", itemRootDir,
"ITEM_FULLNAME", itemFullName, // legacy, deprecated
"ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
@Restricted(NoExternalUse.class)
public void setRawBuildsDir(String buildsDir) {
this.buildsDir = buildsDir;
}
@Override public @Nonnull FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new MasterToSlaveCallable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Jenkins would have to have crumb in it to protect
* Jenkins from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes in Jenkins.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
IdStrategy oldUserIdStrategy = this.securityRealm == null
? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load
: this.securityRealm.getUserIdStrategy();
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) {
User.rekey();
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
* @see ExtensionList#lookup
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Jenkins is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
if (this.numExecutors != n) {
this.numExecutors = n;
updateComputerList();
save();
}
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override public TopLevelItem getItem(String name) throws AccessDeniedException {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
* @throws AccessDeniedException as per {@link ItemGroup#getItem}
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean), {@link User#getById(String, boolean)}
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Jenkins by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(job, oldName, newName);
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
}
@Override public boolean canAdd(TopLevelItem item) {
return true;
}
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
items.put(name, item);
return item;
}
@Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException {
items.remove(item.getName());
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles();
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) {
nodes.setNodes(slaves);
slaves = null;
} else {
nodes.load();
}
clouds.setOwner(Jenkins.this);
}
});
for (final File subdir : subdirs) {
g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
if(!Items.getConfigFile(subdir).exists()) {
//Does not have job config file, so it is not a jenkins job hence skip it
return;
}
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : nodes.getNodes())
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Jenkins and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
} catch (InterruptedException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
e.printStackTrace();
} catch (ReactorException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
}
final Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
// JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
}
});
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
java.util.Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
Timer.shutdown();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
setJDKs(req.bindJSONToList(JDK.class, json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
@RequirePOST
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
@RequirePOST // TODO does not seem to work on _either_ overload!
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
@RequirePOST
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
long waitUntil = timeout;
if (timeout > 0) waitUntil += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < waitUntil)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
@RequirePOST // TODO the cancel link needs to be updated accordingly
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r));
}
@RequirePOST
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
@RequirePOST
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if(".".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName("."));
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
* Used only by {@link LegacySecurityRealm}.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
// TODO fire something in SecurityListener?
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String user = getAuthentication().getName();
securityRealm.doLogout(req, rsp);
SecurityListener.fireLoggedOut(user);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
@RequirePOST
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,FilePath.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Jenkins, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Jenkins for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
@Extension @Restricted(NoExternalUse.class)
public static class MasterRestartNotifyier extends RestartListener {
@Override
public void onRestart() {
Computer computer = Jenkins.getInstance().toComputer();
if (computer == null) return;
RestartCause cause = new RestartCause();
for (ComputerListener listener: ComputerListener.all()) {
listener.onOffline(computer, cause);
}
}
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return true;
}
private static class RestartCause extends OfflineCause.SimpleOfflineCause {
protected RestartCause() {
super(Messages._Jenkins_IsRestarting());
}
}
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
@RequirePOST
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
@RequirePOST
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static @Nonnull Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
if (channel == null) {
throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if (getSecurityRealm().allowsSignup()) {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
return;
}
req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
@RequirePOST
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
@RequirePOST
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals(JDK.DEFAULT_NAME))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
@Deprecated
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
}, 500, TimeUnit.MILLISECONDS);
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/error")
|| rest.startsWith("/oops")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
@Override
public Boolean isUnix() {
return !Functions.isWindows();
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@WebMethod(name="config.xml")
@Override
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return FilePath.localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
@RequirePOST
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*
* @deprecated as of 1.558
* Use {@link FilePath#localChannel}
*/
@Deprecated
public static final LocalChannel localChannel = FilePath.localChannel;
}
/**
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Jenkins.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM;
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Jenkins.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* @deprecated No longer used.
*/
@Deprecated
public static boolean FLYWEIGHT_SUPPORT = true;
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS;
static {
try {
ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
XSTREAM = XSTREAM2 = new XStream2();
XSTREAM.alias("jenkins", Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk", JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
XSTREAM2.addCriticalField(Jenkins.class, "securityRealm");
XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy");
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS != null;
assert ADMINISTER != null;
} catch (RuntimeException e) {
// when loaded on a slave and this fails, subsequent NoClassDefFoundError will fail to chain the cause.
// see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847
// As we don't know where the first exception will go, let's also send this to logging so that
// we have a known place to look at.
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
} catch (Error e) {
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_3055_0
|
crossvul-java_data_bad_1545_0
|
/*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.server.network.protocol.http;
import com.orientechnologies.common.concur.resource.OSharedResourceAbstract;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TimerTask;
/**
* Handles the HTTP sessions such as a real HTTP Server.
*
* @author Luca Garulli
*/
public class OHttpSessionManager extends OSharedResourceAbstract {
private static final OHttpSessionManager instance = new OHttpSessionManager();
private Map<String, OHttpSession> sessions = new HashMap<String, OHttpSession>();
private int expirationTime;
private Random random = new Random();
protected OHttpSessionManager() {
expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;
Orient.instance().scheduleTask(new TimerTask() {
@Override
public void run() {
final int expired = checkSessionsValidity();
if (expired > 0)
OLogManager.instance().debug(this, "Removed %d session because expired", expired);
}
}, expirationTime, expirationTime);
}
public int checkSessionsValidity() {
int expired = 0;
acquireExclusiveLock();
try {
final long now = System.currentTimeMillis();
Entry<String, OHttpSession> s;
for (Iterator<Map.Entry<String, OHttpSession>> it = sessions.entrySet().iterator(); it.hasNext();) {
s = it.next();
if (now - s.getValue().getUpdatedOn() > expirationTime) {
// REMOVE THE SESSION
it.remove();
expired++;
}
}
} finally {
releaseExclusiveLock();
}
return expired;
}
public OHttpSession[] getSessions() {
acquireSharedLock();
try {
return (OHttpSession[]) sessions.values().toArray(new OHttpSession[sessions.size()]);
} finally {
releaseSharedLock();
}
}
public OHttpSession getSession(final String iId) {
acquireSharedLock();
try {
final OHttpSession sess = sessions.get(iId);
if (sess != null)
sess.updateLastUpdatedOn();
return sess;
} finally {
releaseSharedLock();
}
}
public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {
acquireExclusiveLock();
try {
final String id = "OS" + System.currentTimeMillis() + random.nextLong();
sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));
return id;
} finally {
releaseExclusiveLock();
}
}
public OHttpSession removeSession(final String iSessionId) {
acquireExclusiveLock();
try {
return sessions.remove(iSessionId);
} finally {
releaseExclusiveLock();
}
}
public int getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(int expirationTime) {
this.expirationTime = expirationTime;
}
public static OHttpSessionManager getInstance() {
return instance;
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_1545_0
|
crossvul-java_data_good_1503_1
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.security.negotiation;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.ReferralException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.CompositeName;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.jboss.security.SimpleGroup;
import org.jboss.security.negotiation.common.CommonLoginModule;
import org.jboss.security.negotiation.prototype.DecodeAction;
import org.jboss.security.vault.SecurityVaultUtil;
import org.jboss.security.vault.SecurityVaultException;
/**
* Another LDAP LoginModule to take into account requirements
* for different authentication mechanisms and full support
* for password-stacking set to useFirstPass.
*
* This is essentially a complete refactoring of the LdapExtLoginModule
* but with enough restructuring to separate out the three login steps: -
* -1 Find the user
* -2 Authenticate as the user
* -3 Find the users roles
* Configuration should allow for any of the three actions to be
* skipped based on the requirements for the environment making
* use of this login module.
*
*
* @author darran.lofthouse@jboss.com
* @since 3rd July 2008
*/
public class AdvancedLdapLoginModule extends CommonLoginModule
{
/*
* Configuration Option Constants
*/
// Search Context Settings
private static final String BIND_AUTHENTICATION = "bindAuthentication";
private static final String BIND_DN = "bindDN";
private static final String BIND_CREDENTIAL = "bindCredential";
private static final String SECURITY_DOMAIN = "jaasSecurityDomain";
// User Search Settings
private static final String BASE_CTX_DN = "baseCtxDN";
private static final String BASE_FILTER = "baseFilter";
private static final String SEARCH_TIME_LIMIT = "searchTimeLimit";
// Role Search Settings
private static final String ROLES_CTS_DN = "rolesCtxDN";
private static final String ROLE_FILTER = "roleFilter";
private static final String RECURSE_ROLES = "recurseRoles";
private static final String ROLE_ATTRIBUTE_ID = "roleAttributeID";
private static final String ROLE_ATTRIBUTE_IS_DN = "roleAttributeIsDN";
private static final String ROLE_NAME_ATTRIBUTE_ID = "roleNameAttributeID";
private static final String ROLE_SEARCH_SCOPE = "searchScope";
private static final String REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK = "referralUserAttributeIDToCheck";
// Authentication Settings
private static final String ALLOW_EMPTY_PASSWORD = "allowEmptyPassword";
/*
* Other Constants
*/
private static final String AUTH_TYPE_GSSAPI = "GSSAPI";
private static final String AUTH_TYPE_SIMPLE = "simple";
private static final String DEFAULT_LDAP_CTX_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private static final String DEFAULT_URL = "ldap://localhost:389";
private static final String DEFAULT_SSL_URL = "ldap://localhost:686";
private static final String PROTOCOL_SSL = "SSL";
private static final String OBJECT_SCOPE = "OBJECT_SCOPE";
private static final String ONELEVEL_SCOPE = "ONELEVEL_SCOPE";
private static final String SUBTREE_SCOPE = "SUBTREE_SCOPE";
private static final String[] ALL_VALID_OPTIONS =
{
BIND_AUTHENTICATION,BIND_DN,BIND_CREDENTIAL,SECURITY_DOMAIN,
BASE_CTX_DN,BASE_FILTER,SEARCH_TIME_LIMIT,
ROLES_CTS_DN,ROLE_FILTER,RECURSE_ROLES,ROLE_ATTRIBUTE_ID,ROLE_ATTRIBUTE_IS_DN,ROLE_NAME_ATTRIBUTE_ID,ROLE_SEARCH_SCOPE,
ALLOW_EMPTY_PASSWORD,REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK,
Context.INITIAL_CONTEXT_FACTORY,
Context.OBJECT_FACTORIES,
Context.STATE_FACTORIES,
Context.URL_PKG_PREFIXES,
Context.PROVIDER_URL,
Context.DNS_URL,
Context.AUTHORITATIVE,
Context.BATCHSIZE,
Context.REFERRAL,
Context.SECURITY_PROTOCOL,
Context.SECURITY_AUTHENTICATION,
Context.SECURITY_PRINCIPAL,
Context.SECURITY_CREDENTIALS,
Context.LANGUAGE,
Context.APPLET
};
/*
* Configuration Options
*/
// Search Context Settings
protected String bindAuthentication;
protected String bindDn;
protected String bindCredential;
protected String jaasSecurityDomain;
// User Search Settings
protected String baseCtxDN;
protected String baseFilter;
protected int searchTimeLimit = 10000;
protected SearchControls userSearchControls;
// Role Search Settings
protected String rolesCtxDN;
protected String roleFilter;
protected boolean recurseRoles;
protected SearchControls roleSearchControls;
protected String roleAttributeID;
protected boolean roleAttributeIsDN;
protected String roleNameAttributeID;
protected String referralUserAttributeIDToCheck = null;
// Authentication Settings
protected boolean allowEmptyPassword;
// inner state fields
private String referralUserDNToCheck;
/*
* Module State
*/
private SimpleGroup userRoles = new SimpleGroup("Roles");
private Set<String> processedRoleDNs = new HashSet<String>();
private boolean trace;
@Override
public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
{
addValidOptions(ALL_VALID_OPTIONS);
super.initialize(subject, handler, sharedState, options);
trace = log.isTraceEnabled();
// Search Context Settings
bindAuthentication = (String) options.get(BIND_AUTHENTICATION);
bindDn = (String) options.get(BIND_DN);
bindCredential = (String) options.get(BIND_CREDENTIAL);
try
{
//Check if the credential is vaultified
if(bindCredential != null && SecurityVaultUtil.isVaultFormat(bindCredential))
{
bindCredential = SecurityVaultUtil.getValueAsString(bindCredential);
}
}
catch (SecurityVaultException e)
{
log.warn("Unable to obtain bindCredentials from Vault: ", e);
}
jaasSecurityDomain = (String) options.get(SECURITY_DOMAIN);
// User Search Settings
baseCtxDN = (String) options.get(BASE_CTX_DN);
baseFilter = (String) options.get(BASE_FILTER);
String temp = (String) options.get(SEARCH_TIME_LIMIT);
if (temp != null)
{
try
{
searchTimeLimit = Integer.parseInt(temp);
}
catch (NumberFormatException e)
{
log.warn("Failed to parse: " + temp + ", using searchTimeLimit=" + searchTimeLimit);
}
}
userSearchControls = new SearchControls();
userSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
userSearchControls.setReturningAttributes(new String[0]);
userSearchControls.setTimeLimit(searchTimeLimit);
rolesCtxDN = (String) options.get(ROLES_CTS_DN);
roleFilter = (String) options.get(ROLE_FILTER);
referralUserAttributeIDToCheck = (String) options.get(REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK);
temp = (String) options.get(RECURSE_ROLES);
recurseRoles = Boolean.parseBoolean(temp);
int searchScope = SearchControls.SUBTREE_SCOPE;
temp = (String) options.get(ROLE_SEARCH_SCOPE);
if (OBJECT_SCOPE.equalsIgnoreCase(temp))
{
searchScope = SearchControls.OBJECT_SCOPE;
}
else if (ONELEVEL_SCOPE.equalsIgnoreCase(temp))
{
searchScope = SearchControls.ONELEVEL_SCOPE;
}
if (SUBTREE_SCOPE.equalsIgnoreCase(temp))
{
searchScope = SearchControls.SUBTREE_SCOPE;
}
roleSearchControls = new SearchControls();
roleSearchControls.setSearchScope(searchScope);
roleSearchControls.setTimeLimit(searchTimeLimit);
roleAttributeID = (String) options.get(ROLE_ATTRIBUTE_ID);
temp = (String) options.get(ROLE_ATTRIBUTE_IS_DN);
roleAttributeIsDN = Boolean.parseBoolean(temp);
roleNameAttributeID = (String) options.get(ROLE_NAME_ATTRIBUTE_ID);
ArrayList<String> roleSearchAttributeList = new ArrayList<String>(3);
if (roleAttributeID != null)
{
roleSearchAttributeList.add(roleAttributeID);
}
if (roleNameAttributeID != null)
{
roleSearchAttributeList.add(roleNameAttributeID);
}
if (referralUserAttributeIDToCheck != null)
{
roleSearchAttributeList.add(referralUserAttributeIDToCheck);
}
roleSearchControls.setReturningAttributes(roleSearchAttributeList.toArray(new String[0]));
temp = (String) options.get(ALLOW_EMPTY_PASSWORD);
allowEmptyPassword = Boolean.parseBoolean(temp);
}
@Override
public boolean login() throws LoginException
{
Object result = null;
AuthorizeAction action = new AuthorizeAction();
if (AUTH_TYPE_GSSAPI.equals(bindAuthentication))
{
log.trace("Using GSSAPI to connect to LDAP");
LoginContext lc = new LoginContext(jaasSecurityDomain);
lc.login();
Subject serverSubject = lc.getSubject();
if (log.isDebugEnabled())
{
log.debug("Subject = " + serverSubject);
log.debug("Logged in '" + lc + "' LoginContext");
}
result = Subject.doAs(serverSubject, action);
lc.logout();
}
else
{
result = action.run();
}
if (result instanceof LoginException)
{
throw (LoginException) result;
}
return ((Boolean) result).booleanValue();
}
@Override
protected Group[] getRoleSets() throws LoginException
{
Group[] roleSets =
{userRoles};
return roleSets;
}
protected Boolean innerLogin() throws LoginException
{
// Obtain the username and password
processIdentityAndCredential();
if (trace) {
log.trace("Identity - " + getIdentity().getName());
}
// Initialise search ctx
String bindCredential = this.bindCredential;
if (AUTH_TYPE_GSSAPI.equals(bindAuthentication) == false)
{
if (jaasSecurityDomain != null && jaasSecurityDomain.length() > 0)
{
try
{
ObjectName serviceName = new ObjectName(jaasSecurityDomain);
char[] tmp = DecodeAction.decode(bindCredential, serviceName);
bindCredential = new String(tmp);
}
catch (Exception e)
{
LoginException le = new LoginException("Unable to decode bindCredential");
le.initCause(e);
throw le;
}
}
}
LdapContext searchContext = null;
try
{
searchContext = constructLdapContext(null, bindDn, bindCredential, bindAuthentication);
log.debug("Obtained LdapContext");
// Search for user in LDAP
String userDN = findUserDN(searchContext);
if (referralUserAttributeIDToCheck != null)
{
if (isUserDnAbsolute(userDN))
{
referralUserDNToCheck = localUserDN(userDN);
}
else
{
referralUserDNToCheck = userDN;
}
}
// If authentication required authenticate as user
if (super.loginOk == false)
{
authenticate(userDN);
}
if (super.loginOk)
{
// Search for roles in LDAP
rolesSearch(searchContext, userDN);
}
}
finally
{
if (searchContext != null)
{
try
{
searchContext.close();
}
catch (NamingException e)
{
log.warn("Error closing context", e);
}
}
}
return Boolean.valueOf(super.loginOk);
}
private Properties constructLdapContextEnvironment(String namingProviderURL, String principalDN, Object credential, String authentication)
{
Properties env = createBaseProperties();
// Set defaults for key values if they are missing
String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
if (factoryName == null)
{
factoryName = DEFAULT_LDAP_CTX_FACTORY;
env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
}
// If this method is called with an authentication type then use that.
if (authentication != null && authentication.length() > 0)
{
env.setProperty(Context.SECURITY_AUTHENTICATION, authentication);
}
else
{
String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
if (authType == null)
env.setProperty(Context.SECURITY_AUTHENTICATION, AUTH_TYPE_SIMPLE);
}
String providerURL = null;
if (namingProviderURL != null)
{
providerURL = namingProviderURL;
}
else
{
providerURL = (String) options.get(Context.PROVIDER_URL);
}
String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
if (providerURL == null)
{
if (PROTOCOL_SSL.equals(protocol))
{
providerURL = DEFAULT_SSL_URL;
}
else
{
providerURL = DEFAULT_URL;
}
}
env.setProperty(Context.PROVIDER_URL, providerURL);
// Assume the caller of this method has checked the requirements for the principal and
// credentials.
if (principalDN != null)
env.setProperty(Context.SECURITY_PRINCIPAL, principalDN);
if (credential != null)
env.put(Context.SECURITY_CREDENTIALS, credential);
traceLdapEnv(env);
return env;
}
protected LdapContext constructLdapContext(String namingProviderURL, String dn, Object credential, String authentication)
throws LoginException
{
try
{
Properties env = constructLdapContextEnvironment(namingProviderURL, dn, credential, authentication);
return new InitialLdapContext(env, null);
}
catch (NamingException e)
{
LoginException le = new LoginException("Unable to create new InitialLdapContext");
le.initCause(e);
throw le;
}
}
protected Properties createBaseProperties()
{
Properties env = new Properties();
Iterator iter = options.entrySet().iterator();
while (iter.hasNext())
{
Entry entry = (Entry) iter.next();
env.put(entry.getKey(), entry.getValue());
}
return env;
}
protected String findUserDN(LdapContext ctx) throws LoginException
{
if (baseCtxDN == null)
{
return getIdentity().getName();
}
try
{
NamingEnumeration results = null;
Object[] filterArgs =
{getIdentity().getName()};
LdapContext ldapCtx = ctx;
boolean referralsLeft = true;
SearchResult sr = null;
while (referralsLeft)
{
try
{
results = ldapCtx.search(baseCtxDN, baseFilter, filterArgs, userSearchControls);
while (results.hasMore())
{
sr = (SearchResult) results.next();
break;
}
referralsLeft = false;
}
catch (ReferralException e)
{
ldapCtx = (LdapContext) e.getReferralContext();
if (results != null)
{
results.close();
}
}
}
if (sr == null)
{
results.close();
throw new LoginException("Search of baseDN(" + baseCtxDN + ") found no matches");
}
String name = sr.getName();
String userDN = null;
if (sr.isRelative() == true)
{
userDN = new CompositeName(name).get(0) + "," + baseCtxDN;
}
else
{
userDN = sr.getName();
}
results.close();
results = null;
if (trace) {
log.trace("findUserDN - " + userDN);
}
return userDN;
}
catch (NamingException e)
{
LoginException le = new LoginException("Unable to find user DN");
le.initCause(e);
throw le;
}
}
private void referralAuthenticate(String absoluteName, Object credential)
throws LoginException
{
URI uri;
try
{
uri = new URI(absoluteName);
}
catch (URISyntaxException e)
{
LoginException le = new LoginException("Unable to find user DN in referral LDAP");
le.initCause(e);
throw le;
}
String name = localUserDN(absoluteName);
String namingProviderURL = uri.getScheme() + "://" + uri.getAuthority();
InitialLdapContext refCtx = null;
try
{
Properties refEnv = constructLdapContextEnvironment(namingProviderURL, name, credential, null);
refCtx = new InitialLdapContext(refEnv, null);
refCtx.close();
}
catch (NamingException e)
{
LoginException le = new LoginException("Unable to create referral LDAP context");
le.initCause(e);
throw le;
}
}
private String localUserDN(String absoluteDN) {
try
{
URI userURI = new URI(absoluteDN);
return userURI.getPath().substring(1);
}
catch (URISyntaxException e)
{
return null;
}
}
/**
* Checks whether userDN is absolute URI, like the one pointing to an LDAP referral.
* @param userDN
* @return
*/
private Boolean isUserDnAbsolute(String userDN) {
try
{
URI userURI = new URI(userDN);
return userURI.isAbsolute();
}
catch (URISyntaxException e)
{
return false;
}
}
protected void authenticate(String userDN) throws LoginException
{
char[] credential = getCredential();
if (credential.length == 0)
{
if (allowEmptyPassword == false)
{
log.trace("Rejecting empty password.");
return;
}
}
if (isUserDnAbsolute(userDN))
{
// user object resides in referral
referralAuthenticate(userDN, credential);
}
else
{
// non referral user authentication
try
{
LdapContext authContext = constructLdapContext(null, userDN, credential, null);
authContext.close();
}
catch (NamingException ne)
{
if (log.isDebugEnabled())
log.debug("Authentication failed - " + ne.getMessage());
LoginException le = new LoginException("Authentication failed");
le.initCause(ne);
throw le;
}
}
super.loginOk = true;
if (getUseFirstPass() == true)
{ // Add the username and password to the shared state map
sharedState.put("javax.security.auth.login.name", getIdentity().getName());
sharedState.put("javax.security.auth.login.password", credential);
}
}
protected void rolesSearch(LdapContext searchContext, String dn) throws LoginException
{
/*
* The distinguished name passed into this method is expected to be unquoted.
*/
Object[] filterArgs = null;
if (isUserDnAbsolute(dn))
{
filterArgs = new Object[] {getIdentity().getName(), localUserDN(dn)};
}
else
{
filterArgs = new Object[] {getIdentity().getName(), dn};
}
NamingEnumeration results = null;
try
{
if (trace) {
log.trace("rolesCtxDN=" + rolesCtxDN + " roleFilter=" + roleFilter + " filterArgs[0]=" + filterArgs[0]
+ " filterArgs[1]=" + filterArgs[1]);
}
if (roleFilter != null && roleFilter.length() > 0)
{
boolean referralsExist = true;
while (referralsExist)
{
try
{
results = searchContext.search(rolesCtxDN, roleFilter, filterArgs, roleSearchControls);
while (results.hasMore())
{
SearchResult sr = (SearchResult) results.next();
String resultDN = null;
if (sr.isRelative())
{
resultDN = canonicalize(sr.getName());
}
else
{
resultDN = sr.getNameInNamespace();
}
/*
* By this point if the distinguished name needs to be quoted for attribute
* searches it will have been already.
*/
obtainRole(searchContext, resultDN, sr);
}
referralsExist = false;
}
catch (ReferralException e)
{
searchContext = (LdapContext) e.getReferralContext();
}
}
}
else
{
/*
* As there was no search based on the distinguished name it would not have been
* auto-quoted - do that here to be safe.
*/
obtainRole(searchContext, quoted(dn), null);
}
}
catch (NamingException e)
{
LoginException le = new LoginException("Error finding roles");
le.initCause(e);
throw le;
}
finally
{
if (results != null)
{
try
{
results.close();
}
catch (NamingException e)
{
log.warn("Problem closing results", e);
}
}
}
}
private String quoted(final String dn) {
String temp = dn.trim();
if (temp.startsWith("\"") && temp.endsWith("\"")) {
return temp;
}
return "\"" + temp + "\"";
}
protected void obtainRole(LdapContext searchContext, String dn, SearchResult sr) throws NamingException, LoginException
{
if (trace) {
log.trace("rolesSearch resultDN = " + dn);
}
String[] attrNames =
{roleAttributeID};
Attributes result = null;
if (sr == null || sr.isRelative())
{
result = searchContext.getAttributes(dn, attrNames);
}
else
{
result = getAttributesFromReferralEntity(sr);
}
if (result != null && result.size() > 0)
{
Attribute roles = result.get(roleAttributeID);
for (int n = 0; n < roles.size(); n++)
{
String roleName = (String) roles.get(n);
if (roleAttributeIsDN)
{
// Query the roleDN location for the value of roleNameAttributeID
String roleDN = "\"" + roleName + "\"";
loadRoleByRoleNameAttributeID(searchContext, roleDN);
recurseRolesSearch(searchContext, roleName);
}
else
{
// The role attribute value is the role name
addRole(roleName);
}
}
}
}
private Attributes getAttributesFromReferralEntity(SearchResult sr) throws NamingException
{
Attributes result = sr.getAttributes();
boolean chkSuccessful = false;
if (referralUserAttributeIDToCheck != null)
{
Attribute usersToCheck = result.get(referralUserAttributeIDToCheck);
for (int i = 0; usersToCheck != null && i < usersToCheck.size(); i++)
{
String userDNToCheck = (String) usersToCheck.get(i);
if (userDNToCheck.equals(referralUserDNToCheck))
{
chkSuccessful = true;
break;
}
if (userDNToCheck.equals(getIdentity().getName()))
{
chkSuccessful = true;
break;
}
}
}
return (chkSuccessful ? result : null);
}
protected void loadRoleByRoleNameAttributeID(LdapContext searchContext, String roleDN)
{
String[] returnAttribute = {roleNameAttributeID};
if (trace) {
log.trace("Using roleDN: " + roleDN);
}
try
{
Attributes result2 = searchContext.getAttributes(roleDN, returnAttribute);
Attribute roles2 = result2.get(roleNameAttributeID);
if (roles2 != null)
{
for (int m = 0; m < roles2.size(); m++)
{
String roleName = (String) roles2.get(m);
addRole(roleName);
}
}
}
catch (NamingException e)
{
if (trace) {
log.trace("Failed to query roleNameAttrName", e);
}
}
}
protected void recurseRolesSearch(LdapContext searchContext, String roleDN) throws LoginException
{
if (recurseRoles)
{
if (processedRoleDNs.contains(roleDN) == false)
{
processedRoleDNs.add(roleDN);
if (trace) {
log.trace("Recursive search for '" + roleDN + "'");
}
rolesSearch(searchContext, roleDN);
}
else
{
if (trace) {
log.trace("Already visited role '" + roleDN + "' ending recursion.");
}
}
}
}
protected void traceLdapEnv(Properties env)
{
if (trace)
{
Properties tmp = new Properties();
tmp.putAll(env);
String credentials = tmp.getProperty(Context.SECURITY_CREDENTIALS);
String bindCredential = tmp.getProperty(BIND_CREDENTIAL);
if (credentials != null && credentials.length() > 0) {
tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
}
if (bindCredential != null && bindCredential.length() > 0) {
tmp.setProperty(BIND_CREDENTIAL, "***");
}
log.trace("Logging into LDAP server, env=" + tmp.toString());
}
}
protected String canonicalize(String searchResult)
{
String result = searchResult;
int len = searchResult.length();
if (searchResult.endsWith("\""))
{
result = searchResult.substring(0, len - 1) + "," + rolesCtxDN + "\"";
}
else
{
result = searchResult + "," + rolesCtxDN;
}
return result;
}
private void addRole(String roleName)
{
if (roleName != null)
{
try
{
Principal p = super.createIdentity(roleName);
if (trace) {
log.trace("Assign user '" + getIdentity().getName() + "' to role " + roleName);
}
userRoles.addMember(p);
}
catch (Exception e)
{
if (log.isDebugEnabled())
log.debug("Failed to create principal: " + roleName, e);
}
}
}
private class AuthorizeAction implements PrivilegedAction<Object>
{
public Object run()
{
try
{
return innerLogin();
}
catch (LoginException e)
{
return e;
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_1503_1
|
crossvul-java_data_good_3055_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* 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.
*/
package jenkins.model;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.init.TerminatorFinder;
import hudson.lifecycle.Lifecycle;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.logging.LogRecorderManager;
import hudson.markup.EscapedMarkupFormatter;
import hudson.markup.MarkupFormatter;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.LoadStatistics;
import hudson.model.ManagementLink;
import hudson.model.Messages;
import hudson.model.ModifiableViewGroup;
import hudson.model.NoFingerprintMatch;
import hudson.model.Node;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.NamingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static hudson.Util.*;
import static hudson.init.InitMilestone.*;
import hudson.util.LogTaskListener;
import static java.util.logging.Level.*;
import static javax.servlet.http.HttpServletResponse.*;
import org.kohsuke.stapler.WebMethod;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Jenkins whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Jenkins.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Jenkins.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Jenkins system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Legacy store of the set of installed cluster nodes.
* @deprecated in favour of {@link Nodes}
*/
@Deprecated
protected transient volatile NodeList slaves;
/**
* The holder of the set of installed cluster nodes.
*
* @since 1.607
*/
private transient final Nodes nodes = new Nodes(this);
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Jenkins.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
@CheckForNull Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public @CheckForNull Jenkins getInstance() {
return theInstance;
}
};
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstance()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
*/
public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Gets the {@link Jenkins} singleton.
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
*/
@CLIResolver
@CheckForNull
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c, new LogTaskListener(LOGGER, INFO));
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
@Deprecated
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
@Deprecated
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
@Deprecated
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Jenkins by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/** @deprecated Use {@link SCMListener#all} instead. */
@Deprecated
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public @Nonnull MarkupFormatter getMarkupFormatter() {
MarkupFormatter f = markupFormatter;
return f != null ? f : new EscapedMarkupFormatter();
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Jenkins.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Jenkins.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Jenkins forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
@Override public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return lhs.getName().compareTo(rhs.getName());
}
});
return r;
}
@CLIResolver
public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public synchronized List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Replaces all JDK installations with those from the given collection.
*
* Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to
* set JDK installations from external code.
*/
@Restricted(NoExternalUse.class)
public synchronized void setJDKs(Collection<? extends JDK> jdks) {
this.jdks = new ArrayList<JDK>(jdks);
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Jenkins.
*/
public @CheckForNull Node getNode(String name) {
return nodes.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return nodes.getNodes();
}
/**
* Get the {@link Nodes} object that handles maintaining individual {@link Node}s.
* @return The Nodes object.
*/
@Restricted(NoExternalUse.class)
public Nodes getNodesObject() {
// TODO replace this with something better when we properly expose Nodes.
return nodes;
}
/**
* Adds one more {@link Node} to Jenkins.
*/
public void addNode(Node n) throws IOException {
nodes.addNode(n);
}
/**
* Removes a {@link Node} from Jenkins.
*/
public void removeNode(@Nonnull Node n) throws IOException {
nodes.removeNode(n);
}
public void setNodes(final List<? extends Node> n) throws IOException {
nodes.setNodes(n);
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
/*package*/ void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
// do essentially what expandVariablesForDirectory does, without an Item
String replacedValue = expandVariablesForDirectory(value,
"doCheckRawBuildsDir-Marker:foo",
Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo");
File replacedFile = new File(replacedValue);
if (!replacedFile.isAbsolute()) {
return FormValidation.error(value + " does not resolve to an absolute path");
}
if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) {
return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects");
}
if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) {
// make sure platform can handle colon
try {
File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar");
tmp.delete();
} catch (IOException e) {
return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead");
}
}
File d = new File(replacedValue);
if (!d.isDirectory()) {
// if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to
d = d.getParentFile();
while (!d.exists()) {
d = d.getParentFile();
}
if (!d.canWrite()) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
}
return FormValidation.ok();
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return viewGroupMixIn.getViews(); }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}.
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link #getRootUrlFromRequest}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /}
* @since 1.66
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public @Nullable String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}.
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* <p>Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy which has not been fully configured.
* Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set.
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a>
* shows some examples of configuration.
* @since 1.263
*/
public @Nonnull String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
int index = host.indexOf(':');
int port = req.getServerPort();
if (index == -1) {
// Almost everyone else except Nginx put the host and port in separate headers
buf.append(host);
} else {
// Nginx uses the same spec as for the Host header, i.e. hostanme:port
buf.append(host.substring(0, index));
if (index + 1 < host.length()) {
try {
port = Integer.parseInt(host.substring(index + 1));
} catch (NumberFormatException e) {
// ignore
}
}
// but if a user has configured Nginx with an X-Forwarded-Port, that will win out.
}
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath()));
}
@Restricted(NoExternalUse.class)
static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) {
return Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(),
"ITEM_ROOTDIR", itemRootDir,
"ITEM_FULLNAME", itemFullName, // legacy, deprecated
"ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
@Restricted(NoExternalUse.class)
public void setRawBuildsDir(String buildsDir) {
this.buildsDir = buildsDir;
}
@Override public @Nonnull FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new MasterToSlaveCallable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Jenkins would have to have crumb in it to protect
* Jenkins from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes in Jenkins.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
IdStrategy oldUserIdStrategy = this.securityRealm == null
? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load
: this.securityRealm.getUserIdStrategy();
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) {
User.rekey();
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
* @see ExtensionList#lookup
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Jenkins is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
if (this.numExecutors != n) {
this.numExecutors = n;
updateComputerList();
save();
}
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override public TopLevelItem getItem(String name) throws AccessDeniedException {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
* @throws AccessDeniedException as per {@link ItemGroup#getItem}
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean), {@link User#getById(String, boolean)}
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Jenkins by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(job, oldName, newName);
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
}
@Override public boolean canAdd(TopLevelItem item) {
return true;
}
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
items.put(name, item);
return item;
}
@Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException {
items.remove(item.getName());
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles();
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) {
nodes.setNodes(slaves);
slaves = null;
} else {
nodes.load();
}
clouds.setOwner(Jenkins.this);
}
});
for (final File subdir : subdirs) {
g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
if(!Items.getConfigFile(subdir).exists()) {
//Does not have job config file, so it is not a jenkins job hence skip it
return;
}
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : nodes.getNodes())
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Jenkins and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
} catch (InterruptedException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
e.printStackTrace();
} catch (ReactorException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
}
final Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
// JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
}
});
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
java.util.Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
Timer.shutdown();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
setJDKs(req.bindJSONToList(JDK.class, json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
@RequirePOST
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
@RequirePOST // TODO does not seem to work on _either_ overload!
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
@RequirePOST
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
long waitUntil = timeout;
if (timeout > 0) waitUntil += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < waitUntil)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
@RequirePOST // TODO the cancel link needs to be updated accordingly
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r));
}
@RequirePOST
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
@RequirePOST
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if(".".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName("."));
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
* Used only by {@link LegacySecurityRealm}.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
// TODO fire something in SecurityListener?
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String user = getAuthentication().getName();
securityRealm.doLogout(req, rsp);
SecurityListener.fireLoggedOut(user);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
@RequirePOST
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,FilePath.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Jenkins, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Jenkins for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
@Extension @Restricted(NoExternalUse.class)
public static class MasterRestartNotifyier extends RestartListener {
@Override
public void onRestart() {
Computer computer = Jenkins.getInstance().toComputer();
if (computer == null) return;
RestartCause cause = new RestartCause();
for (ComputerListener listener: ComputerListener.all()) {
listener.onOffline(computer, cause);
}
}
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return true;
}
private static class RestartCause extends OfflineCause.SimpleOfflineCause {
protected RestartCause() {
super(Messages._Jenkins_IsRestarting());
}
}
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
@RequirePOST
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
@RequirePOST
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static @Nonnull Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
if (channel == null) {
throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if (getSecurityRealm().allowsSignup()) {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
return;
}
req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
@RequirePOST
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
@RequirePOST
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals(JDK.DEFAULT_NAME))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
@Deprecated
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
}, 500, TimeUnit.MILLISECONDS);
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/error")
|| rest.startsWith("/oops")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
@Override
public Boolean isUnix() {
return !Functions.isWindows();
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@WebMethod(name="config.xml")
@Override
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return FilePath.localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
@RequirePOST
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*
* @deprecated as of 1.558
* Use {@link FilePath#localChannel}
*/
@Deprecated
public static final LocalChannel localChannel = FilePath.localChannel;
}
/**
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Jenkins.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM;
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Jenkins.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* @deprecated No longer used.
*/
@Deprecated
public static boolean FLYWEIGHT_SUPPORT = true;
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS;
static {
try {
ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
XSTREAM = XSTREAM2 = new XStream2();
XSTREAM.alias("jenkins", Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk", JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
XSTREAM2.addCriticalField(Jenkins.class, "securityRealm");
XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy");
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS != null;
assert ADMINISTER != null;
} catch (RuntimeException e) {
// when loaded on a slave and this fails, subsequent NoClassDefFoundError will fail to chain the cause.
// see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847
// As we don't know where the first exception will go, let's also send this to logging so that
// we have a known place to look at.
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
} catch (Error e) {
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_3055_0
|
crossvul-java_data_bad_5809_3
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_5809_3
|
crossvul-java_data_bad_4347_4
|
/*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
/**
* Aspecto encargado de realizar el log de rendimiento de los Controllers.
*/
@Configuration
@ConditionalOnProperty(name = "application.log.enabled", havingValue = "true", matchIfMissing = true)
public class ControllerLoggerAspectConfiguration {
private static final Logger log = LoggerFactory.getLogger("org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable");
@Aspect
@Component
public class ControllerLoggerAspect {
@Before("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..controller..*(..))")
public void logBefore(JoinPoint joinPoint) {
if (log.isDebugEnabled()) {
log.debug("************************* INIT CONTROLLER *********************************");
log.debug("Controller : Entering in Method : {}", joinPoint.getSignature().getDeclaringTypeName());
log.debug("Controller : Method : {}", joinPoint.getSignature().getName());
log.debug("Controller : Arguments : {}", Arrays.toString(joinPoint.getArgs()));
log.debug("Controller : Target class : {}", joinPoint.getTarget().getClass().getName());
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes()).getRequest();
if (null != request) {
log.debug("Controller : Start Header Section of request ");
log.debug("Controller : Method Type : {}", request.getMethod());
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if (!headerName.startsWith("x-forwarded")) {
String headerValue = request.getHeader(headerName);
log.debug("Controller : [Header Name]:{}|[Header Value]:{}", headerName, headerValue);
}
}
log.debug("Controller : Request Path info : {}", request.getServletPath());
log.debug("Controller : End Header Section of request ");
}
}
}
@AfterThrowing(pointcut = "execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..controller..*(..))", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
log.error("Controller : An exception has been thrown in {} ()", joinPoint.getSignature().getName());
log.error("Controller : Cause : {}", exception.getCause());
log.error("Controller : Message : {}", exception.getMessage());
log.debug("************************* END CONTROLLER **********************************");
}
@Around("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..controller..*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
try {
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - start;
log.debug("Controller : Controller {}.{} () execution time: {} ms", className, methodName, elapsedTime);
if ((null != result) && (result instanceof ResponseEntity) && log.isDebugEnabled()) {
Object dataReturned = ((ResponseEntity<?>) result).getBody();
HttpStatus returnedStatus = ((ResponseEntity<?>) result).getStatusCode();
HttpHeaders headers = ((ResponseEntity<?>) result).getHeaders();
log.debug("Controller : Controller Return value : <{}, {}>", returnedStatus, dataReturned);
log.debug("Controller : Start Header Section of response ");
if ((headers != null) && (!headers.isEmpty())) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
log.debug("Controller : [Header Name]:{}|[Header Value]:{}", entry.getKey(),
entry.getValue());
}
}
log.debug("Controller : End Header Section of response ");
}
log.debug("************************* END CONTROLLER **********************************");
return result;
} catch (IllegalArgumentException e) {
log.error("Controller : Illegal argument {} in {}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getName(), e);
throw e;
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_4347_4
|
crossvul-java_data_bad_5809_0
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_5809_0
|
crossvul-java_data_good_3048_1
|
/*
* The MIT License
*
* Copyright (c) 2013 Red Hat, Inc.
*
* 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.
*/
package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import hudson.security.ACL;
import hudson.security.AccessDeniedException2;
import hudson.security.GlobalMatrixAuthorizationStrategy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* @author ogondza
*/
public class ComputerConfigDotXmlTest {
@Rule public final JenkinsRule rule = new JenkinsRule();
@Mock private StaplerRequest req;
@Mock private StaplerResponse rsp;
private Computer computer;
private SecurityContext oldSecurityContext;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
computer = spy(rule.createSlave().toComputer());
rule.jenkins.setSecurityRealm(rule.createDummySecurityRealm());
oldSecurityContext = ACL.impersonate(User.get("user").impersonate());
}
@After
public void tearDown() {
SecurityContextHolder.setContext(oldSecurityContext);
}
@Test(expected = AccessDeniedException2.class)
public void configXmlGetShouldFailForUnauthorized() throws Exception {
when(req.getMethod()).thenReturn("GET");
rule.jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy());
computer.doConfigDotXml(req, rsp);
}
@Test(expected = AccessDeniedException2.class)
public void configXmlPostShouldFailForUnauthorized() throws Exception {
when(req.getMethod()).thenReturn("POST");
rule.jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy());
computer.doConfigDotXml(req, rsp);
}
@Test
public void configXmlGetShouldYieldNodeConfiguration() throws Exception {
when(req.getMethod()).thenReturn("GET");
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
rule.jenkins.setAuthorizationStrategy(auth);
Computer.EXTENDED_READ.setEnabled(true);
auth.add(Computer.EXTENDED_READ, "user");
final OutputStream outputStream = captureOutput();
computer.doConfigDotXml(req, rsp);
final String out = outputStream.toString();
assertThat(out, startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
assertThat(out, containsString("<name>slave0</name>"));
assertThat(out, containsString("<description>dummy</description>"));
}
@Test
public void configXmlPostShouldUpdateNodeConfiguration() throws Exception {
when(req.getMethod()).thenReturn("POST");
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
rule.jenkins.setAuthorizationStrategy(auth);
auth.add(Computer.CONFIGURE, "user");
when(req.getInputStream()).thenReturn(xmlNode("node.xml"));
computer.doConfigDotXml(req, rsp);
final Node updatedSlave = rule.jenkins.getNode("SlaveFromXML");
assertThat(updatedSlave.getNodeName(), equalTo("SlaveFromXML"));
assertThat(updatedSlave.getNumExecutors(), equalTo(42));
}
@Test
@Issue("SECURITY-343")
public void emptyNodeMonitorDataWithoutConnect() throws Exception {
rule.jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy());
assertTrue(computer.getMonitorData().isEmpty());
}
@Test
@Issue("SECURITY-343")
public void populatedNodeMonitorDataWithConnect() throws Exception {
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
rule.jenkins.setAuthorizationStrategy(auth);
auth.add(Computer.CONNECT, "user");
assertFalse(computer.getMonitorData().isEmpty());
}
private OutputStream captureOutput() throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
when(rsp.getOutputStream()).thenReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
baos.write(b);
}
});
return baos;
}
private ServletInputStream xmlNode(final String name) {
class Stream extends ServletInputStream {
private final InputStream inner;
public Stream(final InputStream inner) {
this.inner = inner;
}
@Override
public int read() throws IOException {
return inner.read();
}
}
return new Stream(Computer.class.getResourceAsStream(name));
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_3048_1
|
crossvul-java_data_bad_2096_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, David Calavera, Seiji Sogabe
*
* 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.
*/
package hudson.security;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import hudson.Extension;
import hudson.Util;
import hudson.diagnosis.OldDataMonitor;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import hudson.model.ManagementLink;
import hudson.model.ModelObject;
import hudson.model.User;
import hudson.model.UserProperty;
import hudson.model.UserPropertyDescriptor;
import hudson.security.FederatedLoginService.FederatedIdentity;
import hudson.security.captcha.CaptchaSupport;
import hudson.util.PluginServletFilter;
import hudson.util.Protector;
import hudson.util.Scrambler;
import hudson.util.XStream2;
import net.sf.json.JSONObject;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.encoding.PasswordEncoder;
import org.acegisecurity.providers.encoding.ShaPasswordEncoder;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.tools.ant.taskdefs.email.Mailer;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.dao.DataAccessException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link SecurityRealm} that performs authentication by looking up {@link User}.
*
* <p>
* Implements {@link AccessControlled} to satisfy view rendering, but in reality the access control
* is done against the {@link jenkins.model.Jenkins} object.
*
* @author Kohsuke Kawaguchi
*/
public class HudsonPrivateSecurityRealm extends AbstractPasswordBasedSecurityRealm implements ModelObject, AccessControlled {
/**
* If true, sign up is not allowed.
* <p>
* This is a negative switch so that the default value 'false' remains compatible with older installations.
*/
private final boolean disableSignup;
/**
* If true, captcha will be enabled.
*/
private final boolean enableCaptcha;
@Deprecated
public HudsonPrivateSecurityRealm(boolean allowsSignup) {
this(allowsSignup, false, (CaptchaSupport) null);
}
@DataBoundConstructor
public HudsonPrivateSecurityRealm(boolean allowsSignup, boolean enableCaptcha, CaptchaSupport captchaSupport) {
this.disableSignup = !allowsSignup;
this.enableCaptcha = enableCaptcha;
setCaptchaSupport(captchaSupport);
if(!allowsSignup && !hasSomeUser()) {
// if Hudson is newly set up with the security realm and there's no user account created yet,
// insert a filter that asks the user to create one
try {
PluginServletFilter.addFilter(CREATE_FIRST_USER_FILTER);
} catch (ServletException e) {
throw new AssertionError(e); // never happen because our Filter.init is no-op
}
}
}
@Override
public boolean allowsSignup() {
return !disableSignup;
}
/**
* Checks if captcha is enabled on user signup.
*
* @return true if captcha is enabled on signup.
*/
public boolean isEnableCaptcha() {
return enableCaptcha;
}
/**
* Computes if this Hudson has some user accounts configured.
*
* <p>
* This is used to check for the initial
*/
private static boolean hasSomeUser() {
for (User u : User.getAll())
if(u.getProperty(Details.class)!=null)
return true;
return false;
}
/**
* This implementation doesn't support groups.
*/
@Override
public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
throw new UsernameNotFoundException(groupname);
}
@Override
public Details loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
User u = User.get(username,false);
Details p = u!=null ? u.getProperty(Details.class) : null;
if(p==null)
throw new UsernameNotFoundException("Password is not set: "+username);
if(p.getUser()==null)
throw new AssertionError();
return p;
}
@Override
protected Details authenticate(String username, String password) throws AuthenticationException {
Details u = loadUserByUsername(username);
if (!u.isPasswordCorrect(password))
throw new BadCredentialsException("Failed to login as "+username);
return u;
}
/**
* Show the sign up page with the data from the identity.
*/
@Override
public HttpResponse commenceSignup(final FederatedIdentity identity) {
// store the identity in the session so that we can use this later
Stapler.getCurrentRequest().getSession().setAttribute(FEDERATED_IDENTITY_SESSION_KEY,identity);
return new ForwardToView(this,"signupWithFederatedIdentity.jelly") {
@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
SignupInfo si = new SignupInfo(identity);
si.errorMessage = Messages.HudsonPrivateSecurityRealm_WouldYouLikeToSignUp(identity.getPronoun(),identity.getIdentifier());
req.setAttribute("data", si);
super.generateResponse(req, rsp, node);
}
};
}
/**
* Creates an account and associates that with the given identity. Used in conjunction
* with {@link #commenceSignup(FederatedIdentity)}.
*/
public User doCreateAccountWithFederatedIdentity(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
User u = _doCreateAccount(req,rsp,"signupWithFederatedIdentity.jelly");
if (u!=null)
((FederatedIdentity)req.getSession().getAttribute(FEDERATED_IDENTITY_SESSION_KEY)).addTo(u);
return u;
}
private static final String FEDERATED_IDENTITY_SESSION_KEY = HudsonPrivateSecurityRealm.class.getName()+".federatedIdentity";
/**
* Creates an user account. Used for self-registration.
*/
public User doCreateAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
return _doCreateAccount(req, rsp, "signup.jelly");
}
private User _doCreateAccount(StaplerRequest req, StaplerResponse rsp, String formView) throws ServletException, IOException {
if(!allowsSignup())
throw HttpResponses.error(SC_UNAUTHORIZED,new Exception("User sign up is prohibited"));
boolean firstUser = !hasSomeUser();
User u = createAccount(req, rsp, enableCaptcha, formView);
if(u!=null) {
if(firstUser)
tryToMakeAdmin(u); // the first user should be admin, or else there's a risk of lock out
loginAndTakeBack(req, rsp, u);
}
return u;
}
/**
* Lets the current user silently login as the given user and report back accordingly.
*/
private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u) throws ServletException, IOException {
// ... and let him login
Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1"));
a = this.getSecurityComponents().manager.authenticate(a);
SecurityContextHolder.getContext().setAuthentication(a);
// then back to top
req.getView(this,"success.jelly").forward(req,rsp);
}
/**
* Creates an user account. Used by admins.
*
* This version behaves differently from {@link #doCreateAccount(StaplerRequest, StaplerResponse)} in that
* this is someone creating another user.
*/
public void doCreateAccountByAdmin(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(Jenkins.ADMINISTER);
if(createAccount(req, rsp, false, "addUser.jelly")!=null) {
rsp.sendRedirect("."); // send the user back to the listing page
}
}
/**
* Creates a first admin user account.
*
* <p>
* This can be run by anyone, but only to create the very first user account.
*/
public void doCreateFirstAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if(hasSomeUser()) {
rsp.sendError(SC_UNAUTHORIZED,"First user was already created");
return;
}
User u = createAccount(req, rsp, false, "firstUser.jelly");
if (u!=null) {
tryToMakeAdmin(u);
loginAndTakeBack(req, rsp, u);
}
}
/**
* Try to make this user a super-user
*/
private void tryToMakeAdmin(User u) {
AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy();
if (as instanceof GlobalMatrixAuthorizationStrategy) {
GlobalMatrixAuthorizationStrategy ma = (GlobalMatrixAuthorizationStrategy) as;
ma.add(Jenkins.ADMINISTER,u.getId());
}
}
/**
* @return
* null if failed. The browser is already redirected to retry by the time this method returns.
* a valid {@link User} object if the user creation was successful.
*/
private User createAccount(StaplerRequest req, StaplerResponse rsp, boolean selfRegistration, String formView) throws ServletException, IOException {
// form field validation
// this pattern needs to be generalized and moved to stapler
SignupInfo si = new SignupInfo(req);
if(selfRegistration && !validateCaptcha(si.captcha))
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_TextNotMatchWordInImage();
if(si.password1 != null && !si.password1.equals(si.password2))
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_PasswordNotMatch();
if(!(si.password1 != null && si.password1.length() != 0))
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_PasswordRequired();
if(si.username==null || si.username.length()==0)
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameRequired();
else {
User user = User.get(si.username, false);
if (null != user)
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameAlreadyTaken();
}
if(si.fullname==null || si.fullname.length()==0)
si.fullname = si.username;
if(si.email==null || !si.email.contains("@"))
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_InvalidEmailAddress();
if(si.errorMessage!=null) {
// failed. ask the user to try again.
req.setAttribute("data",si);
req.getView(this, formView).forward(req,rsp);
return null;
}
// register the user
User user = createAccount(si.username,si.password1);
user.setFullName(si.fullname);
try {
// legacy hack. mail support has moved out to a separate plugin
Class<?> up = Jenkins.getInstance().pluginManager.uberClassLoader.loadClass("hudson.tasks.Mailer$UserProperty");
Constructor<?> c = up.getDeclaredConstructor(String.class);
user.addProperty((UserProperty)c.newInstance(si.email));
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to set the e-mail address",e);
}
user.save();
return user;
}
/**
* Creates a new user account by registering a password to the user.
*/
public User createAccount(String userName, String password) throws IOException {
User user = User.get(userName);
user.addProperty(Details.fromPlainPassword(password));
return user;
}
/**
* This is used primarily when the object is listed in the breadcrumb, in the user management screen.
*/
public String getDisplayName() {
return "User Database";
}
public ACL getACL() {
return Jenkins.getInstance().getACL();
}
public void checkPermission(Permission permission) {
Jenkins.getInstance().checkPermission(permission);
}
public boolean hasPermission(Permission permission) {
return Jenkins.getInstance().hasPermission(permission);
}
/**
* All users who can login to the system.
*/
public List<User> getAllUsers() {
List<User> r = new ArrayList<User>();
for (User u : User.getAll()) {
if(u.getProperty(Details.class)!=null)
r.add(u);
}
Collections.sort(r);
return r;
}
/**
* This is to map users under the security realm URL.
* This in turn helps us set up the right navigation breadcrumb.
*/
public User getUser(String id) {
return User.get(id);
}
// TODO
private static final GrantedAuthority[] TEST_AUTHORITY = {AUTHENTICATED_AUTHORITY};
public static final class SignupInfo {
public String username,password1,password2,fullname,email,captcha;
/**
* To display an error message, set it here.
*/
public String errorMessage;
public SignupInfo() {
}
public SignupInfo(StaplerRequest req) {
req.bindParameters(this);
}
public SignupInfo(FederatedIdentity i) {
this.username = i.getNickname();
this.fullname = i.getFullName();
this.email = i.getEmailAddress();
}
}
/**
* {@link UserProperty} that provides the {@link UserDetails} view of the User object.
*
* <p>
* When a {@link User} object has this property on it, it means the user is configured
* for log-in.
*
* <p>
* When a {@link User} object is re-configured via the UI, the password
* is sent to the hidden input field by using {@link Protector}, so that
* the same password can be retained but without leaking information to the browser.
*/
public static final class Details extends UserProperty implements InvalidatableUserDetails {
/**
* Hashed password.
*/
private /*almost final*/ String passwordHash;
/**
* @deprecated Scrambled password.
* Field kept here to load old (pre 1.283) user records,
* but now marked transient so field is no longer saved.
*/
private transient String password;
private Details(String passwordHash) {
this.passwordHash = passwordHash;
}
static Details fromHashedPassword(String hashed) {
return new Details(hashed);
}
static Details fromPlainPassword(String rawPassword) {
return new Details(PASSWORD_ENCODER.encodePassword(rawPassword,null));
}
public GrantedAuthority[] getAuthorities() {
// TODO
return TEST_AUTHORITY;
}
public String getPassword() {
return passwordHash;
}
public boolean isPasswordCorrect(String candidate) {
return PASSWORD_ENCODER.isPasswordValid(getPassword(),candidate,null);
}
public String getProtectedPassword() {
// put session Id in it to prevent a replay attack.
return Protector.protect(Stapler.getCurrentRequest().getSession().getId()+':'+getPassword());
}
public String getUsername() {
return user.getId();
}
/*package*/ User getUser() {
return user;
}
public boolean isAccountNonExpired() {
return true;
}
public boolean isAccountNonLocked() {
return true;
}
public boolean isCredentialsNonExpired() {
return true;
}
public boolean isEnabled() {
return true;
}
public boolean isInvalid() {
return user==null;
}
public static class ConverterImpl extends XStream2.PassthruConverter<Details> {
public ConverterImpl(XStream2 xstream) { super(xstream); }
@Override protected void callback(Details d, UnmarshallingContext context) {
// Convert to hashed password and report to monitor if we load old data
if (d.password!=null && d.passwordHash==null) {
d.passwordHash = PASSWORD_ENCODER.encodePassword(Scrambler.descramble(d.password),null);
OldDataMonitor.report(context, "1.283");
}
}
}
@Extension
public static final class DescriptorImpl extends UserPropertyDescriptor {
public String getDisplayName() {
// this feature is only when HudsonPrivateSecurityRealm is enabled
if(isEnabled())
return Messages.HudsonPrivateSecurityRealm_Details_DisplayName();
else
return null;
}
@Override
public Details newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String pwd = Util.fixEmpty(req.getParameter("user.password"));
String pwd2= Util.fixEmpty(req.getParameter("user.password2"));
if(!Util.fixNull(pwd).equals(Util.fixNull(pwd2)))
throw new FormException("Please confirm the password by typing it twice","user.password2");
String data = Protector.unprotect(pwd);
if(data!=null) {
String prefix = Stapler.getCurrentRequest().getSession().getId() + ':';
if(data.startsWith(prefix))
return Details.fromHashedPassword(data.substring(prefix.length()));
}
return Details.fromPlainPassword(Util.fixNull(pwd));
}
@Override
public boolean isEnabled() {
return Jenkins.getInstance().getSecurityRealm() instanceof HudsonPrivateSecurityRealm;
}
public UserProperty newInstance(User user) {
return null;
}
}
}
/**
* Displays "manage users" link in the system config if {@link HudsonPrivateSecurityRealm}
* is in effect.
*/
@Extension
public static final class ManageUserLinks extends ManagementLink {
public String getIconFileName() {
if(Jenkins.getInstance().getSecurityRealm() instanceof HudsonPrivateSecurityRealm)
return "user.png";
else
return null; // not applicable now
}
public String getUrlName() {
return "securityRealm/";
}
public String getDisplayName() {
return Messages.HudsonPrivateSecurityRealm_ManageUserLinks_DisplayName();
}
@Override
public String getDescription() {
return Messages.HudsonPrivateSecurityRealm_ManageUserLinks_Description();
}
}
/**
* {@link PasswordEncoder} based on SHA-256 and random salt generation.
*
* <p>
* The salt is prepended to the hashed password and returned. So the encoded password is of the form
* <tt>SALT ':' hash(PASSWORD,SALT)</tt>.
*
* <p>
* This abbreviates the need to store the salt separately, which in turn allows us to hide the salt handling
* in this little class. The rest of the Acegi thinks that we are not using salt.
*/
/*package*/ static final PasswordEncoder CLASSIC = new PasswordEncoder() {
private final PasswordEncoder passwordEncoder = new ShaPasswordEncoder(256);
public String encodePassword(String rawPass, Object _) throws DataAccessException {
return hash(rawPass);
}
public boolean isPasswordValid(String encPass, String rawPass, Object _) throws DataAccessException {
// pull out the sale from the encoded password
int i = encPass.indexOf(':');
if(i<0) return false;
String salt = encPass.substring(0,i);
return encPass.substring(i+1).equals(passwordEncoder.encodePassword(rawPass,salt));
}
/**
* Creates a hashed password by generating a random salt.
*/
private String hash(String password) {
String salt = generateSalt();
return salt+':'+passwordEncoder.encodePassword(password,salt);
}
/**
* Generates random salt.
*/
private String generateSalt() {
StringBuilder buf = new StringBuilder();
SecureRandom sr = new SecureRandom();
for( int i=0; i<6; i++ ) {// log2(52^6)=34.20... so, this is about 32bit strong.
boolean upper = sr.nextBoolean();
char ch = (char)(sr.nextInt(26) + 'a');
if(upper) ch=Character.toUpperCase(ch);
buf.append(ch);
}
return buf.toString();
}
};
/**
* {@link PasswordEncoder} that uses jBCrypt.
*/
private static final PasswordEncoder JBCRYPT_ENCODER = new PasswordEncoder() {
public String encodePassword(String rawPass, Object _) throws DataAccessException {
return BCrypt.hashpw(rawPass,BCrypt.gensalt());
}
public boolean isPasswordValid(String encPass, String rawPass, Object _) throws DataAccessException {
return BCrypt.checkpw(rawPass,encPass);
}
};
/**
* Combines {@link #JBCRYPT_ENCODER} and {@link #CLASSIC} into one so that we can continue
* to accept {@link #CLASSIC} format but new encoding will always done via {@link #JBCRYPT_ENCODER}.
*/
public static final PasswordEncoder PASSWORD_ENCODER = new PasswordEncoder() {
/*
CLASSIC encoder outputs "salt:hash" where salt is [a-z]+, so we use unique prefix '#jbcyrpt"
to designate JBCRYPT-format hash.
'#' is neither in base64 nor hex, which makes it a good choice.
*/
public String encodePassword(String rawPass, Object salt) throws DataAccessException {
return JBCRYPT_HEADER+JBCRYPT_ENCODER.encodePassword(rawPass,salt);
}
public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException {
if (encPass.startsWith(JBCRYPT_HEADER))
return JBCRYPT_ENCODER.isPasswordValid(encPass.substring(JBCRYPT_HEADER.length()),rawPass,salt);
else
return CLASSIC.isPasswordValid(encPass,rawPass,salt);
}
private static final String JBCRYPT_HEADER = "#jbcrypt:";
};
@Extension
public static final class DescriptorImpl extends Descriptor<SecurityRealm> {
public String getDisplayName() {
return Messages.HudsonPrivateSecurityRealm_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/security/private-realm.html";
}
}
private static final Filter CREATE_FIRST_USER_FILTER = new Filter() {
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if(req.getRequestURI().equals(req.getContextPath()+"/")) {
if (needsToCreateFirstUser()) {
((HttpServletResponse)response).sendRedirect("securityRealm/firstUser");
} else {// the first user already created. the role of this filter is over.
PluginServletFilter.removeFilter(this);
chain.doFilter(request,response);
}
} else
chain.doFilter(request,response);
}
private boolean needsToCreateFirstUser() {
return !hasSomeUser()
&& Jenkins.getInstance().getSecurityRealm() instanceof HudsonPrivateSecurityRealm;
}
public void destroy() {
}
};
private static final Logger LOGGER = Logger.getLogger(HudsonPrivateSecurityRealm.class.getName());
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_2096_0
|
crossvul-java_data_good_3048_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Red Hat, Inc., Seiji Sogabe, Stephen Connolly, Thomas J. Black, Tom Huybrechts, CloudBees, Inc.
*
* 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.
*/
package hudson.model;
import edu.umd.cs.findbugs.annotations.OverrideMustInvoke;
import edu.umd.cs.findbugs.annotations.When;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Launcher.ProcStarter;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.console.AnnotatedLargeText;
import hudson.init.Initializer;
import hudson.model.Descriptor.FormException;
import hudson.model.Queue.FlyweightTask;
import hudson.model.labels.LabelAtom;
import hudson.model.queue.WorkUnit;
import hudson.node_monitors.NodeMonitor;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.slaves.AbstractCloudSlave;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.ComputerListener;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import hudson.slaves.WorkspaceList;
import hudson.slaves.OfflineCause;
import hudson.slaves.OfflineCause.ByCLI;
import hudson.util.DaemonThreadFactory;
import hudson.util.EditDistance;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.RunList;
import hudson.util.Futures;
import hudson.util.NamingThreadFactory;
import jenkins.model.Jenkins;
import jenkins.util.ContextResettingExecutorService;
import jenkins.security.MasterToSlaveCallable;
import jenkins.security.NotReallyRoleSensitiveCallable;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.nio.charset.Charset;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Inet4Address;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Represents the running state of a remote computer that holds {@link Executor}s.
*
* <p>
* {@link Executor}s on one {@link Computer} are transparently interchangeable
* (that is the definition of {@link Computer}).
*
* <p>
* This object is related to {@link Node} but they have some significant differences.
* {@link Computer} primarily works as a holder of {@link Executor}s, so
* if a {@link Node} is configured (probably temporarily) with 0 executors,
* you won't have a {@link Computer} object for it (except for the master node,
* which always gets its {@link Computer} in case we have no static executors and
* we need to run a {@link FlyweightTask} - see JENKINS-7291 for more discussion.)
*
* Also, even if you remove a {@link Node}, it takes time for the corresponding
* {@link Computer} to be removed, if some builds are already in progress on that
* node. Or when the node configuration is changed, unaffected {@link Computer} object
* remains intact, while all the {@link Node} objects will go away.
*
* <p>
* This object also serves UI (unlike {@link Node}), and can be used along with
* {@link TransientComputerActionFactory} to add {@link Action}s to {@link Computer}s.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public /*transient*/ abstract class Computer extends Actionable implements AccessControlled, ExecutorListener {
private final CopyOnWriteArrayList<Executor> executors = new CopyOnWriteArrayList<Executor>();
// TODO:
private final CopyOnWriteArrayList<OneOffExecutor> oneOffExecutors = new CopyOnWriteArrayList<OneOffExecutor>();
private int numExecutors;
/**
* Contains info about reason behind computer being offline.
*/
protected volatile OfflineCause offlineCause;
private long connectTime = 0;
/**
* True if Jenkins shouldn't start new builds on this node.
*/
private boolean temporarilyOffline;
/**
* {@link Node} object may be created and deleted independently
* from this object.
*/
protected String nodeName;
/**
* @see #getHostName()
*/
private volatile String cachedHostName;
private volatile boolean hostNameCached;
/**
* @see #getEnvironment()
*/
private volatile EnvVars cachedEnvironment;
private final WorkspaceList workspaceList = new WorkspaceList();
protected transient List<Action> transientActions;
protected final Object statusChangeLock = new Object();
/**
* Keeps track of stack traces to track the tremination requests for this computer.
*
* @since 1.607
* @see Executor#resetWorkUnit(String)
*/
private transient final List<TerminationRequest> terminatedBy = Collections.synchronizedList(new ArrayList
<TerminationRequest>());
/**
* This method captures the information of a request to terminate a computer instance. Method is public as
* it needs to be called from {@link AbstractCloudSlave} and {@link jenkins.model.Nodes}. In general you should
* not need to call this method directly, however if implementing a custom node type or a different path
* for removing nodes, it may make sense to call this method in order to capture the originating request.
*
* @since 1.607
*/
public void recordTermination() {
StaplerRequest request = Stapler.getCurrentRequest();
if (request != null) {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d] from HTTP request for %s",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId(),
request.getRequestURL()
)
));
} else {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d]",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId()
)
));
}
}
/**
* Returns the list of captured termination requests for this Computer. This method is used by {@link Executor}
* to provide details on why a Computer was removed in-between work being scheduled against the {@link Executor}
* and the {@link Executor} starting to execute the task.
*
* @return the (possibly empty) list of termination requests.
* @see Executor#resetWorkUnit(String)
* @since 1.607
*/
public List<TerminationRequest> getTerminatedBy() {
return new ArrayList<TerminationRequest>(terminatedBy);
}
public Computer(Node node) {
setNode(node);
}
/**
* Returns list of all boxes {@link ComputerPanelBox}s.
*/
public List<ComputerPanelBox> getComputerPanelBoxs(){
return ComputerPanelBox.all(this);
}
/**
* Returns the transient {@link Action}s associated with the computer.
*/
@SuppressWarnings("deprecation")
public List<Action> getActions() {
List<Action> result = new ArrayList<Action>();
result.addAll(super.getActions());
synchronized (this) {
if (transientActions == null) {
transientActions = TransientComputerActionFactory.createAllFor(this);
}
result.addAll(transientActions);
}
return Collections.unmodifiableList(result);
}
@SuppressWarnings("deprecation")
@Override
public void addAction(Action a) {
if(a==null) throw new IllegalArgumentException();
super.getActions().add(a);
}
/**
* This is where the log from the remote agent goes.
* The method also creates a log directory if required.
* @see #getLogDir(), #relocateOldLogs()
*/
public @Nonnull File getLogFile() {
return new File(getLogDir(),"slave.log");
}
/**
* Directory where rotated slave logs are stored.
*
* The method also creates a log directory if required.
*
* @since 1.613
*/
protected @Nonnull File getLogDir() {
File dir = new File(Jenkins.getInstance().getRootDir(),"logs/slaves/"+nodeName);
if (!dir.exists() && !dir.mkdirs()) {
LOGGER.severe("Failed to create slave log directory " + dir.getAbsolutePath());
}
return dir;
}
/**
* Gets the object that coordinates the workspace allocation on this computer.
*/
public WorkspaceList getWorkspaceList() {
return workspaceList;
}
/**
* Gets the string representation of the slave log.
*/
public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}
/**
* Used to URL-bind {@link AnnotatedLargeText}.
*/
public AnnotatedLargeText<Computer> getLogText() {
return new AnnotatedLargeText<Computer>(getLogFile(), Charset.defaultCharset(), false, this);
}
public ACL getACL() {
return Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
}
public void checkPermission(Permission permission) {
getACL().checkPermission(permission);
}
public boolean hasPermission(Permission permission) {
return getACL().hasPermission(permission);
}
/**
* If the computer was offline (either temporarily or not),
* this method will return the cause.
*
* @return
* null if the system was put offline without given a cause.
*/
@Exported
public OfflineCause getOfflineCause() {
return offlineCause;
}
/**
* If the computer was offline (either temporarily or not),
* this method will return the cause as a string (without user info).
*
* @return
* empty string if the system was put offline without given a cause.
*/
@Exported
public String getOfflineCauseReason() {
if (offlineCause == null) {
return "";
}
// fetch the localized string for "Disconnected By"
String gsub_base = hudson.slaves.Messages.SlaveComputer_DisconnectedBy("","");
// regex to remove commented reason base string
String gsub1 = "^" + gsub_base + "[\\w\\W]* \\: ";
// regex to remove non-commented reason base string
String gsub2 = "^" + gsub_base + "[\\w\\W]*";
String newString = offlineCause.toString().replaceAll(gsub1, "");
return newString.replaceAll(gsub2, "");
}
/**
* Gets the channel that can be used to run a program on this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract @Nullable VirtualChannel getChannel();
/**
* Gets the default charset of this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract Charset getDefaultCharset();
/**
* Gets the logs recorded by this slave.
*/
public abstract List<LogRecord> getLogRecords() throws IOException, InterruptedException;
/**
* If {@link #getChannel()}==null, attempts to relaunch the slave agent.
*/
public abstract void doLaunchSlaveAgent( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException;
/**
* @deprecated since 2009-01-06. Use {@link #connect(boolean)}
*/
@Deprecated
public final void launch() {
connect(true);
}
/**
* Do the same as {@link #doLaunchSlaveAgent(StaplerRequest, StaplerResponse)}
* but outside the context of serving a request.
*
* <p>
* If already connected or if this computer doesn't support proactive launching, no-op.
* This method may return immediately
* while the launch operation happens asynchronously.
*
* @see #disconnect()
*
* @param forceReconnect
* If true and a connect activity is already in progress, it will be cancelled and
* the new one will be started. If false, and a connect activity is already in progress, this method
* will do nothing and just return the pending connection operation.
* @return
* A {@link Future} representing pending completion of the task. The 'completion' includes
* both a successful completion and a non-successful completion (such distinction typically doesn't
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
public final Future<?> connect(boolean forceReconnect) {
connectTime = System.currentTimeMillis();
return _connect(forceReconnect);
}
/**
* Allows implementing-classes to provide an implementation for the connect method.
*
* <p>
* If already connected or if this computer doesn't support proactive launching, no-op.
* This method may return immediately
* while the launch operation happens asynchronously.
*
* @see #disconnect()
*
* @param forceReconnect
* If true and a connect activity is already in progress, it will be cancelled and
* the new one will be started. If false, and a connect activity is already in progress, this method
* will do nothing and just return the pending connection operation.
* @return
* A {@link Future} representing pending completion of the task. The 'completion' includes
* both a successful completion and a non-successful completion (such distinction typically doesn't
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
protected abstract Future<?> _connect(boolean forceReconnect);
/**
* CLI command to reconnect this node.
*/
@CLIMethod(name="connect-node")
public void cliConnect(@Option(name="-f",usage="Cancel any currently pending connect operation and retry from scratch") boolean force) throws ExecutionException, InterruptedException {
checkPermission(CONNECT);
connect(force).get();
}
/**
* Gets the time (since epoch) when this computer connected.
*
* @return The time in ms since epoch when this computer last connected.
*/
public final long getConnectTime() {
return connectTime;
}
/**
* Disconnect this computer.
*
* If this is the master, no-op. This method may return immediately
* while the launch operation happens asynchronously.
*
* @param cause
* Object that identifies the reason the node was disconnected.
*
* @return
* {@link Future} to track the asynchronous disconnect operation.
* @see #connect(boolean)
* @since 1.320
*/
public Future<?> disconnect(OfflineCause cause) {
recordTermination();
offlineCause = cause;
if (Util.isOverridden(Computer.class,getClass(),"disconnect"))
return disconnect(); // legacy subtypes that extend disconnect().
connectTime=0;
return Futures.precomputed(null);
}
/**
* Equivalent to {@code disconnect(null)}
*
* @deprecated as of 1.320.
* Use {@link #disconnect(OfflineCause)} and specify the cause.
*/
@Deprecated
public Future<?> disconnect() {
recordTermination();
if (Util.isOverridden(Computer.class,getClass(),"disconnect",OfflineCause.class))
// if the subtype already derives disconnect(OfflineCause), delegate to it
return disconnect(null);
connectTime=0;
return Futures.precomputed(null);
}
/**
* CLI command to disconnects this node.
*/
@CLIMethod(name="disconnect-node")
public void cliDisconnect(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
disconnect(new ByCLI(cause)).get();
}
/**
* CLI command to mark the node offline.
*/
@CLIMethod(name="offline-node")
public void cliOffline(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
setTemporarilyOffline(true, new ByCLI(cause));
}
@CLIMethod(name="online-node")
public void cliOnline() throws ExecutionException, InterruptedException {
checkPermission(CONNECT);
setTemporarilyOffline(false, null);
}
/**
* Number of {@link Executor}s that are configured for this computer.
*
* <p>
* When this value is decreased, it is temporarily possible
* for {@link #executors} to have a larger number than this.
*/
// ugly name to let EL access this
@Exported
public int getNumExecutors() {
return numExecutors;
}
/**
* Returns {@link Node#getNodeName() the name of the node}.
*/
public @Nonnull String getName() {
return nodeName != null ? nodeName : "";
}
/**
* True if this computer is a Unix machine (as opposed to Windows machine).
*
* @since 1.624
* @return
* null if the computer is disconnected and therefore we don't know whether it is Unix or not.
*/
public abstract @CheckForNull Boolean isUnix();
/**
* Returns the {@link Node} that this computer represents.
*
* @return
* null if the configuration has changed and the node is removed, yet the corresponding {@link Computer}
* is not yet gone.
*/
public @CheckForNull Node getNode() {
Jenkins j = Jenkins.getInstance();
if (j == null) {
return null;
}
if (nodeName == null) {
return j;
}
return j.getNode(nodeName);
}
@Exported
public LoadStatistics getLoadStatistics() {
return LabelAtom.get(nodeName != null ? nodeName : Jenkins.getInstance().getSelfLabel().toString()).loadStatistics;
}
public BuildTimelineWidget getTimeline() {
return new BuildTimelineWidget(getBuilds());
}
/**
* {@inheritDoc}
*/
public void taskAccepted(Executor executor, Queue.Task task) {
// dummy implementation
}
/**
* {@inheritDoc}
*/
public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
// dummy implementation
}
/**
* {@inheritDoc}
*/
public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) {
// dummy implementation
}
@Exported
public boolean isOffline() {
return temporarilyOffline || getChannel()==null;
}
public final boolean isOnline() {
return !isOffline();
}
/**
* This method is called to determine whether manual launching of the slave is allowed at this point in time.
* @return {@code true} if manual launching of the slave is allowed at this point in time.
*/
@Exported
public boolean isManualLaunchAllowed() {
return getRetentionStrategy().isManualLaunchAllowed(this);
}
/**
* Is a {@link #connect(boolean)} operation in progress?
*/
public abstract boolean isConnecting();
/**
* Returns true if this computer is supposed to be launched via JNLP.
* @deprecated since 2008-05-18.
* See {@linkplain #isLaunchSupported()} and {@linkplain ComputerLauncher}
*/
@Exported
@Deprecated
public boolean isJnlpAgent() {
return false;
}
/**
* Returns true if this computer can be launched by Hudson proactively and automatically.
*
* <p>
* For example, JNLP slaves return {@code false} from this, because the launch process
* needs to be initiated from the slave side.
*/
@Exported
public boolean isLaunchSupported() {
return true;
}
/**
* Returns true if this node is marked temporarily offline by the user.
*
* <p>
* In contrast, {@link #isOffline()} represents the actual online/offline
* state. For example, this method may return false while {@link #isOffline()}
* returns true if the slave agent failed to launch.
*
* @deprecated
* You should almost always want {@link #isOffline()}.
* This method is marked as deprecated to warn people when they
* accidentally call this method.
*/
@Exported
@Deprecated
public boolean isTemporarilyOffline() {
return temporarilyOffline;
}
/**
* @deprecated as of 1.320.
* Use {@link #setTemporarilyOffline(boolean, OfflineCause)}
*/
@Deprecated
public void setTemporarilyOffline(boolean temporarilyOffline) {
setTemporarilyOffline(temporarilyOffline,null);
}
/**
* Marks the computer as temporarily offline. This retains the underlying
* {@link Channel} connection, but prevent builds from executing.
*
* @param cause
* If the first argument is true, specify the reason why the node is being put
* offline.
*/
public void setTemporarilyOffline(boolean temporarilyOffline, OfflineCause cause) {
offlineCause = temporarilyOffline ? cause : null;
this.temporarilyOffline = temporarilyOffline;
Node node = getNode();
if (node != null) {
node.setTemporaryOfflineCause(offlineCause);
}
Jenkins.getInstance().getQueue().scheduleMaintenance();
synchronized (statusChangeLock) {
statusChangeLock.notifyAll();
}
for (ComputerListener cl : ComputerListener.all()) {
if (temporarilyOffline) cl.onTemporarilyOffline(this,cause);
else cl.onTemporarilyOnline(this);
}
}
@Exported
public String getIcon() {
if(isOffline())
return "computer-x.png";
else
return "computer.png";
}
@Exported
public String getIconClassName() {
if(isOffline())
return "icon-computer-x";
else
return "icon-computer";
}
public String getIconAltText() {
if(isOffline())
return "[offline]";
else
return "[online]";
}
@Exported
@Override public @Nonnull String getDisplayName() {
return nodeName;
}
public String getCaption() {
return Messages.Computer_Caption(nodeName);
}
public String getUrl() {
return "computer/" + Util.rawEncode(getName()) + "/";
}
/**
* Returns projects that are tied on this node.
*/
public List<AbstractProject> getTiedJobs() {
Node node = getNode();
return (node != null) ? node.getSelfLabel().getTiedJobs() : Collections.EMPTY_LIST;
}
public RunList getBuilds() {
return new RunList(Jenkins.getInstance().getAllItems(Job.class)).node(getNode());
}
/**
* Called to notify {@link Computer} that its corresponding {@link Node}
* configuration is updated.
*/
protected void setNode(Node node) {
assert node!=null;
if(node instanceof Slave)
this.nodeName = node.getNodeName();
else
this.nodeName = null;
setNumExecutors(node.getNumExecutors());
if (this.temporarilyOffline) {
// When we get a new node, push our current temp offline
// status to it (as the status is not carried across
// configuration changes that recreate the node).
// Since this is also called the very first time this
// Computer is created, avoid pushing an empty status
// as that could overwrite any status that the Node
// brought along from its persisted config data.
node.setTemporaryOfflineCause(this.offlineCause);
}
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* @see #onRemoved()
*/
protected void kill() {
// On most code paths, this should already be zero, and thus this next call becomes a no-op... and more
// importantly it will not acquire a lock on the Queue... not that the lock is bad, more that the lock
// may delay unnecessarily
setNumExecutors(0);
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* <p>
* Note that the Queue lock is already held when this method is called.
*
* @see #onRemoved()
*/
@Restricted(NoExternalUse.class)
@GuardedBy("hudson.model.Queue.lock")
/*package*/ void inflictMortalWound() {
setNumExecutors(0);
}
/**
* Called by {@link Jenkins} when this computer is removed.
*
* <p>
* This happens when list of nodes are updated (for example by {@link Jenkins#setNodes(List)} and
* the computer becomes redundant. Such {@link Computer}s get {@linkplain #kill() killed}, then
* after all its executors are finished, this method is called.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* @see #kill()
* @since 1.510
*/
protected void onRemoved(){
}
private synchronized void setNumExecutors(int n) {
this.numExecutors = n;
final int diff = executors.size()-n;
if (diff>0) {
// we have too many executors
// send signal to all idle executors to potentially kill them off
// need the Queue maintenance lock held to prevent concurrent job assignment on the idle executors
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Executor e : executors )
if(e.isIdle())
e.interrupt();
}
});
}
if (diff<0) {
// if the number is increased, add new ones
addNewExecutorIfNecessary();
}
}
private void addNewExecutorIfNecessary() {
Set<Integer> availableNumbers = new HashSet<Integer>();
for (int i = 0; i < numExecutors; i++)
availableNumbers.add(i);
for (Executor executor : executors)
availableNumbers.remove(executor.getNumber());
for (Integer number : availableNumbers) {
/* There may be busy executors with higher index, so only
fill up until numExecutors is reached.
Extra executors will call removeExecutor(...) and that
will create any necessary executors from #0 again. */
if (executors.size() < numExecutors) {
Executor e = new Executor(this, number);
executors.add(e);
}
}
}
/**
* Returns the number of idle {@link Executor}s that can start working immediately.
*/
public int countIdle() {
int n = 0;
for (Executor e : executors) {
if(e.isIdle())
n++;
}
return n;
}
/**
* Returns the number of {@link Executor}s that are doing some work right now.
*/
public final int countBusy() {
return countExecutors()-countIdle();
}
/**
* Returns the current size of the executor pool for this computer.
* This number may temporarily differ from {@link #getNumExecutors()} if there
* are busy tasks when the configured size is decreased. OneOffExecutors are
* not included in this count.
*/
public final int countExecutors() {
return executors.size();
}
/**
* Gets the read-only snapshot view of all {@link Executor}s.
*/
@Exported
public List<Executor> getExecutors() {
return new ArrayList<Executor>(executors);
}
/**
* Gets the read-only snapshot view of all {@link OneOffExecutor}s.
*/
@Exported
public List<OneOffExecutor> getOneOffExecutors() {
return new ArrayList<OneOffExecutor>(oneOffExecutors);
}
/**
* Used to render the list of executors.
* @return a snapshot of the executor display information
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public List<DisplayExecutor> getDisplayExecutors() {
// The size may change while we are populating, but let's start with a reasonable guess to minimize resizing
List<DisplayExecutor> result = new ArrayList<DisplayExecutor>(executors.size()+oneOffExecutors.size());
int index = 0;
for (Executor e: executors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor(Integer.toString(index + 1), String.format("executors/%d", index), e));
}
index++;
}
index = 0;
for (OneOffExecutor e: oneOffExecutors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor("", String.format("oneOffExecutors/%d", index), e));
}
index++;
}
return result;
}
/**
* Returns true if all the executors of this computer are idle.
*/
@Exported
public final boolean isIdle() {
if (!oneOffExecutors.isEmpty())
return false;
for (Executor e : executors)
if(!e.isIdle())
return false;
return true;
}
/**
* Returns true if this computer has some idle executors that can take more workload.
*/
public final boolean isPartiallyIdle() {
for (Executor e : executors)
if(e.isIdle())
return true;
return false;
}
/**
* Returns the time when this computer last became idle.
*
* <p>
* If this computer is already idle, the return value will point to the
* time in the past since when this computer has been idle.
*
* <p>
* If this computer is busy, the return value will point to the
* time in the future where this computer will be expected to become free.
*/
public final long getIdleStartMilliseconds() {
long firstIdle = Long.MIN_VALUE;
for (Executor e : oneOffExecutors) {
firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
}
for (Executor e : executors) {
firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
}
return firstIdle;
}
/**
* Returns the time when this computer first became in demand.
*/
public final long getDemandStartMilliseconds() {
long firstDemand = Long.MAX_VALUE;
for (Queue.BuildableItem item : Jenkins.getInstance().getQueue().getBuildableItems(this)) {
firstDemand = Math.min(item.buildableStartMilliseconds, firstDemand);
}
return firstDemand;
}
/**
* Called by {@link Executor} to kill excessive executors from this computer.
*/
/*package*/ void removeExecutor(final Executor e) {
final Runnable task = new Runnable() {
@Override
public void run() {
synchronized (Computer.this) {
executors.remove(e);
addNewExecutorIfNecessary();
if (!isAlive()) {
AbstractCIBase ciBase = Jenkins.getInstance();
if (ciBase != null) {
ciBase.removeComputer(Computer.this);
}
}
}
}
};
if (!Queue.tryWithLock(task)) {
// JENKINS-28840 if we couldn't get the lock push the operation to a separate thread to avoid deadlocks
threadPoolForRemoting.submit(Queue.wrapWithLock(task));
}
}
/**
* Returns true if any of the executors are {@linkplain Executor#isActive active}.
*
* Note that if an executor dies, we'll leave it in {@link #executors} until
* the administrator yanks it out, so that we can see why it died.
*
* @since 1.509
*/
protected boolean isAlive() {
for (Executor e : executors)
if (e.isActive())
return true;
return false;
}
/**
* Interrupt all {@link Executor}s.
* Called from {@link Jenkins#cleanUp}.
*/
public void interrupt() {
Queue.withLock(new Runnable() {
@Override
public void run() {
for (Executor e : executors) {
e.interruptForShutdown();
}
}
});
}
public String getSearchUrl() {
return getUrl();
}
/**
* {@link RetentionStrategy} associated with this computer.
*
* @return
* never null. This method return {@code RetentionStrategy<? super T>} where
* {@code T=this.getClass()}.
*/
public abstract RetentionStrategy getRetentionStrategy();
/**
* Expose monitoring data for the remote API.
*/
@Exported(inline=true)
public Map<String/*monitor name*/,Object> getMonitorData() {
Map<String,Object> r = new HashMap<String, Object>();
if (hasPermission(CONNECT)) {
for (NodeMonitor monitor : NodeMonitor.getAll())
r.put(monitor.getClass().getName(), monitor.data(this));
}
return r;
}
/**
* Gets the system properties of the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public Map<Object,Object> getSystemProperties() throws IOException, InterruptedException {
return RemotingDiagnostics.getSystemProperties(getChannel());
}
/**
* @deprecated as of 1.292
* Use {@link #getEnvironment()} instead.
*/
@Deprecated
public Map<String,String> getEnvVars() throws IOException, InterruptedException {
return getEnvironment();
}
/**
* Returns cached environment variables (copy to prevent modification) for the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public EnvVars getEnvironment() throws IOException, InterruptedException {
EnvVars cachedEnvironment = this.cachedEnvironment;
if (cachedEnvironment != null) {
return new EnvVars(cachedEnvironment);
}
cachedEnvironment = EnvVars.getRemote(getChannel());
this.cachedEnvironment = cachedEnvironment;
return new EnvVars(cachedEnvironment);
}
/**
* Creates an environment variable override to be used for launching processes on this node.
*
* @see ProcStarter#envs(Map)
* @since 1.489
*/
public @Nonnull EnvVars buildEnvironment(@Nonnull TaskListener listener) throws IOException, InterruptedException {
EnvVars env = new EnvVars();
Node node = getNode();
if (node==null) return env; // bail out
for (NodeProperty nodeProperty: Jenkins.getInstance().getGlobalNodeProperties()) {
nodeProperty.buildEnvVars(env,listener);
}
for (NodeProperty nodeProperty: node.getNodeProperties()) {
nodeProperty.buildEnvVars(env,listener);
}
// TODO: hmm, they don't really belong
String rootUrl = Jenkins.getInstance().getRootUrl();
if(rootUrl!=null) {
env.put("HUDSON_URL", rootUrl); // Legacy.
env.put("JENKINS_URL", rootUrl);
}
return env;
}
/**
* Gets the thread dump of the slave JVM.
* @return
* key is the thread name, and the value is the pre-formatted dump.
*/
public Map<String,String> getThreadDump() throws IOException, InterruptedException {
return RemotingDiagnostics.getThreadDump(getChannel());
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,getChannel());
}
/**
* This method tries to compute the name of the host that's reachable by all the other nodes.
*
* <p>
* Since it's possible that the slave is not reachable from the master (it may be behind a firewall,
* connecting to master via JNLP), this method may return null.
*
* It's surprisingly tricky for a machine to know a name that other systems can get to,
* especially between things like DNS search suffix, the hosts file, and YP.
*
* <p>
* So the technique here is to compute possible interfaces and names on the slave,
* then try to ping them from the master, and pick the one that worked.
*
* <p>
* The computation may take some time, so it employs caching to make the successive lookups faster.
*
* @since 1.300
* @return
* null if the host name cannot be computed (for example because this computer is offline,
* because the slave is behind the firewall, etc.)
*/
public String getHostName() throws IOException, InterruptedException {
if(hostNameCached)
// in the worst case we end up having multiple threads computing the host name simultaneously, but that's not harmful, just wasteful.
return cachedHostName;
VirtualChannel channel = getChannel();
if(channel==null) return null; // can't compute right now
for( String address : channel.call(new ListPossibleNames())) {
try {
InetAddress ia = InetAddress.getByName(address);
if(!(ia instanceof Inet4Address)) {
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address);
continue;
}
if(!ComputerPinger.checkIsReachable(ia, 3)) {
LOGGER.log(Level.FINE, "{0} didn't respond to ping", address);
continue;
}
cachedHostName = ia.getCanonicalHostName();
hostNameCached = true;
return cachedHostName;
} catch (IOException e) {
// if a given name fails to parse on this host, we get this error
LogRecord lr = new LogRecord(Level.FINE, "Failed to parse {0}");
lr.setThrown(e);
lr.setParameters(new Object[]{address});
LOGGER.log(lr);
}
}
// allow the administrator to manually specify the host name as a fallback. HUDSON-5373
cachedHostName = channel.call(new GetFallbackName());
hostNameCached = true;
return cachedHostName;
}
/**
* Starts executing a fly-weight task.
*/
/*package*/ final void startFlyWeightTask(WorkUnit p) {
OneOffExecutor e = new OneOffExecutor(this);
e.start(p);
oneOffExecutors.add(e);
}
/*package*/ final void remove(OneOffExecutor e) {
oneOffExecutors.remove(e);
}
private static class ListPossibleNames extends MasterToSlaveCallable<List<String>,IOException> {
/**
* In the normal case we would use {@link Computer} as the logger's name, however to
* do that we would have to send the {@link Computer} class over to the remote classloader
* and then it would need to be loaded, which pulls in {@link Jenkins} and loads that
* and then that fails to load as you are not supposed to do that. Another option
* would be to export the logger over remoting, with increased complexity as a result.
* Instead we just use a loger based on this class name and prevent any references to
* other classes from being transferred over remoting.
*/
private static final Logger LOGGER = Logger.getLogger(ListPossibleNames.class.getName());
public List<String> call() throws IOException {
List<String> names = new ArrayList<String>();
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
LOGGER.log(Level.FINE, "Listing up IP addresses for {0}", ni.getDisplayName());
Enumeration<InetAddress> e = ni.getInetAddresses();
while (e.hasMoreElements()) {
InetAddress ia = e.nextElement();
if(ia.isLoopbackAddress()) {
LOGGER.log(Level.FINE, "{0} is a loopback address", ia);
continue;
}
if(!(ia instanceof Inet4Address)) {
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", ia);
continue;
}
LOGGER.log(Level.FINE, "{0} is a viable candidate", ia);
names.add(ia.getHostAddress());
}
}
return names;
}
private static final long serialVersionUID = 1L;
}
private static class GetFallbackName extends MasterToSlaveCallable<String,IOException> {
public String call() throws IOException {
return System.getProperty("host.name");
}
private static final long serialVersionUID = 1L;
}
public static final ExecutorService threadPoolForRemoting = new ContextResettingExecutorService(
Executors.newCachedThreadPool(
new ExceptionCatchingThreadFactory(
new NamingThreadFactory(new DaemonThreadFactory(), "Computer.threadPoolForRemoting"))));
//
//
// UI
//
//
public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " all builds", getBuilds());
}
public void doRssFailed(StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " failed builds", getBuilds().failureOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName() + suffix, getUrl(),
runs.newBuilds(), Run.FEED_ADAPTER, req, rsp);
}
@RequirePOST
public HttpResponse doToggleOffline(@QueryParameter String offlineMessage) throws IOException, ServletException {
if(!temporarilyOffline) {
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(!temporarilyOffline,
new OfflineCause.UserCause(User.current(), offlineMessage));
} else {
checkPermission(CONNECT);
setTemporarilyOffline(!temporarilyOffline,null);
}
return HttpResponses.redirectToDot();
}
@RequirePOST
public HttpResponse doChangeOfflineCause(@QueryParameter String offlineMessage) throws IOException, ServletException {
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(true,
new OfflineCause.UserCause(User.current(), offlineMessage));
return HttpResponses.redirectToDot();
}
public Api getApi() {
return new Api(this);
}
/**
* Dumps the contents of the export table.
*/
public void doDumpExportTable( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
// this is a debug probe and may expose sensitive information
checkPermission(Jenkins.ADMINISTER);
rsp.setContentType("text/plain");
PrintWriter w = new PrintWriter(rsp.getCompressedWriter(req));
VirtualChannel vc = getChannel();
if (vc instanceof Channel) {
w.println("Master to slave");
((Channel)vc).dumpExportTable(w);
w.flush(); // flush here once so that even if the dump from the slave fails, the client gets some useful info
w.println("\n\n\nSlave to master");
w.print(vc.call(new DumpExportTableTask()));
} else {
w.println(Messages.Computer_BadChannel());
}
w.close();
}
private static final class DumpExportTableTask extends MasterToSlaveCallable<String,IOException> {
public String call() throws IOException {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Channel.current().dumpExportTable(pw);
pw.close();
return sw.toString();
}
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, "_script.jelly");
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, "_scriptText.jelly");
}
protected void _doScript(StaplerRequest req, StaplerResponse rsp, String view) throws IOException, ServletException {
Jenkins._doScript(req, rsp, req.getView(this, view), getChannel(), getACL());
}
/**
* Accepts the update to the node configuration.
*/
@RequirePOST
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(CONFIGURE);
String name = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name"));
Jenkins.checkGoodName(name);
Node node = getNode();
if (node == null) {
throw new ServletException("No such node " + nodeName);
}
Node result = node.reconfigure(req, req.getSubmittedForm());
replaceBy(result);
// take the user back to the slave top page.
rsp.sendRedirect2("../" + result.getNodeName() + '/');
}
/**
* Accepts <tt>config.xml</tt> submission, as well as serve it.
*/
@WebMethod(name = "config.xml")
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
if (req.getMethod().equals("GET")) {
// read
checkPermission(EXTENDED_READ);
rsp.setContentType("application/xml");
Node node = getNode();
if (node == null) {
throw HttpResponses.notFound();
}
Jenkins.XSTREAM2.toXMLUTF8(node, rsp.getOutputStream());
return;
}
if (req.getMethod().equals("POST")) {
// submission
updateByXml(req.getInputStream());
return;
}
// huh?
rsp.sendError(SC_BAD_REQUEST);
}
/**
* Replaces the current {@link Node} by another one.
*/
private void replaceBy(final Node newNode) throws ServletException, IOException {
final Jenkins app = Jenkins.getInstance();
// use the queue lock until Nodes has a way of directly modifying a single node.
Queue.withLock(new NotReallyRoleSensitiveCallable<Void, IOException>() {
public Void call() throws IOException {
List<Node> nodes = new ArrayList<Node>(app.getNodes());
Node node = getNode();
int i = (node != null) ? nodes.indexOf(node) : -1;
if(i<0) {
throw new IOException("This slave appears to be removed while you were editing the configuration");
}
nodes.set(i, newNode);
app.setNodes(nodes);
return null;
}
});
}
/**
* Updates Job by its XML definition.
*
* @since 1.526
*/
public void updateByXml(final InputStream source) throws IOException, ServletException {
checkPermission(CONFIGURE);
Node result = (Node)Jenkins.XSTREAM2.fromXML(source);
replaceBy(result);
}
/**
* Really deletes the slave.
*/
@RequirePOST
public HttpResponse doDoDelete() throws IOException {
checkPermission(DELETE);
Node node = getNode();
if (node != null) {
Jenkins.getInstance().removeNode(node);
} else {
AbstractCIBase app = Jenkins.getInstance();
app.removeComputer(this);
}
return new HttpRedirect("..");
}
/**
* Blocks until the node becomes online/offline.
*/
@CLIMethod(name="wait-node-online")
public void waitUntilOnline() throws InterruptedException {
synchronized (statusChangeLock) {
while (!isOnline())
statusChangeLock.wait(1000);
}
}
@CLIMethod(name="wait-node-offline")
public void waitUntilOffline() throws InterruptedException {
synchronized (statusChangeLock) {
while (!isOffline())
statusChangeLock.wait(1000);
}
}
/**
* Handles incremental log.
*/
public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
getLogText().doProgressText(req, rsp);
}
/**
* Gets the current {@link Computer} that the build is running.
* This method only works when called during a build, such as by
* {@link hudson.tasks.Publisher}, {@link hudson.tasks.BuildWrapper}, etc.
* @return the {@link Computer} associated with {@link Executor#currentExecutor}, or (consistently as of 1.591) null if not on an executor thread
*/
public static @Nullable Computer currentComputer() {
Executor e = Executor.currentExecutor();
return e != null ? e.getOwner() : null;
}
/**
* Returns {@code true} if the computer is accepting tasks. Needed to allow slaves programmatic suspension of task
* scheduling that does not overlap with being offline.
*
* @return {@code true} if the computer is accepting tasks
* @see hudson.slaves.RetentionStrategy#isAcceptingTasks(Computer)
* @see hudson.model.Node#isAcceptingTasks()
*/
@OverrideMustInvoke(When.ANYTIME)
public boolean isAcceptingTasks() {
final Node node = getNode();
return getRetentionStrategy().isAcceptingTasks(this) && (node == null || node.isAcceptingTasks());
}
/**
* Used for CLI binding.
*/
@CLIResolver
public static Computer resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Slave name, or empty string for master") String name) throws CmdLineException {
Jenkins h = Jenkins.getInstance();
Computer item = h.getComputer(name);
if (item==null) {
List<String> names = new ArrayList<String>();
for (Computer c : h.getComputers())
if (c.getName().length()>0)
names.add(c.getName());
throw new CmdLineException(null,Messages.Computer_NoSuchSlaveExists(name,EditDistance.findNearest(name,names)));
}
return item;
}
/**
* Relocate log files in the old location to the new location.
*
* Files were used to be $JENKINS_ROOT/slave-NAME.log (and .1, .2, ...)
* but now they are at $JENKINS_ROOT/logs/slaves/NAME/slave.log (and .1, .2, ...)
*
* @see #getLogFile()
*/
@Initializer
public static void relocateOldLogs() {
relocateOldLogs(Jenkins.getInstance().getRootDir());
}
/*package*/ static void relocateOldLogs(File dir) {
final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?");
File[] logfiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return logfile.matcher(name).matches();
}
});
if (logfiles==null) return;
for (File f : logfiles) {
Matcher m = logfile.matcher(f.getName());
if (m.matches()) {
File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2)));
newLocation.getParentFile().mkdirs();
boolean relocationSuccessfull=f.renameTo(newLocation);
if (relocationSuccessfull) { // The operation will fail if mkdir fails
LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
} else {
LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
}
} else {
assert false;
}
}
}
/**
* A value class to provide a consistent snapshot view of the state of an executor to avoid race conditions
* during rendering of the executors list.
*
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public static class DisplayExecutor implements ModelObject {
@Nonnull
private final String displayName;
@Nonnull
private final String url;
@Nonnull
private final Executor executor;
public DisplayExecutor(@Nonnull String displayName, @Nonnull String url, @Nonnull Executor executor) {
this.displayName = displayName;
this.url = url;
this.executor = executor;
}
@Override
@Nonnull
public String getDisplayName() {
return displayName;
}
@Nonnull
public String getUrl() {
return url;
}
@Nonnull
public Executor getExecutor() {
return executor;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DisplayExecutor{");
sb.append("displayName='").append(displayName).append('\'');
sb.append(", url='").append(url).append('\'');
sb.append(", executor=").append(executor);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DisplayExecutor that = (DisplayExecutor) o;
if (!executor.equals(that.executor)) {
return false;
}
return true;
}
@Extension(ordinal = Double.MAX_VALUE)
@Restricted(DoNotUse.class)
public static class InternalComputerListener extends ComputerListener {
@Override
public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
c.cachedEnvironment = null;
}
}
@Override
public int hashCode() {
return executor.hashCode();
}
}
/**
* Used to trace requests to terminate a computer.
*
* @since 1.607
*/
public static class TerminationRequest extends RuntimeException {
private final long when;
public TerminationRequest(String message) {
super(message);
this.when = System.currentTimeMillis();
}
/**
* Returns the when the termination request was created.
*
* @return the difference, measured in milliseconds, between
* the time of the termination request and midnight, January 1, 1970 UTC.
*/
public long getWhen() {
return when;
}
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Computer.class,Messages._Computer_Permissions_Title());
public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._Computer_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.COMPUTER);
/**
* @since 1.532
*/
public static final Permission EXTENDED_READ = new Permission(PERMISSIONS,"ExtendedRead", Messages._Computer_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.COMPUTER});
public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._Computer_DeletePermission_Description(), Permission.DELETE, PermissionScope.COMPUTER);
public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._Computer_CreatePermission_Description(), Permission.CREATE, PermissionScope.COMPUTER);
public static final Permission DISCONNECT = new Permission(PERMISSIONS,"Disconnect", Messages._Computer_DisconnectPermission_Description(), Jenkins.ADMINISTER, PermissionScope.COMPUTER);
public static final Permission CONNECT = new Permission(PERMISSIONS,"Connect", Messages._Computer_ConnectPermission_Description(), DISCONNECT, PermissionScope.COMPUTER);
public static final Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._Computer_BuildPermission_Description(), Permission.WRITE, PermissionScope.COMPUTER);
private static final Logger LOGGER = Logger.getLogger(Computer.class.getName());
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_3048_0
|
crossvul-java_data_good_4347_4
|
/*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
/**
* Aspecto encargado de realizar el log de rendimiento de los Controllers.
*/
@Configuration
@ConditionalOnProperty(name = "application.log.enabled", havingValue = "true", matchIfMissing = true)
public class ControllerLoggerAspectConfiguration {
private static final Logger log = LoggerFactory.getLogger("org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable");
@Aspect
@Order(1)
@Component
public class ControllerLoggerAspect {
@Before("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..controller..*(..))")
public void logBefore(JoinPoint joinPoint) {
if (log.isDebugEnabled()) {
log.debug("************************* INIT CONTROLLER *********************************");
log.debug("Controller : Entering in Method : {}", joinPoint.getSignature().getDeclaringTypeName());
log.debug("Controller : Method : {}", joinPoint.getSignature().getName());
log.debug("Controller : Arguments : {}", Arrays.toString(joinPoint.getArgs()));
log.debug("Controller : Target class : {}", joinPoint.getTarget().getClass().getName());
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes()).getRequest();
if (null != request) {
log.debug("Controller : Start Header Section of request ");
log.debug("Controller : Method Type : {}", request.getMethod());
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if (!headerName.startsWith("x-forwarded")) {
String headerValue = request.getHeader(headerName);
log.debug("Controller : [Header Name]:{}|[Header Value]:{}", headerName, headerValue);
}
}
log.debug("Controller : Request Path info : {}", request.getServletPath());
log.debug("Controller : End Header Section of request ");
}
}
}
@AfterThrowing(pointcut = "execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..controller..*(..))", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
log.error("Controller : An exception has been thrown in {} ()", joinPoint.getSignature().getName());
log.error("Controller : Cause : {}", exception.getCause());
log.error("Controller : Message : {}", exception.getMessage());
log.debug("************************* END CONTROLLER **********************************");
}
@Around("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..controller..*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
try {
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - start;
log.debug("Controller : Controller {}.{} () execution time: {} ms", className, methodName, elapsedTime);
if ((null != result) && (result instanceof ResponseEntity) && log.isDebugEnabled()) {
Object dataReturned = ((ResponseEntity<?>) result).getBody();
HttpStatus returnedStatus = ((ResponseEntity<?>) result).getStatusCode();
HttpHeaders headers = ((ResponseEntity<?>) result).getHeaders();
log.debug("Controller : Controller Return value : <{}, {}>", returnedStatus, dataReturned);
log.debug("Controller : Start Header Section of response ");
if ((headers != null) && (!headers.isEmpty())) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
log.debug("Controller : [Header Name]:{}|[Header Value]:{}", entry.getKey(),
entry.getValue());
}
}
log.debug("Controller : End Header Section of response ");
}
log.debug("************************* END CONTROLLER **********************************");
return result;
} catch (IllegalArgumentException e) {
log.error("Controller : Illegal argument {} in {}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getName(), e);
throw e;
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_4347_4
|
crossvul-java_data_bad_1503_1
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.security.negotiation;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.ReferralException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.CompositeName;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.jboss.security.SimpleGroup;
import org.jboss.security.negotiation.common.CommonLoginModule;
import org.jboss.security.negotiation.prototype.DecodeAction;
import org.jboss.security.vault.SecurityVaultUtil;
import org.jboss.security.vault.SecurityVaultException;
/**
* Another LDAP LoginModule to take into account requirements
* for different authentication mechanisms and full support
* for password-stacking set to useFirstPass.
*
* This is essentially a complete refactoring of the LdapExtLoginModule
* but with enough restructuring to separate out the three login steps: -
* -1 Find the user
* -2 Authenticate as the user
* -3 Find the users roles
* Configuration should allow for any of the three actions to be
* skipped based on the requirements for the environment making
* use of this login module.
*
*
* @author darran.lofthouse@jboss.com
* @since 3rd July 2008
*/
public class AdvancedLdapLoginModule extends CommonLoginModule
{
/*
* Configuration Option Constants
*/
// Search Context Settings
private static final String BIND_AUTHENTICATION = "bindAuthentication";
private static final String BIND_DN = "bindDN";
private static final String BIND_CREDENTIAL = "bindCredential";
private static final String SECURITY_DOMAIN = "jaasSecurityDomain";
// User Search Settings
private static final String BASE_CTX_DN = "baseCtxDN";
private static final String BASE_FILTER = "baseFilter";
private static final String SEARCH_TIME_LIMIT = "searchTimeLimit";
// Role Search Settings
private static final String ROLES_CTS_DN = "rolesCtxDN";
private static final String ROLE_FILTER = "roleFilter";
private static final String RECURSE_ROLES = "recurseRoles";
private static final String ROLE_ATTRIBUTE_ID = "roleAttributeID";
private static final String ROLE_ATTRIBUTE_IS_DN = "roleAttributeIsDN";
private static final String ROLE_NAME_ATTRIBUTE_ID = "roleNameAttributeID";
private static final String ROLE_SEARCH_SCOPE = "searchScope";
private static final String REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK = "referralUserAttributeIDToCheck";
// Authentication Settings
private static final String ALLOW_EMPTY_PASSWORD = "allowEmptyPassword";
/*
* Other Constants
*/
private static final String AUTH_TYPE_GSSAPI = "GSSAPI";
private static final String AUTH_TYPE_SIMPLE = "simple";
private static final String DEFAULT_LDAP_CTX_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private static final String DEFAULT_URL = "ldap://localhost:389";
private static final String DEFAULT_SSL_URL = "ldap://localhost:686";
private static final String PROTOCOL_SSL = "SSL";
private static final String OBJECT_SCOPE = "OBJECT_SCOPE";
private static final String ONELEVEL_SCOPE = "ONELEVEL_SCOPE";
private static final String SUBTREE_SCOPE = "SUBTREE_SCOPE";
private static final String[] ALL_VALID_OPTIONS =
{
BIND_AUTHENTICATION,BIND_DN,BIND_CREDENTIAL,SECURITY_DOMAIN,
BASE_CTX_DN,BASE_FILTER,SEARCH_TIME_LIMIT,
ROLES_CTS_DN,ROLE_FILTER,RECURSE_ROLES,ROLE_ATTRIBUTE_ID,ROLE_ATTRIBUTE_IS_DN,ROLE_NAME_ATTRIBUTE_ID,ROLE_SEARCH_SCOPE,
ALLOW_EMPTY_PASSWORD,REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK,
Context.INITIAL_CONTEXT_FACTORY,
Context.OBJECT_FACTORIES,
Context.STATE_FACTORIES,
Context.URL_PKG_PREFIXES,
Context.PROVIDER_URL,
Context.DNS_URL,
Context.AUTHORITATIVE,
Context.BATCHSIZE,
Context.REFERRAL,
Context.SECURITY_PROTOCOL,
Context.SECURITY_AUTHENTICATION,
Context.SECURITY_PRINCIPAL,
Context.SECURITY_CREDENTIALS,
Context.LANGUAGE,
Context.APPLET
};
/*
* Configuration Options
*/
// Search Context Settings
protected String bindAuthentication;
protected String bindDn;
protected String bindCredential;
protected String jaasSecurityDomain;
// User Search Settings
protected String baseCtxDN;
protected String baseFilter;
protected int searchTimeLimit = 10000;
protected SearchControls userSearchControls;
// Role Search Settings
protected String rolesCtxDN;
protected String roleFilter;
protected boolean recurseRoles;
protected SearchControls roleSearchControls;
protected String roleAttributeID;
protected boolean roleAttributeIsDN;
protected String roleNameAttributeID;
protected String referralUserAttributeIDToCheck = null;
// Authentication Settings
protected boolean allowEmptyPassword;
// inner state fields
private String referralUserDNToCheck;
/*
* Module State
*/
private SimpleGroup userRoles = new SimpleGroup("Roles");
private Set<String> processedRoleDNs = new HashSet<String>();
private boolean trace;
@Override
public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
{
addValidOptions(ALL_VALID_OPTIONS);
super.initialize(subject, handler, sharedState, options);
trace = log.isTraceEnabled();
// Search Context Settings
bindAuthentication = (String) options.get(BIND_AUTHENTICATION);
bindDn = (String) options.get(BIND_DN);
bindCredential = (String) options.get(BIND_CREDENTIAL);
try
{
//Check if the credential is vaultified
if(bindCredential != null && SecurityVaultUtil.isVaultFormat(bindCredential))
{
bindCredential = SecurityVaultUtil.getValueAsString(bindCredential);
}
}
catch (SecurityVaultException e)
{
log.warn("Unable to obtain bindCredentials from Vault: ", e);
}
jaasSecurityDomain = (String) options.get(SECURITY_DOMAIN);
// User Search Settings
baseCtxDN = (String) options.get(BASE_CTX_DN);
baseFilter = (String) options.get(BASE_FILTER);
String temp = (String) options.get(SEARCH_TIME_LIMIT);
if (temp != null)
{
try
{
searchTimeLimit = Integer.parseInt(temp);
}
catch (NumberFormatException e)
{
log.warn("Failed to parse: " + temp + ", using searchTimeLimit=" + searchTimeLimit);
}
}
userSearchControls = new SearchControls();
userSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
userSearchControls.setReturningAttributes(new String[0]);
userSearchControls.setTimeLimit(searchTimeLimit);
rolesCtxDN = (String) options.get(ROLES_CTS_DN);
roleFilter = (String) options.get(ROLE_FILTER);
referralUserAttributeIDToCheck = (String) options.get(REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK);
temp = (String) options.get(RECURSE_ROLES);
recurseRoles = Boolean.parseBoolean(temp);
int searchScope = SearchControls.SUBTREE_SCOPE;
temp = (String) options.get(ROLE_SEARCH_SCOPE);
if (OBJECT_SCOPE.equalsIgnoreCase(temp))
{
searchScope = SearchControls.OBJECT_SCOPE;
}
else if (ONELEVEL_SCOPE.equalsIgnoreCase(temp))
{
searchScope = SearchControls.ONELEVEL_SCOPE;
}
if (SUBTREE_SCOPE.equalsIgnoreCase(temp))
{
searchScope = SearchControls.SUBTREE_SCOPE;
}
roleSearchControls = new SearchControls();
roleSearchControls.setSearchScope(searchScope);
roleSearchControls.setTimeLimit(searchTimeLimit);
roleAttributeID = (String) options.get(ROLE_ATTRIBUTE_ID);
temp = (String) options.get(ROLE_ATTRIBUTE_IS_DN);
roleAttributeIsDN = Boolean.parseBoolean(temp);
roleNameAttributeID = (String) options.get(ROLE_NAME_ATTRIBUTE_ID);
ArrayList<String> roleSearchAttributeList = new ArrayList<String>(3);
if (roleAttributeID != null)
{
roleSearchAttributeList.add(roleAttributeID);
}
if (roleNameAttributeID != null)
{
roleSearchAttributeList.add(roleNameAttributeID);
}
if (referralUserAttributeIDToCheck != null)
{
roleSearchAttributeList.add(referralUserAttributeIDToCheck);
}
roleSearchControls.setReturningAttributes(roleSearchAttributeList.toArray(new String[0]));
temp = (String) options.get(ALLOW_EMPTY_PASSWORD);
allowEmptyPassword = Boolean.parseBoolean(temp);
}
@Override
public boolean login() throws LoginException
{
Object result = null;
AuthorizeAction action = new AuthorizeAction();
if (AUTH_TYPE_GSSAPI.equals(bindAuthentication))
{
log.trace("Using GSSAPI to connect to LDAP");
LoginContext lc = new LoginContext(jaasSecurityDomain);
lc.login();
Subject serverSubject = lc.getSubject();
if (log.isDebugEnabled())
{
log.debug("Subject = " + serverSubject);
log.debug("Logged in '" + lc + "' LoginContext");
}
result = Subject.doAs(serverSubject, action);
lc.logout();
}
else
{
result = action.run();
}
if (result instanceof LoginException)
{
throw (LoginException) result;
}
return ((Boolean) result).booleanValue();
}
@Override
protected Group[] getRoleSets() throws LoginException
{
Group[] roleSets =
{userRoles};
return roleSets;
}
protected Boolean innerLogin() throws LoginException
{
// Obtain the username and password
processIdentityAndCredential();
if (trace) {
log.trace("Identity - " + getIdentity().getName());
}
// Initialise search ctx
String bindCredential = this.bindCredential;
if (AUTH_TYPE_GSSAPI.equals(bindAuthentication) == false)
{
if (jaasSecurityDomain != null && jaasSecurityDomain.length() > 0)
{
try
{
ObjectName serviceName = new ObjectName(jaasSecurityDomain);
char[] tmp = DecodeAction.decode(bindCredential, serviceName);
bindCredential = new String(tmp);
}
catch (Exception e)
{
LoginException le = new LoginException("Unable to decode bindCredential");
le.initCause(e);
throw le;
}
}
}
LdapContext searchContext = null;
try
{
searchContext = constructLdapContext(null, bindDn, bindCredential, bindAuthentication);
log.debug("Obtained LdapContext");
// Search for user in LDAP
String userDN = findUserDN(searchContext);
if (referralUserAttributeIDToCheck != null)
{
if (isUserDnAbsolute(userDN))
{
referralUserDNToCheck = localUserDN(userDN);
}
else
{
referralUserDNToCheck = userDN;
}
}
// If authentication required authenticate as user
if (super.loginOk == false)
{
authenticate(userDN);
}
if (super.loginOk)
{
// Search for roles in LDAP
rolesSearch(searchContext, userDN);
}
}
finally
{
if (searchContext != null)
{
try
{
searchContext.close();
}
catch (NamingException e)
{
log.warn("Error closing context", e);
}
}
}
return Boolean.valueOf(super.loginOk);
}
private Properties constructLdapContextEnvironment(String namingProviderURL, String principalDN, Object credential, String authentication)
{
Properties env = createBaseProperties();
// Set defaults for key values if they are missing
String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
if (factoryName == null)
{
factoryName = DEFAULT_LDAP_CTX_FACTORY;
env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
}
// If this method is called with an authentication type then use that.
if (authentication != null && authentication.length() > 0)
{
env.setProperty(Context.SECURITY_AUTHENTICATION, authentication);
}
else
{
String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
if (authType == null)
env.setProperty(Context.SECURITY_AUTHENTICATION, AUTH_TYPE_SIMPLE);
}
String providerURL = null;
if (namingProviderURL != null)
{
providerURL = namingProviderURL;
}
else
{
providerURL = (String) options.get(Context.PROVIDER_URL);
}
String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
if (providerURL == null)
{
if (PROTOCOL_SSL.equals(protocol))
{
providerURL = DEFAULT_SSL_URL;
}
else
{
providerURL = DEFAULT_URL;
}
}
env.setProperty(Context.PROVIDER_URL, providerURL);
// Assume the caller of this method has checked the requirements for the principal and
// credentials.
if (principalDN != null)
env.setProperty(Context.SECURITY_PRINCIPAL, principalDN);
if (credential != null)
env.put(Context.SECURITY_CREDENTIALS, credential);
traceLdapEnv(env);
return env;
}
protected LdapContext constructLdapContext(String namingProviderURL, String dn, Object credential, String authentication)
throws LoginException
{
try
{
Properties env = constructLdapContextEnvironment(namingProviderURL, dn, credential, authentication);
return new InitialLdapContext(env, null);
}
catch (NamingException e)
{
LoginException le = new LoginException("Unable to create new InitialLdapContext");
le.initCause(e);
throw le;
}
}
protected Properties createBaseProperties()
{
Properties env = new Properties();
Iterator iter = options.entrySet().iterator();
while (iter.hasNext())
{
Entry entry = (Entry) iter.next();
env.put(entry.getKey(), entry.getValue());
}
return env;
}
protected String findUserDN(LdapContext ctx) throws LoginException
{
if (baseCtxDN == null)
{
return getIdentity().getName();
}
try
{
NamingEnumeration results = null;
Object[] filterArgs =
{getIdentity().getName()};
LdapContext ldapCtx = ctx;
boolean referralsLeft = true;
SearchResult sr = null;
while (referralsLeft)
{
try
{
results = ldapCtx.search(baseCtxDN, baseFilter, filterArgs, userSearchControls);
while (results.hasMore())
{
sr = (SearchResult) results.next();
break;
}
referralsLeft = false;
}
catch (ReferralException e)
{
ldapCtx = (LdapContext) e.getReferralContext();
if (results != null)
{
results.close();
}
}
}
if (sr == null)
{
results.close();
throw new LoginException("Search of baseDN(" + baseCtxDN + ") found no matches");
}
String name = sr.getName();
String userDN = null;
if (sr.isRelative() == true)
{
userDN = new CompositeName(name).get(0) + "," + baseCtxDN;
}
else
{
userDN = sr.getName();
}
results.close();
results = null;
if (trace) {
log.trace("findUserDN - " + userDN);
}
return userDN;
}
catch (NamingException e)
{
LoginException le = new LoginException("Unable to find user DN");
le.initCause(e);
throw le;
}
}
private void referralAuthenticate(String absoluteName, Object credential)
throws LoginException
{
URI uri;
try
{
uri = new URI(absoluteName);
}
catch (URISyntaxException e)
{
LoginException le = new LoginException("Unable to find user DN in referral LDAP");
le.initCause(e);
throw le;
}
String name = localUserDN(absoluteName);
String namingProviderURL = uri.getScheme() + "://" + uri.getAuthority();
InitialLdapContext refCtx = null;
try
{
Properties refEnv = constructLdapContextEnvironment(namingProviderURL, name, credential, null);
refCtx = new InitialLdapContext(refEnv, null);
refCtx.close();
}
catch (NamingException e)
{
LoginException le = new LoginException("Unable to create referral LDAP context");
le.initCause(e);
throw le;
}
}
private String localUserDN(String absoluteDN) {
try
{
URI userURI = new URI(absoluteDN);
return userURI.getPath().substring(1);
}
catch (URISyntaxException e)
{
return null;
}
}
/**
* Checks whether userDN is absolute URI, like the one pointing to an LDAP referral.
* @param userDN
* @return
*/
private Boolean isUserDnAbsolute(String userDN) {
try
{
URI userURI = new URI(userDN);
return userURI.isAbsolute();
}
catch (URISyntaxException e)
{
return false;
}
}
protected void authenticate(String userDN) throws LoginException
{
char[] credential = getCredential();
if (credential.length == 0)
{
if (allowEmptyPassword == false)
{
log.trace("Rejecting empty password.");
return;
}
}
if (isUserDnAbsolute(userDN))
{
// user object resides in referral
referralAuthenticate(userDN, credential);
}
else
{
// non referral user authentication
try
{
LdapContext authContext = constructLdapContext(null, userDN, credential, null);
authContext.close();
}
catch (NamingException ne)
{
if (log.isDebugEnabled())
log.debug("Authentication failed - " + ne.getMessage());
LoginException le = new LoginException("Authentication failed");
le.initCause(ne);
throw le;
}
}
super.loginOk = true;
if (getUseFirstPass() == true)
{ // Add the username and password to the shared state map
sharedState.put("javax.security.auth.login.name", getIdentity().getName());
sharedState.put("javax.security.auth.login.password", credential);
}
}
protected void rolesSearch(LdapContext searchContext, String dn) throws LoginException
{
/*
* The distinguished name passed into this method is expected to be unquoted.
*/
Object[] filterArgs = null;
if (isUserDnAbsolute(dn))
{
filterArgs = new Object[] {getIdentity().getName(), localUserDN(dn)};
}
else
{
filterArgs = new Object[] {getIdentity().getName(), dn};
}
NamingEnumeration results = null;
try
{
if (trace) {
log.trace("rolesCtxDN=" + rolesCtxDN + " roleFilter=" + roleFilter + " filterArgs[0]=" + filterArgs[0]
+ " filterArgs[1]=" + filterArgs[1]);
}
if (roleFilter != null && roleFilter.length() > 0)
{
boolean referralsExist = true;
while (referralsExist)
{
try
{
results = searchContext.search(rolesCtxDN, roleFilter, filterArgs, roleSearchControls);
while (results.hasMore())
{
SearchResult sr = (SearchResult) results.next();
String resultDN = null;
if (sr.isRelative())
{
resultDN = canonicalize(sr.getName());
}
else
{
resultDN = sr.getNameInNamespace();
}
/*
* By this point if the distinguished name needs to be quoted for attribute
* searches it will have been already.
*/
obtainRole(searchContext, resultDN, sr);
}
referralsExist = false;
}
catch (ReferralException e)
{
searchContext = (LdapContext) e.getReferralContext();
}
}
}
else
{
/*
* As there was no search based on the distinguished name it would not have been
* auto-quoted - do that here to be safe.
*/
obtainRole(searchContext, quoted(dn), null);
}
}
catch (NamingException e)
{
LoginException le = new LoginException("Error finding roles");
le.initCause(e);
throw le;
}
finally
{
if (results != null)
{
try
{
results.close();
}
catch (NamingException e)
{
log.warn("Problem closing results", e);
}
}
}
}
private String quoted(final String dn) {
String temp = dn.trim();
if (temp.startsWith("\"") && temp.endsWith("\"")) {
return temp;
}
return "\"" + temp + "\"";
}
protected void obtainRole(LdapContext searchContext, String dn, SearchResult sr) throws NamingException, LoginException
{
if (trace) {
log.trace("rolesSearch resultDN = " + dn);
}
String[] attrNames =
{roleAttributeID};
Attributes result = null;
if (sr == null || sr.isRelative())
{
result = searchContext.getAttributes(dn, attrNames);
}
else
{
result = getAttributesFromReferralEntity(sr);
}
if (result != null && result.size() > 0)
{
Attribute roles = result.get(roleAttributeID);
for (int n = 0; n < roles.size(); n++)
{
String roleName = (String) roles.get(n);
if (roleAttributeIsDN)
{
// Query the roleDN location for the value of roleNameAttributeID
String roleDN = "\"" + roleName + "\"";
loadRoleByRoleNameAttributeID(searchContext, roleDN);
recurseRolesSearch(searchContext, roleName);
}
else
{
// The role attribute value is the role name
addRole(roleName);
}
}
}
}
private Attributes getAttributesFromReferralEntity(SearchResult sr) throws NamingException
{
Attributes result = sr.getAttributes();
boolean chkSuccessful = false;
if (referralUserAttributeIDToCheck != null)
{
Attribute usersToCheck = result.get(referralUserAttributeIDToCheck);
for (int i = 0; usersToCheck != null && i < usersToCheck.size(); i++)
{
String userDNToCheck = (String) usersToCheck.get(i);
if (userDNToCheck.equals(referralUserDNToCheck))
{
chkSuccessful = true;
break;
}
if (userDNToCheck.equals(getIdentity().getName()))
{
chkSuccessful = true;
break;
}
}
}
return (chkSuccessful ? result : null);
}
protected void loadRoleByRoleNameAttributeID(LdapContext searchContext, String roleDN)
{
String[] returnAttribute = {roleNameAttributeID};
if (trace) {
log.trace("Using roleDN: " + roleDN);
}
try
{
Attributes result2 = searchContext.getAttributes(roleDN, returnAttribute);
Attribute roles2 = result2.get(roleNameAttributeID);
if (roles2 != null)
{
for (int m = 0; m < roles2.size(); m++)
{
String roleName = (String) roles2.get(m);
addRole(roleName);
}
}
}
catch (NamingException e)
{
if (trace) {
log.trace("Failed to query roleNameAttrName", e);
}
}
}
protected void recurseRolesSearch(LdapContext searchContext, String roleDN) throws LoginException
{
if (recurseRoles)
{
if (processedRoleDNs.contains(roleDN) == false)
{
processedRoleDNs.add(roleDN);
if (trace) {
log.trace("Recursive search for '" + roleDN + "'");
}
rolesSearch(searchContext, roleDN);
}
else
{
if (trace) {
log.trace("Already visited role '" + roleDN + "' ending recursion.");
}
}
}
}
protected void traceLdapEnv(Properties env)
{
if (trace)
{
Properties tmp = new Properties();
tmp.putAll(env);
String credentials = tmp.getProperty(Context.SECURITY_CREDENTIALS);
String bindCredential = tmp.getProperty(BIND_CREDENTIAL);
if (credentials != null && credentials.length() > 0)
tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
if (bindCredential != null && bindCredential.length() > 0)
tmp.setProperty(BIND_CREDENTIAL, "***");
log.trace("Logging into LDAP server, env=" + tmp.toString());
}
}
protected String canonicalize(String searchResult)
{
String result = searchResult;
int len = searchResult.length();
if (searchResult.endsWith("\""))
{
result = searchResult.substring(0, len - 1) + "," + rolesCtxDN + "\"";
}
else
{
result = searchResult + "," + rolesCtxDN;
}
return result;
}
private void addRole(String roleName)
{
if (roleName != null)
{
try
{
Principal p = super.createIdentity(roleName);
if (trace) {
log.trace("Assign user '" + getIdentity().getName() + "' to role " + roleName);
}
userRoles.addMember(p);
}
catch (Exception e)
{
if (log.isDebugEnabled())
log.debug("Failed to create principal: " + roleName, e);
}
}
}
private class AuthorizeAction implements PrivilegedAction<Object>
{
public Object run()
{
try
{
return innerLogin();
}
catch (LoginException e)
{
return e;
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_1503_1
|
crossvul-java_data_bad_3053_1
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_3053_1
|
crossvul-java_data_good_4347_3
|
/*
* Copyright (c) 2020 Ubique Innovation AG <https://www.ubique.ch>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.jsonwebtoken.Jwts;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dpppt.backend.sdk.data.gaen.FakeKeyService;
import org.dpppt.backend.sdk.data.gaen.GAENDataService;
import org.dpppt.backend.sdk.model.gaen.*;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention;
import org.dpppt.backend.sdk.ws.security.ValidateRequest;
import org.dpppt.backend.sdk.ws.security.ValidateRequest.InvalidDateException;
import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature;
import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature.ProtoSignatureWrapper;
import org.dpppt.backend.sdk.ws.util.ValidationUtils;
import org.dpppt.backend.sdk.ws.util.ValidationUtils.BadBatchReleaseTimeException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.Callable;
@Controller
@RequestMapping("/v1/gaen")
@Tag(name = "GAEN", description = "The GAEN endpoint for the mobile clients")
/**
* The GaenController defines the API endpoints for the mobile clients to access the GAEN functionality of the
* red backend.
* Clients can send new Exposed Keys, or request the existing Exposed Keys.
*/
public class GaenController {
private static final Logger logger = LoggerFactory.getLogger(GaenController.class);
private static final String FAKE_CODE = "112358132134";
private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER =
DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
.withZoneUTC().withLocale(Locale.ENGLISH);
// releaseBucketDuration is used to delay the publishing of Exposed Keys by splitting the database up into batches of keys
// in releaseBucketDuration duration. The current batch is never published, only previous batches are published.
private final Duration releaseBucketDuration;
private final Duration requestTime;
private final ValidateRequest validateRequest;
private final ValidationUtils validationUtils;
private final GAENDataService dataService;
private final FakeKeyService fakeKeyService;
private final Duration exposedListCacheControl;
private final PrivateKey secondDayKey;
private final ProtoSignature gaenSigner;
public GaenController(GAENDataService dataService, FakeKeyService fakeKeyService, ValidateRequest validateRequest,
ProtoSignature gaenSigner, ValidationUtils validationUtils, Duration releaseBucketDuration, Duration requestTime,
Duration exposedListCacheControl, PrivateKey secondDayKey) {
this.dataService = dataService;
this.fakeKeyService = fakeKeyService;
this.releaseBucketDuration = releaseBucketDuration;
this.validateRequest = validateRequest;
this.requestTime = requestTime;
this.validationUtils = validationUtils;
this.exposedListCacheControl = exposedListCacheControl;
this.secondDayKey = secondDayKey;
this.gaenSigner = gaenSigner;
}
@PostMapping(value = "/exposed")
@Loggable
@ResponseRetention(time = "application.response.retention.time.exposed")
@Transactional
@Operation(description = "Send exposed keys to server - includes a fix for the fact that GAEN doesn't give access to the current day's exposed key")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed keys have been stored in the database"),
@ApiResponse(responseCode = "400", description =
"- Invalid base64 encoding in GaenRequest" +
"- negative rolling period" +
"- fake claim with non-fake keys"),
@ApiResponse(responseCode = "403", description = "Authentication failed") })
public @ResponseBody Callable<ResponseEntity<String>> addExposed(
@Valid @RequestBody @Parameter(description = "The GaenRequest contains the SecretKey from the guessed infection date, the infection date itself, and some authentication data to verify the test result") GaenRequest gaenRequest,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server") Object principal) {
var now = Instant.now().toEpochMilli();
if (!this.validateRequest.isValid(principal)) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
List<GaenKey> nonFakeKeys = new ArrayList<>();
for (var key : gaenRequest.getGaenKeys()) {
if (!validationUtils.isValidBase64Key(key.getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (this.validateRequest.isFakeRequest(principal, key)
|| hasNegativeRollingPeriod(key)
|| hasInvalidKeyDate(principal, key)) {
continue;
}
if (key.getRollingPeriod().equals(0)) {
//currently only android seems to send 0 which can never be valid, since a non used key should not be submitted
//default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since
//this should not happen
key.setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod);
if (userAgent.toLowerCase().contains("ios")) {
logger.error("Received a rolling period of 0 for an iOS User-Agent");
}
}
nonFakeKeys.add(key);
}
if (principal instanceof Jwt && ((Jwt) principal).containsClaim("fake")
&& ((Jwt) principal).getClaimAsString("fake").equals("1")) {
Jwt token = (Jwt) principal;
if (FAKE_CODE.equals(token.getSubject())) {
logger.info("Claim is fake - subject: {}", token.getSubject());
} else if (!nonFakeKeys.isEmpty()) {
return () -> ResponseEntity.badRequest().body("Claim is fake but list contains non fake keys");
}
}
if (!nonFakeKeys.isEmpty()) {
dataService.upsertExposees(nonFakeKeys);
}
var delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes);
var delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()),
ZoneOffset.UTC);
var nowDay = LocalDate.now(ZoneOffset.UTC);
if (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) {
return () -> ResponseEntity.badRequest().body("delayedKeyDate date must be between yesterday and tomorrow");
}
var responseBuilder = ResponseEntity.ok();
if (principal instanceof Jwt) {
var originalJWT = (Jwt) principal;
var jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now()))
.setIssuer("dpppt-sdk-backend").setSubject(originalJWT.getSubject())
.setExpiration(Date
.from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48))))
.claim("scope", "currentDayExposed").claim("delayedKeyDate", gaenRequest.getDelayedKeyDate());
if (originalJWT.containsClaim("fake")) {
jwtBuilder.claim("fake", originalJWT.getClaim("fake"));
}
String jwt = jwtBuilder.signWith(secondDayKey).compact();
responseBuilder.header("Authorization", "Bearer " + jwt);
responseBuilder.header("X-Exposed-Token", "Bearer " + jwt);
}
Callable<ResponseEntity<String>> cb = () -> {
normalizeRequestTime(now);
return responseBuilder.body("OK");
};
return cb;
}
@PostMapping(value = "/exposednextday")
@Loggable
@ResponseRetention(time = "application.response.retention.time.exposednextday")
@Transactional
@Operation(description = "Allows the client to send the last exposed key of the infection to the backend server. The JWT must come from a previous call to /exposed")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed key has been stored in the backend"),
@ApiResponse(responseCode = "400", description =
"- Ivnalid base64 encoded Temporary Exposure Key" +
"- TEK-date does not match delayedKeyDAte claim in Jwt" +
"- TEK has negative rolling period"),
@ApiResponse(responseCode = "403", description = "No delayedKeyDate claim in authentication") })
public @ResponseBody Callable<ResponseEntity<String>> addExposedSecond(
@Valid @RequestBody @Parameter(description = "The last exposed key of the user") GaenSecondDay gaenSecondDay,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate") Object principal) {
var now = Instant.now().toEpochMilli();
if (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (principal instanceof Jwt && !((Jwt) principal).containsClaim("delayedKeyDate")) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body("claim does not contain delayedKeyDate");
}
if (principal instanceof Jwt) {
var jwt = (Jwt) principal;
var claimKeyDate = Integer.parseInt(jwt.getClaimAsString("delayedKeyDate"));
if (!gaenSecondDay.getDelayedKey().getRollingStartNumber().equals(claimKeyDate)) {
return () -> ResponseEntity.badRequest().body("keyDate does not match claim keyDate");
}
}
if (!this.validateRequest.isFakeRequest(principal, gaenSecondDay.getDelayedKey())) {
if (gaenSecondDay.getDelayedKey().getRollingPeriod().equals(0)) {
// currently only android seems to send 0 which can never be valid, since a non used key should not be submitted
// default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since
// this should not happen
gaenSecondDay.getDelayedKey().setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod);
if(userAgent.toLowerCase().contains("ios")) {
logger.error("Received a rolling period of 0 for an iOS User-Agent");
}
} else if(gaenSecondDay.getDelayedKey().getRollingPeriod() < 0) {
return () -> ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rolling Period MUST NOT be negative.");
}
List<GaenKey> keys = new ArrayList<>();
keys.add(gaenSecondDay.getDelayedKey());
dataService.upsertExposees(keys);
}
return () -> {
normalizeRequestTime(now);
return ResponseEntity.ok().body("OK");
};
}
@GetMapping(value = "/exposed/{keyDate}", produces = "application/zip")
@Loggable
@Operation(description = "Request the exposed key from a given date")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"),
@ApiResponse(responseCode = "400", description =
"- invalid starting key date, doesn't point to midnight UTC" +
"- _publishedAfter_ is not at the beginning of a batch release time, currently 2h")})
public @ResponseBody ResponseEntity<byte[]> getExposedKeys(
@PathVariable @Parameter(description = "Requested date for Exposed Keys retrieval, in milliseconds since Unix epoch (1970-01-01). It must indicate the beginning of a TEKRollingPeriod, currently midnight UTC.", example = "1593043200000") long keyDate,
@RequestParam(required = false) @Parameter(description = "Restrict returned Exposed Keys to dates after this parameter. Given in milliseconds since Unix epoch (1970-01-01).", example = "1593043200000") Long publishedafter)
throws BadBatchReleaseTimeException, IOException, InvalidKeyException, SignatureException,
NoSuchAlgorithmException {
if (!validationUtils.isValidKeyDate(keyDate)) {
return ResponseEntity.notFound().build();
}
if (publishedafter != null && !validationUtils.isValidBatchReleaseTime(publishedafter)) {
return ResponseEntity.notFound().build();
}
long now = System.currentTimeMillis();
// calculate exposed until bucket
long publishedUntil = now - (now % releaseBucketDuration.toMillis());
DateTime dateTime = new DateTime(publishedUntil + releaseBucketDuration.toMillis() - 1, DateTimeZone.UTC);
var exposedKeys = dataService.getSortedExposedForKeyDate(keyDate, publishedafter, publishedUntil);
exposedKeys = fakeKeyService.fillUpKeys(exposedKeys, publishedafter, keyDate);
if (exposedKeys.isEmpty()) {
return ResponseEntity.noContent()//.cacheControl(CacheControl.maxAge(exposedListCacheControl))
.header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil))
.header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime))
.build();
}
ProtoSignatureWrapper payload = gaenSigner.getPayload(exposedKeys);
return ResponseEntity.ok()//.cacheControl(CacheControl.maxAge(exposedListCacheControl))
.header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil))
.header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime))
.body(payload.getZip());
}
@GetMapping(value = "/buckets/{dayDateStr}")
@Loggable
@Operation(description = "Request the available release batch times for a given day")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"),
@ApiResponse(responseCode = "400", description = "invalid starting key date, points outside of the retention range")})
public @ResponseBody ResponseEntity<DayBuckets> getBuckets(
@PathVariable @Parameter(description = "Starting date for exposed key retrieval, as ISO-8601 format", example = "2020-06-27") String dayDateStr) {
var atStartOfDay = LocalDate.parse(dayDateStr).atStartOfDay().toInstant(ZoneOffset.UTC)
.atOffset(ZoneOffset.UTC);
var end = atStartOfDay.plusDays(1);
var now = Instant.now().atOffset(ZoneOffset.UTC);
if (!validationUtils.isDateInRange(atStartOfDay)) {
return ResponseEntity.notFound().build();
}
var relativeUrls = new ArrayList<String>();
var dayBuckets = new DayBuckets();
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
dayBuckets.setDay(dayDateStr).setRelativeUrls(relativeUrls).setDayTimestamp(atStartOfDay.toInstant().toEpochMilli());
while (atStartOfDay.toInstant().toEpochMilli() < Math.min(now.toInstant().toEpochMilli(),
end.toInstant().toEpochMilli())) {
relativeUrls.add(controllerMapping + "/exposed" + "/" + atStartOfDay.toInstant().toEpochMilli());
atStartOfDay = atStartOfDay.plus(this.releaseBucketDuration);
}
return ResponseEntity.ok(dayBuckets);
}
private void normalizeRequestTime(long now) {
long after = Instant.now().toEpochMilli();
long duration = after - now;
try {
Thread.sleep(Math.max(requestTime.minusMillis(duration).toMillis(), 0));
} catch (Exception ex) {
logger.error("Couldn't equalize request time: {}", ex.toString());
}
}
private boolean hasNegativeRollingPeriod(GaenKey key) {
Integer rollingPeriod = key.getRollingPeriod();
if (key.getRollingPeriod() < 0) {
logger.error("Detected key with negative rolling period {}", rollingPeriod);
return true;
} else {
return false;
}
}
private boolean hasInvalidKeyDate(Object principal, GaenKey key) {
try {
this.validateRequest.getKeyDate(principal, key);
}
catch (InvalidDateException invalidDate) {
logger.error(invalidDate.getLocalizedMessage());
return true;
}
return false;
}
@ExceptionHandler({IllegalArgumentException.class, InvalidDateException.class, JsonProcessingException.class,
MethodArgumentNotValidException.class, BadBatchReleaseTimeException.class, DateTimeParseException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Object> invalidArguments(Exception ex) {
logger.error("Exception ({}): {}", ex.getClass().getSimpleName(), ex.getMessage(), ex);
return ResponseEntity.badRequest().build();
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_4347_3
|
crossvul-java_data_bad_3055_1
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.
*/
package hudson.search;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import hudson.model.FreeStyleProject;
import hudson.model.ListView;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.MockFolder;
import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
/**
* @author Kohsuke Kawaguchi
*/
public class SearchTest {
@Rule public JenkinsRule j = new JenkinsRule();
/**
* No exact match should result in a failure status code.
*/
@Test
public void testFailure() throws Exception {
try {
j.search("no-such-thing");
fail("404 expected");
} catch (FailingHttpStatusCodeException e) {
assertEquals(404,e.getResponse().getStatusCode());
}
}
/**
* Makes sure the script doesn't execute.
*/
@Issue("JENKINS-3415")
@Test
public void testXSS() throws Exception {
try {
WebClient wc = j.createWebClient();
wc.setAlertHandler(new AlertHandler() {
public void handleAlert(Page page, String message) {
throw new AssertionError();
}
});
wc.search("<script>alert('script');</script>");
fail("404 expected");
} catch (FailingHttpStatusCodeException e) {
assertEquals(404,e.getResponse().getStatusCode());
}
}
@Test
public void testSearchByProjectName() throws Exception {
final String projectName = "testSearchByProjectName";
j.createFreeStyleProject(projectName);
Page result = j.search(projectName);
assertNotNull(result);
j.assertGoodStatus(result);
// make sure we've fetched the testSearchByDisplayName project page
String contents = result.getWebResponse().getContentAsString();
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", projectName)));
}
@Issue("JENKINS-24433")
@Test
public void testSearchByProjectNameBehindAFolder() throws Exception {
FreeStyleProject myFreeStyleProject = j.createFreeStyleProject("testSearchByProjectName");
MockFolder myMockFolder = j.createFolder("my-folder-1");
Page result = j.createWebClient().goTo(myMockFolder.getUrl() + "search?q="+ myFreeStyleProject.getName());
assertNotNull(result);
j.assertGoodStatus(result);
URL resultUrl = result.getUrl();
assertTrue(resultUrl.toString().equals(j.getInstance().getRootUrl() + myFreeStyleProject.getUrl()));
}
@Issue("JENKINS-24433")
@Test
public void testSearchByProjectNameInAFolder() throws Exception {
MockFolder myMockFolder = j.createFolder("my-folder-1");
FreeStyleProject myFreeStyleProject = myMockFolder.createProject(FreeStyleProject.class, "my-job-1");
Page result = j.createWebClient().goTo(myMockFolder.getUrl() + "search?q=" + myFreeStyleProject.getFullName());
assertNotNull(result);
j.assertGoodStatus(result);
URL resultUrl = result.getUrl();
assertTrue(resultUrl.toString().equals(j.getInstance().getRootUrl() + myFreeStyleProject.getUrl()));
}
@Test
public void testSearchByDisplayName() throws Exception {
final String displayName = "displayName9999999";
FreeStyleProject project = j.createFreeStyleProject("testSearchByDisplayName");
project.setDisplayName(displayName);
Page result = j.search(displayName);
assertNotNull(result);
j.assertGoodStatus(result);
// make sure we've fetched the testSearchByDisplayName project page
String contents = result.getWebResponse().getContentAsString();
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", displayName)));
}
@Test
public void testSearch2ProjectsWithSameDisplayName() throws Exception {
// create 2 freestyle projects with the same display name
final String projectName1 = "projectName1";
final String projectName2 = "projectName2";
final String projectName3 = "projectName3";
final String displayName = "displayNameFoo";
final String otherDisplayName = "otherDisplayName";
FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
project1.setDisplayName(displayName);
FreeStyleProject project2 = j.createFreeStyleProject(projectName2);
project2.setDisplayName(displayName);
FreeStyleProject project3 = j.createFreeStyleProject(projectName3);
project3.setDisplayName(otherDisplayName);
// make sure that on search we get back one of the projects, it doesn't
// matter which one as long as the one that is returned has displayName
// as the display name
Page result = j.search(displayName);
assertNotNull(result);
j.assertGoodStatus(result);
// make sure we've fetched the testSearchByDisplayName project page
String contents = result.getWebResponse().getContentAsString();
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", displayName)));
assertFalse(contents.contains(otherDisplayName));
}
@Test
public void testProjectNamePrecedesDisplayName() throws Exception {
final String project1Name = "foo";
final String project1DisplayName = "project1DisplayName";
final String project2Name = "project2Name";
final String project2DisplayName = project1Name;
final String project3Name = "project3Name";
final String project3DisplayName = "project3DisplayName";
// create 1 freestyle project with the name foo
FreeStyleProject project1 = j.createFreeStyleProject(project1Name);
project1.setDisplayName(project1DisplayName);
// create another with the display name foo
FreeStyleProject project2 = j.createFreeStyleProject(project2Name);
project2.setDisplayName(project2DisplayName);
// create a third project and make sure it's not picked up by search
FreeStyleProject project3 = j.createFreeStyleProject(project3Name);
project3.setDisplayName(project3DisplayName);
// search for foo
Page result = j.search(project1Name);
assertNotNull(result);
j.assertGoodStatus(result);
// make sure we get the project with the name foo
String contents = result.getWebResponse().getContentAsString();
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", project1DisplayName)));
// make sure projects 2 and 3 were not picked up
assertFalse(contents.contains(project2Name));
assertFalse(contents.contains(project3Name));
assertFalse(contents.contains(project3DisplayName));
}
@Test
public void testGetSuggestionsHasBothNamesAndDisplayNames() throws Exception {
final String projectName = "project name";
final String displayName = "display name";
FreeStyleProject project1 = j.createFreeStyleProject(projectName);
project1.setDisplayName(displayName);
WebClient wc = j.createWebClient();
Page result = wc.goTo("search/suggest?query=name", "application/json");
assertNotNull(result);
j.assertGoodStatus(result);
String content = result.getWebResponse().getContentAsString();
System.out.println(content);
JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
assertNotNull(jsonContent);
JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
assertNotNull(jsonArray);
assertEquals(2, jsonArray.size());
boolean foundProjectName = false;
boolean foundDispayName = false;
for(Object suggestion : jsonArray) {
JSONObject jsonSuggestion = (JSONObject)suggestion;
String name = (String)jsonSuggestion.get("name");
if(projectName.equals(name)) {
foundProjectName = true;
}
else if(displayName.equals(name)) {
foundDispayName = true;
}
}
assertTrue(foundProjectName);
assertTrue(foundDispayName);
}
@Issue("JENKINS-24433")
@Test
public void testProjectNameBehindAFolderDisplayName() throws Exception {
final String projectName1 = "job-1";
final String displayName1 = "job-1 display";
final String projectName2 = "job-2";
final String displayName2 = "job-2 display";
FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
project1.setDisplayName(displayName1);
MockFolder myMockFolder = j.createFolder("my-folder-1");
FreeStyleProject project2 = myMockFolder.createProject(FreeStyleProject.class, projectName2);
project2.setDisplayName(displayName2);
WebClient wc = j.createWebClient();
Page result = wc.goTo(myMockFolder.getUrl() + "search/suggest?query=" + projectName1, "application/json");
assertNotNull(result);
j.assertGoodStatus(result);
String content = result.getWebResponse().getContentAsString();
JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
assertNotNull(jsonContent);
JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
assertNotNull(jsonArray);
assertEquals(2, jsonArray.size());
boolean foundDisplayName = false;
for(Object suggestion : jsonArray) {
JSONObject jsonSuggestion = (JSONObject)suggestion;
String name = (String)jsonSuggestion.get("name");
if(projectName1.equals(name)) {
foundDisplayName = true;
}
}
assertTrue(foundDisplayName);
}
@Issue("JENKINS-24433")
@Test
public void testProjectNameInAFolderDisplayName() throws Exception {
final String projectName1 = "job-1";
final String displayName1 = "job-1 display";
final String projectName2 = "job-2";
final String displayName2 = "my-folder-1 job-2";
FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
project1.setDisplayName(displayName1);
MockFolder myMockFolder = j.createFolder("my-folder-1");
FreeStyleProject project2 = myMockFolder.createProject(FreeStyleProject.class, projectName2);
project2.setDisplayName(displayName2);
WebClient wc = j.createWebClient();
Page result = wc.goTo(myMockFolder.getUrl() + "search/suggest?query=" + projectName2, "application/json");
assertNotNull(result);
j.assertGoodStatus(result);
String content = result.getWebResponse().getContentAsString();
JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
assertNotNull(jsonContent);
JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
assertNotNull(jsonArray);
assertEquals(1, jsonArray.size());
boolean foundDisplayName = false;
for(Object suggestion : jsonArray) {
JSONObject jsonSuggestion = (JSONObject)suggestion;
String name = (String)jsonSuggestion.get("name");
if(displayName2.equals(name)) {
foundDisplayName = true;
}
}
assertTrue(foundDisplayName);
}
/**
* Disable/enable status shouldn't affect the search
*/
@Issue("JENKINS-13148")
@Test
public void testDisabledJobShouldBeSearchable() throws Exception {
FreeStyleProject p = j.createFreeStyleProject("foo-bar");
assertTrue(suggest(j.jenkins.getSearchIndex(), "foo").contains(p));
p.disable();
assertTrue(suggest(j.jenkins.getSearchIndex(), "foo").contains(p));
}
/**
* All top-level jobs should be searchable, not just jobs in the current view.
*/
@Issue("JENKINS-13148")
@Test
public void testCompletionOutsideView() throws Exception {
FreeStyleProject p = j.createFreeStyleProject("foo-bar");
ListView v = new ListView("empty1",j.jenkins);
ListView w = new ListView("empty2",j.jenkins);
j.jenkins.addView(v);
j.jenkins.addView(w);
j.jenkins.setPrimaryView(w);
// new view should be empty
assertFalse(v.contains(p));
assertFalse(w.contains(p));
assertFalse(j.jenkins.getPrimaryView().contains(p));
assertTrue(suggest(j.jenkins.getSearchIndex(),"foo").contains(p));
}
@Test
public void testSearchWithinFolders() throws Exception {
MockFolder folder1 = j.createFolder("folder1");
FreeStyleProject p1 = folder1.createProject(FreeStyleProject.class, "myjob");
MockFolder folder2 = j.createFolder("folder2");
FreeStyleProject p2 = folder2.createProject(FreeStyleProject.class, "myjob");
List<SearchItem> suggest = suggest(j.jenkins.getSearchIndex(), "myjob");
assertTrue(suggest.contains(p1));
assertTrue(suggest.contains(p2));
}
private List<SearchItem> suggest(SearchIndex index, String term) {
List<SearchItem> result = new ArrayList<SearchItem>();
index.suggest(term, result);
return result;
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_3055_1
|
crossvul-java_data_good_4188_0
|
package org.junit.rules;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Rule;
/**
* The TemporaryFolder Rule allows creation of files and folders that should
* be deleted when the test method finishes (whether it passes or
* fails).
* By default no exception will be thrown in case the deletion fails.
*
* <p>Example of usage:
* <pre>
* public static class HasTempFolder {
* @Rule
* public TemporaryFolder folder= new TemporaryFolder();
*
* @Test
* public void testUsingTempFolder() throws IOException {
* File createdFile= folder.newFile("myfile.txt");
* File createdFolder= folder.newFolder("subfolder");
* // ...
* }
* }
* </pre>
*
* <p>TemporaryFolder rule supports assured deletion mode, which
* will fail the test in case deletion fails with {@link AssertionError}.
*
* <p>Creating TemporaryFolder with assured deletion:
* <pre>
* @Rule
* public TemporaryFolder folder= TemporaryFolder.builder().assureDeletion().build();
* </pre>
*
* @since 4.7
*/
public class TemporaryFolder extends ExternalResource {
private final File parentFolder;
private final boolean assureDeletion;
private File folder;
private static final int TEMP_DIR_ATTEMPTS = 10000;
private static final String TMP_PREFIX = "junit";
/**
* Create a temporary folder which uses system default temporary-file
* directory to create temporary resources.
*/
public TemporaryFolder() {
this((File) null);
}
/**
* Create a temporary folder which uses the specified directory to create
* temporary resources.
*
* @param parentFolder folder where temporary resources will be created.
* If {@code null} then system default temporary-file directory is used.
*/
public TemporaryFolder(File parentFolder) {
this.parentFolder = parentFolder;
this.assureDeletion = false;
}
/**
* Create a {@link TemporaryFolder} initialized with
* values from a builder.
*/
protected TemporaryFolder(Builder builder) {
this.parentFolder = builder.parentFolder;
this.assureDeletion = builder.assureDeletion;
}
/**
* Returns a new builder for building an instance of {@link TemporaryFolder}.
*
* @since 4.13
*/
public static Builder builder() {
return new Builder();
}
/**
* Builds an instance of {@link TemporaryFolder}.
*
* @since 4.13
*/
public static class Builder {
private File parentFolder;
private boolean assureDeletion;
protected Builder() {}
/**
* Specifies which folder to use for creating temporary resources.
* If {@code null} then system default temporary-file directory is
* used.
*
* @return this
*/
public Builder parentFolder(File parentFolder) {
this.parentFolder = parentFolder;
return this;
}
/**
* Setting this flag assures that no resources are left undeleted. Failure
* to fulfill the assurance results in failure of tests with an
* {@link AssertionError}.
*
* @return this
*/
public Builder assureDeletion() {
this.assureDeletion = true;
return this;
}
/**
* Builds a {@link TemporaryFolder} instance using the values in this builder.
*/
public TemporaryFolder build() {
return new TemporaryFolder(this);
}
}
@Override
protected void before() throws Throwable {
create();
}
@Override
protected void after() {
delete();
}
// testing purposes only
/**
* for testing purposes only. Do not use.
*/
public void create() throws IOException {
folder = createTemporaryFolderIn(parentFolder);
}
/**
* Returns a new fresh file with the given name under the temporary folder.
*/
public File newFile(String fileName) throws IOException {
File file = new File(getRoot(), fileName);
if (!file.createNewFile()) {
throw new IOException(
"a file with the name \'" + fileName + "\' already exists in the test folder");
}
return file;
}
/**
* Returns a new fresh file with a random name under the temporary folder.
*/
public File newFile() throws IOException {
return File.createTempFile(TMP_PREFIX, null, getRoot());
}
/**
* Returns a new fresh folder with the given path under the temporary
* folder.
*/
public File newFolder(String path) throws IOException {
return newFolder(new String[]{path});
}
/**
* Returns a new fresh folder with the given paths under the temporary
* folder. For example, if you pass in the strings {@code "parent"} and {@code "child"}
* then a directory named {@code "parent"} will be created under the temporary folder
* and a directory named {@code "child"} will be created under the newly-created
* {@code "parent"} directory.
*/
public File newFolder(String... paths) throws IOException {
if (paths.length == 0) {
throw new IllegalArgumentException("must pass at least one path");
}
/*
* Before checking if the paths are absolute paths, check if create() was ever called,
* and if it wasn't, throw IllegalStateException.
*/
File root = getRoot();
for (String path : paths) {
if (new File(path).isAbsolute()) {
throw new IOException("folder path \'" + path + "\' is not a relative path");
}
}
File relativePath = null;
File file = root;
boolean lastMkdirsCallSuccessful = true;
for (String path : paths) {
relativePath = new File(relativePath, path);
file = new File(root, relativePath.getPath());
lastMkdirsCallSuccessful = file.mkdirs();
if (!lastMkdirsCallSuccessful && !file.isDirectory()) {
if (file.exists()) {
throw new IOException(
"a file with the path \'" + relativePath.getPath() + "\' exists");
} else {
throw new IOException(
"could not create a folder with the path \'" + relativePath.getPath() + "\'");
}
}
}
if (!lastMkdirsCallSuccessful) {
throw new IOException(
"a folder with the path \'" + relativePath.getPath() + "\' already exists");
}
return file;
}
/**
* Returns a new fresh folder with a random name under the temporary folder.
*/
public File newFolder() throws IOException {
return createTemporaryFolderIn(getRoot());
}
private static File createTemporaryFolderIn(File parentFolder) throws IOException {
try {
return createTemporaryFolderWithNioApi(parentFolder);
} catch (ClassNotFoundException ignore) {
// Fallback for Java 5 and 6
return createTemporaryFolderWithFileApi(parentFolder);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
throw (IOException) cause;
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
IOException exception = new IOException("Failed to create temporary folder in " + parentFolder);
exception.initCause(cause);
throw exception;
} catch (Exception e) {
throw new RuntimeException("Failed to create temporary folder in " + parentFolder, e);
}
}
private static File createTemporaryFolderWithNioApi(File parentFolder) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> filesClass = Class.forName("java.nio.file.Files");
Object fileAttributeArray = Array.newInstance(Class.forName("java.nio.file.attribute.FileAttribute"), 0);
Class<?> pathClass = Class.forName("java.nio.file.Path");
Object tempDir;
if (parentFolder != null) {
Method createTempDirectoryMethod = filesClass.getDeclaredMethod("createTempDirectory", pathClass, String.class, fileAttributeArray.getClass());
Object parentPath = File.class.getDeclaredMethod("toPath").invoke(parentFolder);
tempDir = createTempDirectoryMethod.invoke(null, parentPath, TMP_PREFIX, fileAttributeArray);
} else {
Method createTempDirectoryMethod = filesClass.getDeclaredMethod("createTempDirectory", String.class, fileAttributeArray.getClass());
tempDir = createTempDirectoryMethod.invoke(null, TMP_PREFIX, fileAttributeArray);
}
return (File) pathClass.getDeclaredMethod("toFile").invoke(tempDir);
}
private static File createTemporaryFolderWithFileApi(File parentFolder) throws IOException {
File createdFolder = null;
for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) {
// Use createTempFile to get a suitable folder name.
String suffix = ".tmp";
File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder);
String tmpName = tmpFile.toString();
// Discard .tmp suffix of tmpName.
String folderName = tmpName.substring(0, tmpName.length() - suffix.length());
createdFolder = new File(folderName);
if (createdFolder.mkdir()) {
tmpFile.delete();
return createdFolder;
}
tmpFile.delete();
}
throw new IOException("Unable to create temporary directory in: "
+ parentFolder.toString() + ". Tried " + TEMP_DIR_ATTEMPTS + " times. "
+ "Last attempted to create: " + createdFolder.toString());
}
/**
* @return the location of this temporary folder.
*/
public File getRoot() {
if (folder == null) {
throw new IllegalStateException(
"the temporary folder has not yet been created");
}
return folder;
}
/**
* Delete all files and folders under the temporary folder. Usually not
* called directly, since it is automatically applied by the {@link Rule}.
*
* @throws AssertionError if unable to clean up resources
* and deletion of resources is assured.
*/
public void delete() {
if (!tryDelete()) {
if (assureDeletion) {
fail("Unable to clean up temporary folder " + folder);
}
}
}
/**
* Tries to delete all files and folders under the temporary folder and
* returns whether deletion was successful or not.
*
* @return {@code true} if all resources are deleted successfully,
* {@code false} otherwise.
*/
private boolean tryDelete() {
if (folder == null) {
return true;
}
return recursiveDelete(folder);
}
private boolean recursiveDelete(File file) {
// Try deleting file before assuming file is a directory
// to prevent following symbolic links.
if (file.delete()) {
return true;
}
File[] files = file.listFiles();
if (files != null) {
for (File each : files) {
if (!recursiveDelete(each)) {
return false;
}
}
}
return file.delete();
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_4188_0
|
crossvul-java_data_bad_4348_3
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_4348_3
|
crossvul-java_data_good_4348_4
|
/*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.config;
import java.util.Arrays;
import org.apache.commons.lang3.math.NumberUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention;
import org.dpppt.backend.sdk.ws.radarcovid.exception.RadarCovidServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* Aspect in charge of controlling the minimum response time of a service.
*/
@Configuration
@ConditionalOnProperty(name = "application.response.retention.enabled", havingValue = "true", matchIfMissing = true)
public class ResponseRetentionAspectConfiguration {
private static final Logger log = LoggerFactory.getLogger("org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention");
@Autowired
private Environment environment;
@Aspect
@Component
public class ControllerTimeResponseControlAspect {
@Pointcut("@annotation(responseRetention)")
public void annotationPointCutDefinition(ResponseRetention responseRetention){
}
@Around("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention * *..controller..*(..)) && annotationPointCutDefinition(responseRetention)")
public Object logAround(ProceedingJoinPoint joinPoint, ResponseRetention responseRetention) throws Throwable {
log.debug("************************* INIT TIME RESPONSE CONTROL *********************************");
long start = System.currentTimeMillis();
try {
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - start;
long responseRetentionTimeMillis = getTimeMillis(responseRetention.time());
log.debug("Controller : Controller {}.{} () execution time : {} ms", className, methodName, elapsedTime);
if (elapsedTime < responseRetentionTimeMillis) {
Thread.sleep(responseRetentionTimeMillis - elapsedTime);
}
elapsedTime = System.currentTimeMillis() - start;
log.debug("Controller : Controller {}.{} () NEW execution time : {} ms", className, methodName, elapsedTime);
log.debug("************************* END TIME RESPONSE CONTROL **********************************");
return result;
} catch (IllegalArgumentException e) {
log.error("Controller : Illegal argument {} in {} ()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getName());
log.debug("************************* END TIME RESPONSE CONTROL **********************************");
throw e;
}
}
private long getTimeMillis(String timeMillisString) {
String stringValue = environment.getProperty(timeMillisString);
if (NumberUtils.isCreatable(stringValue)) {
return Long.parseLong(stringValue);
} else {
throw new RadarCovidServerException(HttpStatus.INTERNAL_SERVER_ERROR,
"Invalid timeMillisString value \"" + timeMillisString + "\" - not found or cannot parse into long");
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_4348_4
|
crossvul-java_data_bad_3048_1
|
/*
* The MIT License
*
* Copyright (c) 2013 Red Hat, Inc.
*
* 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.
*/
package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import hudson.security.ACL;
import hudson.security.AccessDeniedException2;
import hudson.security.GlobalMatrixAuthorizationStrategy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* @author ogondza
*/
public class ComputerConfigDotXmlTest {
@Rule public final JenkinsRule rule = new JenkinsRule();
@Mock private StaplerRequest req;
@Mock private StaplerResponse rsp;
private Computer computer;
private SecurityContext oldSecurityContext;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
computer = spy(rule.createSlave().toComputer());
rule.jenkins.setSecurityRealm(rule.createDummySecurityRealm());
oldSecurityContext = ACL.impersonate(User.get("user").impersonate());
}
@After
public void tearDown() {
SecurityContextHolder.setContext(oldSecurityContext);
}
@Test(expected = AccessDeniedException2.class)
public void configXmlGetShouldFailForUnauthorized() throws Exception {
when(req.getMethod()).thenReturn("GET");
rule.jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy());
computer.doConfigDotXml(req, rsp);
}
@Test(expected = AccessDeniedException2.class)
public void configXmlPostShouldFailForUnauthorized() throws Exception {
when(req.getMethod()).thenReturn("POST");
rule.jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy());
computer.doConfigDotXml(req, rsp);
}
@Test
public void configXmlGetShouldYieldNodeConfiguration() throws Exception {
when(req.getMethod()).thenReturn("GET");
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
rule.jenkins.setAuthorizationStrategy(auth);
Computer.EXTENDED_READ.setEnabled(true);
auth.add(Computer.EXTENDED_READ, "user");
final OutputStream outputStream = captureOutput();
computer.doConfigDotXml(req, rsp);
final String out = outputStream.toString();
assertThat(out, startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
assertThat(out, containsString("<name>slave0</name>"));
assertThat(out, containsString("<description>dummy</description>"));
}
@Test
public void configXmlPostShouldUpdateNodeConfiguration() throws Exception {
when(req.getMethod()).thenReturn("POST");
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
rule.jenkins.setAuthorizationStrategy(auth);
auth.add(Computer.CONFIGURE, "user");
when(req.getInputStream()).thenReturn(xmlNode("node.xml"));
computer.doConfigDotXml(req, rsp);
final Node updatedSlave = rule.jenkins.getNode("SlaveFromXML");
assertThat(updatedSlave.getNodeName(), equalTo("SlaveFromXML"));
assertThat(updatedSlave.getNumExecutors(), equalTo(42));
}
private OutputStream captureOutput() throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
when(rsp.getOutputStream()).thenReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
baos.write(b);
}
});
return baos;
}
private ServletInputStream xmlNode(final String name) {
class Stream extends ServletInputStream {
private final InputStream inner;
public Stream(final InputStream inner) {
this.inner = inner;
}
@Override
public int read() throws IOException {
return inner.read();
}
}
return new Stream(Computer.class.getResourceAsStream(name));
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_3048_1
|
crossvul-java_data_good_3051_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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.
*/
package hudson.slaves;
import hudson.Functions;
import hudson.model.Computer;
import hudson.model.User;
import org.jvnet.localizer.Localizable;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Exported;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import java.io.ObjectStreamException;
import java.util.Collections;
import java.util.Date;
/**
* Represents a cause that puts a {@linkplain Computer#isOffline() computer offline}.
*
* <h2>Views</h2>
* <p>
* {@link OfflineCause} must have <tt>cause.jelly</tt> that renders a cause
* into HTML. This is used to tell users why the node is put offline.
* This view should render a block element like DIV.
*
* @author Kohsuke Kawaguchi
* @since 1.320
*/
@ExportedBean
public abstract class OfflineCause {
protected final long timestamp = System.currentTimeMillis();
/**
* Timestamp in which the event happened.
*
* @since 1.612
*/
@Exported
public long getTimestamp() {
return timestamp;
}
/**
* Same as {@link #getTimestamp()} but in a different type.
*
* @since 1.612
*/
public final @Nonnull Date getTime() {
return new Date(timestamp);
}
/**
* {@link OfflineCause} that renders a static text,
* but without any further UI.
*/
public static class SimpleOfflineCause extends OfflineCause {
public final Localizable description;
/**
* @since 1.571
*/
protected SimpleOfflineCause(Localizable description) {
this.description = description;
}
@Exported(name="description") @Override
public String toString() {
return description.toString();
}
}
public static OfflineCause create(Localizable d) {
if (d==null) return null;
return new SimpleOfflineCause(d);
}
/**
* Caused by unexpected channel termination.
*/
public static class ChannelTermination extends OfflineCause {
@Exported
public final Exception cause;
public ChannelTermination(Exception cause) {
this.cause = cause;
}
public String getShortDescription() {
return cause.toString();
}
@Override public String toString() {
return Messages.OfflineCause_connection_was_broken_(Functions.printThrowable(cause));
}
}
/**
* Caused by failure to launch.
*/
public static class LaunchFailed extends OfflineCause {
@Override
public String toString() {
return Messages.OfflineCause_LaunchFailed();
}
}
/**
* Taken offline by user.
*
* @since 1.551
*/
public static class UserCause extends SimpleOfflineCause {
@Deprecated
private transient User user;
// null when unknown
private /*final*/ @CheckForNull String userId;
public UserCause(@CheckForNull User user, @CheckForNull String message) {
this(
user != null ? user.getId() : null,
message != null ? " : " + message : ""
);
}
private UserCause(String userId, String message) {
super(hudson.slaves.Messages._SlaveComputer_DisconnectedBy(userId, message));
this.userId = userId;
}
public User getUser() {
return userId == null
? User.getUnknown()
: User.getById(userId, true)
;
}
// Storing the User in a filed was a mistake, switch to userId
@SuppressWarnings("deprecation")
private Object readResolve() throws ObjectStreamException {
if (user != null) {
String id = user.getId();
if (id != null) {
userId = id;
} else {
// The user field is not properly deserialized so id may be missing. Look the user up by fullname
User user = User.get(this.user.getFullName(), true, Collections.emptyMap());
userId = user.getId();
}
this.user = null;
}
return this;
}
}
public static class ByCLI extends UserCause {
@Exported
public final String message;
public ByCLI(String message) {
super(User.current(), message);
this.message = message;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_3051_0
|
crossvul-java_data_bad_4188_0
|
package org.junit.rules;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import org.junit.Rule;
/**
* The TemporaryFolder Rule allows creation of files and folders that should
* be deleted when the test method finishes (whether it passes or
* fails).
* By default no exception will be thrown in case the deletion fails.
*
* <p>Example of usage:
* <pre>
* public static class HasTempFolder {
* @Rule
* public TemporaryFolder folder= new TemporaryFolder();
*
* @Test
* public void testUsingTempFolder() throws IOException {
* File createdFile= folder.newFile("myfile.txt");
* File createdFolder= folder.newFolder("subfolder");
* // ...
* }
* }
* </pre>
*
* <p>TemporaryFolder rule supports assured deletion mode, which
* will fail the test in case deletion fails with {@link AssertionError}.
*
* <p>Creating TemporaryFolder with assured deletion:
* <pre>
* @Rule
* public TemporaryFolder folder= TemporaryFolder.builder().assureDeletion().build();
* </pre>
*
* @since 4.7
*/
public class TemporaryFolder extends ExternalResource {
private final File parentFolder;
private final boolean assureDeletion;
private File folder;
private static final int TEMP_DIR_ATTEMPTS = 10000;
private static final String TMP_PREFIX = "junit";
/**
* Create a temporary folder which uses system default temporary-file
* directory to create temporary resources.
*/
public TemporaryFolder() {
this((File) null);
}
/**
* Create a temporary folder which uses the specified directory to create
* temporary resources.
*
* @param parentFolder folder where temporary resources will be created.
* If {@code null} then system default temporary-file directory is used.
*/
public TemporaryFolder(File parentFolder) {
this.parentFolder = parentFolder;
this.assureDeletion = false;
}
/**
* Create a {@link TemporaryFolder} initialized with
* values from a builder.
*/
protected TemporaryFolder(Builder builder) {
this.parentFolder = builder.parentFolder;
this.assureDeletion = builder.assureDeletion;
}
/**
* Returns a new builder for building an instance of {@link TemporaryFolder}.
*
* @since 4.13
*/
public static Builder builder() {
return new Builder();
}
/**
* Builds an instance of {@link TemporaryFolder}.
*
* @since 4.13
*/
public static class Builder {
private File parentFolder;
private boolean assureDeletion;
protected Builder() {}
/**
* Specifies which folder to use for creating temporary resources.
* If {@code null} then system default temporary-file directory is
* used.
*
* @return this
*/
public Builder parentFolder(File parentFolder) {
this.parentFolder = parentFolder;
return this;
}
/**
* Setting this flag assures that no resources are left undeleted. Failure
* to fulfill the assurance results in failure of tests with an
* {@link AssertionError}.
*
* @return this
*/
public Builder assureDeletion() {
this.assureDeletion = true;
return this;
}
/**
* Builds a {@link TemporaryFolder} instance using the values in this builder.
*/
public TemporaryFolder build() {
return new TemporaryFolder(this);
}
}
@Override
protected void before() throws Throwable {
create();
}
@Override
protected void after() {
delete();
}
// testing purposes only
/**
* for testing purposes only. Do not use.
*/
public void create() throws IOException {
folder = createTemporaryFolderIn(parentFolder);
}
/**
* Returns a new fresh file with the given name under the temporary folder.
*/
public File newFile(String fileName) throws IOException {
File file = new File(getRoot(), fileName);
if (!file.createNewFile()) {
throw new IOException(
"a file with the name \'" + fileName + "\' already exists in the test folder");
}
return file;
}
/**
* Returns a new fresh file with a random name under the temporary folder.
*/
public File newFile() throws IOException {
return File.createTempFile(TMP_PREFIX, null, getRoot());
}
/**
* Returns a new fresh folder with the given path under the temporary
* folder.
*/
public File newFolder(String path) throws IOException {
return newFolder(new String[]{path});
}
/**
* Returns a new fresh folder with the given paths under the temporary
* folder. For example, if you pass in the strings {@code "parent"} and {@code "child"}
* then a directory named {@code "parent"} will be created under the temporary folder
* and a directory named {@code "child"} will be created under the newly-created
* {@code "parent"} directory.
*/
public File newFolder(String... paths) throws IOException {
if (paths.length == 0) {
throw new IllegalArgumentException("must pass at least one path");
}
/*
* Before checking if the paths are absolute paths, check if create() was ever called,
* and if it wasn't, throw IllegalStateException.
*/
File root = getRoot();
for (String path : paths) {
if (new File(path).isAbsolute()) {
throw new IOException("folder path \'" + path + "\' is not a relative path");
}
}
File relativePath = null;
File file = root;
boolean lastMkdirsCallSuccessful = true;
for (String path : paths) {
relativePath = new File(relativePath, path);
file = new File(root, relativePath.getPath());
lastMkdirsCallSuccessful = file.mkdirs();
if (!lastMkdirsCallSuccessful && !file.isDirectory()) {
if (file.exists()) {
throw new IOException(
"a file with the path \'" + relativePath.getPath() + "\' exists");
} else {
throw new IOException(
"could not create a folder with the path \'" + relativePath.getPath() + "\'");
}
}
}
if (!lastMkdirsCallSuccessful) {
throw new IOException(
"a folder with the path \'" + relativePath.getPath() + "\' already exists");
}
return file;
}
/**
* Returns a new fresh folder with a random name under the temporary folder.
*/
public File newFolder() throws IOException {
return createTemporaryFolderIn(getRoot());
}
private File createTemporaryFolderIn(File parentFolder) throws IOException {
File createdFolder = null;
for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) {
// Use createTempFile to get a suitable folder name.
String suffix = ".tmp";
File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder);
String tmpName = tmpFile.toString();
// Discard .tmp suffix of tmpName.
String folderName = tmpName.substring(0, tmpName.length() - suffix.length());
createdFolder = new File(folderName);
if (createdFolder.mkdir()) {
tmpFile.delete();
return createdFolder;
}
tmpFile.delete();
}
throw new IOException("Unable to create temporary directory in: "
+ parentFolder.toString() + ". Tried " + TEMP_DIR_ATTEMPTS + " times. "
+ "Last attempted to create: " + createdFolder.toString());
}
/**
* @return the location of this temporary folder.
*/
public File getRoot() {
if (folder == null) {
throw new IllegalStateException(
"the temporary folder has not yet been created");
}
return folder;
}
/**
* Delete all files and folders under the temporary folder. Usually not
* called directly, since it is automatically applied by the {@link Rule}.
*
* @throws AssertionError if unable to clean up resources
* and deletion of resources is assured.
*/
public void delete() {
if (!tryDelete()) {
if (assureDeletion) {
fail("Unable to clean up temporary folder " + folder);
}
}
}
/**
* Tries to delete all files and folders under the temporary folder and
* returns whether deletion was successful or not.
*
* @return {@code true} if all resources are deleted successfully,
* {@code false} otherwise.
*/
private boolean tryDelete() {
if (folder == null) {
return true;
}
return recursiveDelete(folder);
}
private boolean recursiveDelete(File file) {
// Try deleting file before assuming file is a directory
// to prevent following symbolic links.
if (file.delete()) {
return true;
}
File[] files = file.listFiles();
if (files != null) {
for (File each : files) {
if (!recursiveDelete(each)) {
return false;
}
}
}
return file.delete();
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_4188_0
|
crossvul-java_data_good_4347_6
|
/*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.config;
import java.util.Arrays;
import org.apache.commons.lang3.math.NumberUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention;
import org.dpppt.backend.sdk.ws.radarcovid.exception.RadarCovidServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* Aspect in charge of controlling the minimum response time of a service.
*/
@Configuration
@ConditionalOnProperty(name = "application.response.retention.enabled", havingValue = "true", matchIfMissing = true)
public class ResponseRetentionAspectConfiguration {
private static final Logger log = LoggerFactory.getLogger("org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention");
@Autowired
private Environment environment;
@Aspect
@Order(0)
@Component
public class ControllerTimeResponseControlAspect {
@Pointcut("@annotation(responseRetention)")
public void annotationPointCutDefinition(ResponseRetention responseRetention){
}
@Around("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention * *..controller..*(..)) && annotationPointCutDefinition(responseRetention)")
public Object logAround(ProceedingJoinPoint joinPoint, ResponseRetention responseRetention) throws Throwable {
log.debug("************************* INIT TIME RESPONSE CONTROL *********************************");
long start = System.currentTimeMillis();
try {
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - start;
long responseRetentionTimeMillis = getTimeMillis(responseRetention.time());
log.debug("Controller : Controller {}.{} () execution time : {} ms", className, methodName, elapsedTime);
if (elapsedTime < responseRetentionTimeMillis) {
try {
Thread.sleep(responseRetentionTimeMillis - elapsedTime);
} catch (InterruptedException e) {
log.warn("Controller : Controller {}.{} () Thread sleep interrupted", className, methodName);
}
}
elapsedTime = System.currentTimeMillis() - start;
log.debug("Controller : Controller {}.{} () NEW execution time : {} ms", className, methodName, elapsedTime);
log.debug("************************* END TIME RESPONSE CONTROL **********************************");
return result;
} catch (IllegalArgumentException e) {
log.error("Controller : Illegal argument {} in {} ()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getName());
log.debug("************************* END TIME RESPONSE CONTROL **********************************");
throw e;
}
}
private long getTimeMillis(String timeMillisString) {
String stringValue = environment.getProperty(timeMillisString);
if (NumberUtils.isCreatable(stringValue)) {
return Long.parseLong(stringValue);
} else {
throw new RadarCovidServerException(HttpStatus.INTERNAL_SERVER_ERROR,
"Invalid timeMillisString value \"" + timeMillisString + "\" - not found or cannot parse into long");
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_4347_6
|
crossvul-java_data_good_3053_1
|
package jenkins.security;
import com.gargoylesoftware.htmlunit.Page;
import hudson.model.UnprotectedRootAction;
import hudson.security.ACL;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.util.HttpResponses;
import jenkins.model.Jenkins;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.HttpResponse;
public class Security380Test {
@Rule
public JenkinsRule j = new JenkinsRule();
@Issue("SECURITY-380")
@Test
public void testGetItemsWithoutAnonRead() throws Exception {
FullControlOnceLoggedInAuthorizationStrategy strategy = new FullControlOnceLoggedInAuthorizationStrategy();
strategy.setAllowAnonymousRead(false);
Jenkins.getInstance().setAuthorizationStrategy(strategy);
Jenkins.getInstance().setSecurityRealm(j.createDummySecurityRealm());
j.createFreeStyleProject();
ACL.impersonate(Jenkins.ANONYMOUS, new Runnable() {
@Override
public void run() {
Assert.assertEquals("no items", 0, Jenkins.getInstance().getItems().size());
}
});
}
@Issue("SECURITY-380")
@Test
public void testGetItems() throws Exception {
FullControlOnceLoggedInAuthorizationStrategy strategy = new FullControlOnceLoggedInAuthorizationStrategy();
strategy.setAllowAnonymousRead(true);
Jenkins.getInstance().setAuthorizationStrategy(strategy);
Jenkins.getInstance().setSecurityRealm(j.createDummySecurityRealm());
j.createFreeStyleProject();
ACL.impersonate(Jenkins.ANONYMOUS, new Runnable() {
@Override
public void run() {
Assert.assertEquals("one item", 1, Jenkins.getInstance().getItems().size());
}
});
}
@Issue("SECURITY-380")
@Test
public void testWithUnprotectedRootAction() throws Exception {
FullControlOnceLoggedInAuthorizationStrategy strategy = new FullControlOnceLoggedInAuthorizationStrategy();
strategy.setAllowAnonymousRead(false);
Jenkins.getInstance().setAuthorizationStrategy(strategy);
Jenkins.getInstance().setSecurityRealm(j.createDummySecurityRealm());
j.createFreeStyleProject();
JenkinsRule.WebClient wc = j.createWebClient();
Page page = wc.goTo("listJobs", "text/plain");
Assert.assertEquals("expect 0 items", "0", page.getWebResponse().getContentAsString().trim());
}
@TestExtension
public static class JobListingUnprotectedRootAction implements UnprotectedRootAction {
@Override
public String getIconFileName() {
return null;
}
@Override
public String getDisplayName() {
return null;
}
@Override
public String getUrlName() {
return "listJobs";
}
public HttpResponse doIndex() throws Exception {
return HttpResponses.plainText(Integer.toString(Jenkins.getInstance().getItems().size()));
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_3053_1
|
crossvul-java_data_good_4347_5
|
/*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* Aspecto encargado de trazar la información de los servicios implementados.
*/
@Configuration
@ConditionalOnProperty(name = "application.log.enabled", havingValue = "true", matchIfMissing = true)
public class MethodLoggerAspectConfiguration {
private static final Logger log = LoggerFactory.getLogger("org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable");
@Aspect
@Order(2)
@Component
public class MethodLoggerAspect {
@Before("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..business.impl..*(..))")
public void logBefore(JoinPoint joinPoint) {
if (log.isDebugEnabled()) {
log.debug(" ************************* INIT SERVICE ******************************");
log.debug(" Service : Entering in Method : {}", joinPoint.getSignature().getDeclaringTypeName());
log.debug(" Service : Method : {}", joinPoint.getSignature().getName());
log.debug(" Service : Arguments : {}", Arrays.toString(joinPoint.getArgs()));
log.debug(" Service : Target class : {}", joinPoint.getTarget().getClass().getName());
}
}
@AfterThrowing(pointcut = "execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..business.impl..*(..))", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
log.error(" Service : An exception has been thrown in {} ()", joinPoint.getSignature().getName());
log.error(" Service : Cause : {}", exception.getCause());
log.error(" Service : Message : {}", exception.getMessage());
log.debug(" ************************** END SERVICE ******************************");
}
@Around("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..business.impl..*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
try {
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - start;
log.debug(" Service : {}.{} () execution time: {} ms", className, methodName, elapsedTime);
log.debug(" ************************** END SERVICE ******************************");
return result;
} catch (IllegalArgumentException e) {
log.error(" Service : Illegal argument {} in {}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getName(), e);
log.debug(" ************************** END SERVICE ******************************");
throw e;
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_4347_5
|
crossvul-java_data_bad_3053_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* 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.
*/
package jenkins.model;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.Lookup;
import hudson.Main;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import jenkins.util.SystemProperties;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.init.TermMilestone;
import hudson.init.TerminatorFinder;
import hudson.lifecycle.Lifecycle;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.logging.LogRecorderManager;
import hudson.markup.EscapedMarkupFormatter;
import hudson.markup.MarkupFormatter;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.LoadStatistics;
import hudson.model.ManagementLink;
import hudson.model.Messages;
import hudson.model.ModifiableViewGroup;
import hudson.model.NoFingerprintMatch;
import hudson.model.Node;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.NamingThreadFactory;
import hudson.util.PluginServletFilter;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import java.util.Objects;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.install.InstallState;
import jenkins.install.InstallUtil;
import jenkins.install.SetupWizard;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.JenkinsJVM;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import jenkins.util.xml.XMLUtils;
import net.jcip.annotations.GuardedBy;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Milestone;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.ReactorListener;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static hudson.Util.*;
import static hudson.init.InitMilestone.*;
import hudson.init.Initializer;
import hudson.util.LogTaskListener;
import static java.util.logging.Level.*;
import static javax.servlet.http.HttpServletResponse.*;
import org.kohsuke.stapler.WebMethod;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Jenkins whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* The Jenkins instance startup type i.e. NEW, UPGRADE etc
*/
private transient InstallState installState = InstallState.UNKNOWN;
/**
* If we're in the process of an initial setup,
* this will be set
*/
private transient SetupWizard setupWizard;
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Jenkins.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Jenkins.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
@GuardedBy("Jenkins.class")
private transient boolean cleanUpStarted;
private volatile List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Jenkins system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Legacy store of the set of installed cluster nodes.
* @deprecated in favour of {@link Nodes}
*/
@Deprecated
protected transient volatile NodeList slaves;
/**
* The holder of the set of installed cluster nodes.
*
* @since 1.607
*/
private transient final Nodes nodes = new Nodes(this);
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient final Object tcpSlaveAgentListenerLock = new Object();
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort = SystemProperties.getInteger(Jenkins.class.getName()+".slaveAgentPort",0);
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and agents.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* agents and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Jenkins.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
@CheckForNull Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public @CheckForNull Jenkins getInstance() {
return theInstance;
}
};
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstanceOrNull()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
* @deprecated use {@link #getInstance()}
*/
@Deprecated
@Nonnull
public static Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Gets the {@link Jenkins} singleton.
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
* @since 1.653
*/
@CheckForNull
public static Jenkins getInstanceOrNull() {
return HOLDER.getInstance();
}
/**
* Gets the {@link Jenkins} singleton. In certain rare cases you may have code that is intended to run before
* Jenkins starts or while Jenkins is being shut-down. For those rare cases use {@link #getInstanceOrNull()}.
* In other cases you may have code that might end up running on a remote JVM and not on the Jenkins master,
* for those cases you really should rewrite your code so that when the {@link Callable} is sent over the remoting
* channel it uses a {@code writeReplace} method or similar to ensure that the {@link Jenkins} class is not being
* loaded into the remote class loader
* @return The instance.
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
*/
@CLIResolver
@Nonnull
public static Jenkins getInstance() {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
if(SystemProperties.getBoolean(Jenkins.class.getName()+".enableExceptionOnNullInstance")) {
// TODO: remove that second block around 2.20 (that is: ~20 versions to battle test it)
// See https://github.com/jenkinsci/jenkins/pull/2297#issuecomment-216710150
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
}
return instance;
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = UpdateCenter.createUpdateCenter(null);
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
private transient final boolean oldJenkinsJVM;
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root, context, null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
oldJenkinsJVM = JenkinsJVM.isJenkinsJVM(); // capture to restore in cleanUp()
JenkinsJVMAccess._setJenkinsJVM(true); // set it for unit tests as they will not have gone through WebAppMain
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with agents
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = PluginManager.createDefault(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
setupWizard = new SetupWizard();
InstallUtil.proceedToNextStateFrom(InstallState.UNKNOWN);
launchTcpSlaveAgentListener();
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c, new LogTaskListener(LOGGER, INFO));
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Maintains backwards compatibility. Invoked by XStream when this object is de-serialized.
*/
@SuppressWarnings({"unused"})
private Object readResolve() {
if (jdks == null) {
jdks = new ArrayList<>();
}
return this;
}
/**
* Get the Jenkins {@link jenkins.install.InstallState install state}.
* @return The Jenkins {@link jenkins.install.InstallState install state}.
*/
@Nonnull
@Restricted(NoExternalUse.class)
public InstallState getInstallState() {
if (installState == null || installState.name() == null) {
return InstallState.UNKNOWN;
}
return installState;
}
/**
* Update the current install state. This will invoke state.initializeState()
* when the state has been transitioned.
*/
@Restricted(NoExternalUse.class)
public void setInstallState(@Nonnull InstallState newState) {
InstallState prior = installState;
installState = newState;
if (!prior.equals(newState)) {
newState.initializeState();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
if (milestone==PLUGINS_PREPARED) {
// set up Guice to enable injection as early as possible
// before this milestone, ExtensionList.ensureLoaded() won't actually try to locate instances
ExtensionList.lookup(ExtensionFinder.class).getComponents();
}
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
launchTcpSlaveAgentListener();
}
private void launchTcpSlaveAgentListener() throws IOException {
synchronized(tcpSlaveAgentListenerLock) {
// shutdown previous agent if the port has changed
if (tcpSlaveAgentListener != null && tcpSlaveAgentListener.configuredPort != slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
}
if (slaveAgentPort != -1 && tcpSlaveAgentListener == null) {
String administrativeMonitorId = getClass().getName() + ".tcpBind";
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
// remove previous monitor in case of previous error
for (Iterator<AdministrativeMonitor> it = AdministrativeMonitor.all().iterator(); it.hasNext(); ) {
AdministrativeMonitor am = it.next();
if (administrativeMonitorId.equals(am.id)) {
it.remove();
}
}
} catch (BindException e) {
LOGGER.log(Level.WARNING, String.format("Failed to listen to incoming agent connections through JNLP port %s. Change the JNLP port number", slaveAgentPort), e);
new AdministrativeError(administrativeMonitorId,
"Failed to listen to incoming agent connections through JNLP",
"Failed to listen to incoming agent connections through JNLP. <a href='configureSecurity'>Change the JNLP port number</a> to solve the problem.", e);
}
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
@Deprecated
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
@Deprecated
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName, SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
@Deprecated
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Jenkins by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName, SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/** @deprecated Use {@link SCMListener#all} instead. */
@Deprecated
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public @Nonnull MarkupFormatter getMarkupFormatter() {
MarkupFormatter f = markupFormatter;
return f != null ? f : new EscapedMarkupFormatter();
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Jenkins.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(), Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
/**
* Completely replaces views.
*
* <p>
* This operation is NOT provided as an atomic operation, but rather
* the sole purpose of this is to define a setter for this to help
* introspecting code, such as system-config-dsl plugin
*/
// even if we want to offer this atomic operation, CopyOnWriteArrayList
// offers no such operation
public void setViews(Collection<View> views) throws IOException {
BulkChange bc = new BulkChange(this);
try {
this.views.clear();
for (View v : views) {
addView(v);
}
} finally {
bc.commit();
}
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view, oldName, newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Jenkins.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Jenkins forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
@Override public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return lhs.getName().compareTo(rhs.getName());
}
});
return r;
}
@CLIResolver
public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public List<JDK> getJDKs() {
return jdks;
}
/**
* Replaces all JDK installations with those from the given collection.
*
* Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to
* set JDK installations from external code.
*/
@Restricted(NoExternalUse.class)
public void setJDKs(Collection<? extends JDK> jdks) {
this.jdks = new ArrayList<JDK>(jdks);
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the agent node of the give name, hooked under this Jenkins.
*/
public @CheckForNull Node getNode(String name) {
return nodes.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return nodes.getNodes();
}
/**
* Get the {@link Nodes} object that handles maintaining individual {@link Node}s.
* @return The Nodes object.
*/
@Restricted(NoExternalUse.class)
public Nodes getNodesObject() {
// TODO replace this with something better when we properly expose Nodes.
return nodes;
}
/**
* Adds one more {@link Node} to Jenkins.
*/
public void addNode(Node n) throws IOException {
nodes.addNode(n);
}
/**
* Removes a {@link Node} from Jenkins.
*/
public void removeNode(@Nonnull Node n) throws IOException {
nodes.removeNode(n);
}
/**
* Saves an existing {@link Node} on disk, called by {@link Node#save()}. This method is preferred in those cases
* where you need to determine atomically that the node being saved is actually in the list of nodes.
*
* @param n the node to be updated.
* @return {@code true}, if the node was updated. {@code false}, if the node was not in the list of nodes.
* @throws IOException if the node could not be persisted.
* @see Nodes#updateNode
* @since 1.634
*/
public boolean updateNode(Node n) throws IOException {
return nodes.updateNode(n);
}
public void setNodes(final List<? extends Node> n) throws IOException {
nodes.setNodes(n);
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
/*package*/ void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
// do essentially what expandVariablesForDirectory does, without an Item
String replacedValue = expandVariablesForDirectory(value,
"doCheckRawBuildsDir-Marker:foo",
Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo");
File replacedFile = new File(replacedValue);
if (!replacedFile.isAbsolute()) {
return FormValidation.error(value + " does not resolve to an absolute path");
}
if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) {
return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects");
}
if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) {
// make sure platform can handle colon
try {
File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar");
tmp.delete();
} catch (IOException e) {
return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead");
}
}
File d = new File(replacedValue);
if (!d.isDirectory()) {
// if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to
d = d.getParentFile();
while (!d.exists()) {
d = d.getParentFile();
}
if (!d.canWrite()) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
}
return FormValidation.ok();
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}.
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link #getRootUrlFromRequest}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /}
* @since 1.66
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public @Nullable String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}.
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* <p>Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy which has not been fully configured.
* Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set.
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a>
* shows some examples of configuration.
* @since 1.263
*/
public @Nonnull String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
int index = host.indexOf(':');
int port = req.getServerPort();
if (index == -1) {
// Almost everyone else except Nginx put the host and port in separate headers
buf.append(host);
} else {
// Nginx uses the same spec as for the Host header, i.e. hostanme:port
buf.append(host.substring(0, index));
if (index + 1 < host.length()) {
try {
port = Integer.parseInt(host.substring(index + 1));
} catch (NumberFormatException e) {
// ignore
}
}
// but if a user has configured Nginx with an X-Forwarded-Port, that will win out.
}
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath()));
}
@Restricted(NoExternalUse.class)
static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) {
return Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(),
"ITEM_ROOTDIR", itemRootDir,
"ITEM_FULLNAME", itemFullName, // legacy, deprecated
"ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
@Restricted(NoExternalUse.class)
public void setRawBuildsDir(String buildsDir) {
this.buildsDir = buildsDir;
}
@Override public @Nonnull FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new MasterToSlaveCallable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Jenkins would have to have crumb in it to protect
* Jenkins from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes in Jenkins.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
IdStrategy oldUserIdStrategy = this.securityRealm == null
? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load
: this.securityRealm.getUserIdStrategy();
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) {
User.rekey();
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
* @see ExtensionList#lookup
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Jenkins is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
if (this.numExecutors != n) {
this.numExecutors = n;
updateComputerList();
save();
}
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override public TopLevelItem getItem(String name) throws AccessDeniedException {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
* @throws AccessDeniedException as per {@link ItemGroup#getItem}
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean), {@link User#getById(String, boolean)}
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Jenkins by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(job, oldName, newName);
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
}
@Override public boolean canAdd(TopLevelItem item) {
return true;
}
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
items.put(name, item);
return item;
}
@Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException {
items.remove(item.getName());
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private void loadConfig() throws IOException {
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles();
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
loadConfig();
// if we are loading old data that doesn't have this field
if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) {
nodes.setNodes(slaves);
slaves = null;
} else {
nodes.load();
}
clouds.setOwner(Jenkins.this);
}
});
for (final File subdir : subdirs) {
g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
if(!Items.getConfigFile(subdir).exists()) {
//Does not have job config file, so it is not a jenkins job hence skip it
return;
}
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : nodes.getNodes())
// Note that not all labels are visible until the agents have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Jenkins and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
if (theInstance != this && theInstance != null) {
LOGGER.log(Level.WARNING, "This instance is no longer the singleton, ignoring cleanUp()");
return;
}
synchronized (Jenkins.class) {
if (cleanUpStarted) {
LOGGER.log(Level.WARNING, "Jenkins.cleanUp() already started, ignoring repeated cleanUp()");
return;
}
cleanUpStarted = true;
}
try {
LOGGER.log(Level.INFO, "Stopping Jenkins");
final List<Throwable> errors = new ArrayList<>();
fireBeforeShutdown(errors);
_cleanUpRunTerminators(errors);
terminating = true;
final Set<Future<?>> pending = _cleanUpDisconnectComputers(errors);
_cleanUpShutdownUDPBroadcast(errors);
_cleanUpCloseDNSMulticast(errors);
_cleanUpInterruptReloadThread(errors);
_cleanUpShutdownTriggers(errors);
_cleanUpShutdownTimer(errors);
_cleanUpShutdownTcpSlaveAgent(errors);
_cleanUpShutdownPluginManager(errors);
_cleanUpPersistQueue(errors);
_cleanUpShutdownThreadPoolForLoad(errors);
_cleanUpAwaitDisconnects(errors, pending);
_cleanUpPluginServletFilters(errors);
_cleanUpReleaseAllLoggers(errors);
LOGGER.log(Level.INFO, "Jenkins stopped");
if (!errors.isEmpty()) {
StringBuilder message = new StringBuilder("Unexpected issues encountered during cleanUp: ");
Iterator<Throwable> iterator = errors.iterator();
message.append(iterator.next().getMessage());
while (iterator.hasNext()) {
message.append("; ");
message.append(iterator.next().getMessage());
}
iterator = errors.iterator();
RuntimeException exception = new RuntimeException(message.toString(), iterator.next());
while (iterator.hasNext()) {
exception.addSuppressed(iterator.next());
}
throw exception;
}
} finally {
theInstance = null;
if (JenkinsJVM.isJenkinsJVM()) {
JenkinsJVMAccess._setJenkinsJVM(oldJenkinsJVM);
}
}
}
private void fireBeforeShutdown(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Notifying termination");
for (ItemListener l : ItemListener.all()) {
try {
l.onBeforeShutdown();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(Level.WARNING, "ItemListener " + l + ": " + e.getMessage(), e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "ItemListener " + l + ": " + e.getMessage(), e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpRunTerminators(List<Throwable> errors) {
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
}, new ReactorListener() {
final Level level = Level.parse(Configuration.getStringConfigParameter("termLogLevel", "FINE"));
public void onTaskStarted(Task t) {
LOGGER.log(level, "Started " + t.getDisplayName());
}
public void onTaskCompleted(Task t) {
LOGGER.log(level, "Completed " + t.getDisplayName());
}
public void onTaskFailed(Task t, Throwable err, boolean fatal) {
LOGGER.log(SEVERE, "Failed " + t.getDisplayName(), err);
}
public void onAttained(Milestone milestone) {
Level lv = level;
String s = "Attained " + milestone.toString();
if (milestone instanceof TermMilestone) {
lv = Level.INFO; // noteworthy milestones --- at least while we debug problems further
s = milestone.toString();
}
LOGGER.log(lv, s);
}
});
} catch (InterruptedException | ReactorException | IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
errors.add(e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to execute termination", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to execute termination", e);
// save for later
errors.add(e);
}
}
private Set<Future<?>> _cleanUpDisconnectComputers(final List<Throwable> errors) {
LOGGER.log(Level.INFO, "Starting node disconnection");
final Set<Future<?>> pending = new HashSet<Future<?>>();
// JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Computer c : computers.values() ) {
try {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(Level.WARNING, "Could not disconnect " + c + ": " + e.getMessage(), e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Could not disconnect " + c + ": " + e.getMessage(), e);
// save for later
errors.add(e);
}
}
}
});
return pending;
}
private void _cleanUpShutdownUDPBroadcast(List<Throwable> errors) {
if(udpBroadcastThread!=null) {
LOGGER.log(Level.FINE, "Shutting down {0}", udpBroadcastThread.getName());
try {
udpBroadcastThread.shutdown();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shutdown UDP Broadcast Thread", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shutdown UDP Broadcast Thread", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpCloseDNSMulticast(List<Throwable> errors) {
if(dnsMultiCast!=null) {
LOGGER.log(Level.FINE, "Closing DNS Multicast service");
try {
dnsMultiCast.close();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpInterruptReloadThread(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Interrupting reload thread");
try {
interruptReloadThread();
} catch (SecurityException e) {
LOGGER.log(WARNING, "Not permitted to interrupt reload thread", e);
errors.add(e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to interrupt reload thread", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to interrupt reload thread", e);
// save for later
errors.add(e);
}
}
private void _cleanUpShutdownTriggers(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Shutting down triggers");
try {
final java.util.Timer timer = Trigger.timer;
if (timer != null) {
final CountDownLatch latch = new CountDownLatch(1);
timer.schedule(new TimerTask() {
@Override
public void run() {
timer.cancel();
latch.countDown();
}
}, 0);
if (latch.await(10, TimeUnit.SECONDS)) {
LOGGER.log(Level.FINE, "Triggers shut down successfully");
} else {
timer.cancel();
LOGGER.log(Level.INFO, "Gave up waiting for triggers to finish running");
}
}
Trigger.timer = null;
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shut down triggers", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shut down triggers", e);
// save for later
errors.add(e);
}
}
private void _cleanUpShutdownTimer(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Shutting down timer");
try {
Timer.shutdown();
} catch (SecurityException e) {
LOGGER.log(WARNING, "Not permitted to shut down Timer", e);
errors.add(e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shut down Timer", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shut down Timer", e);
// save for later
errors.add(e);
}
}
private void _cleanUpShutdownTcpSlaveAgent(List<Throwable> errors) {
if(tcpSlaveAgentListener!=null) {
LOGGER.log(FINE, "Shutting down TCP/IP slave agent listener");
try {
tcpSlaveAgentListener.shutdown();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shut down TCP/IP slave agent listener", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shut down TCP/IP slave agent listener", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpShutdownPluginManager(List<Throwable> errors) {
if(pluginManager!=null) {// be defensive. there could be some ugly timing related issues
LOGGER.log(Level.INFO, "Stopping plugin manager");
try {
pluginManager.stop();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to stop plugin manager", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to stop plugin manager", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpPersistQueue(List<Throwable> errors) {
if(getRootDir().exists()) {
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
LOGGER.log(Level.INFO, "Persisting build queue");
try {
getQueue().save();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to persist build queue", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to persist build queue", e);
// save for later
errors.add(e);
}
}
}
private void _cleanUpShutdownThreadPoolForLoad(List<Throwable> errors) {
LOGGER.log(FINE, "Shuting down Jenkins load thread pool");
try {
threadPoolForLoad.shutdown();
} catch (SecurityException e) {
LOGGER.log(WARNING, "Not permitted to shut down Jenkins load thread pool", e);
errors.add(e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to shut down Jenkins load thread pool", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to shut down Jenkins load thread pool", e);
// save for later
errors.add(e);
}
}
private void _cleanUpAwaitDisconnects(List<Throwable> errors, Set<Future<?>> pending) {
if (!pending.isEmpty()) {
LOGGER.log(Level.INFO, "Waiting for node disconnection completion");
}
for (Future<?> f : pending) {
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection cleanly", e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection within 10 seconds", e);
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection", e);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Unexpected error while waiting for remote computer connection disconnect", e);
errors.add(e);
}
}
}
private void _cleanUpPluginServletFilters(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Stopping filters");
try {
PluginServletFilter.cleanUp();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to stop filters", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to stop filters", e);
// save for later
errors.add(e);
}
}
private void _cleanUpReleaseAllLoggers(List<Throwable> errors) {
LOGGER.log(Level.FINE, "Releasing all loggers");
try {
LogFactory.releaseAll();
} catch (OutOfMemoryError e) {
// we should just propagate this, no point trying to log
throw e;
} catch (LinkageError e) {
LOGGER.log(SEVERE, "Failed to release all loggers", e);
// safe to ignore and continue for this one
} catch (Throwable e) {
LOGGER.log(SEVERE, "Failed to release all loggers", e);
// save for later
errors.add(e);
}
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if (Objects.equals(a.getUrlName(), token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
@RequirePOST
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
@RequirePOST // TODO does not seem to work on _either_ overload!
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
@RequirePOST
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
long waitUntil = timeout;
if (timeout > 0) waitUntil += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < waitUntil)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
@RequirePOST // TODO the cancel link needs to be updated accordingly
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all agents (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang agents.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r));
}
@RequirePOST
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
@RequirePOST
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if(".".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName("."));
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
* Used only by {@link LegacySecurityRealm}.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
// TODO fire something in SecurityListener?
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String user = getAuthentication().getName();
securityRealm.doLogout(req, rsp);
SecurityListener.fireLoggedOut(user);
}
/**
* Serves jar files for JNLP agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
LOGGER.log(Level.WARNING, "Reloading Jenkins as requested by {0}", getAuthentication().getName());
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
* Beware that this calls neither {@link ItemListener#onLoaded} nor {@link Initializer}s.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
queue.save();
executeReactor(null, loadTasks());
User.reload();
queue.load();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
@RequirePOST
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,FilePath.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Jenkins, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Jenkins for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException | IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
@Extension @Restricted(NoExternalUse.class)
public static class MasterRestartNotifyier extends RestartListener {
@Override
public void onRestart() {
Computer computer = Jenkins.getInstance().toComputer();
if (computer == null) return;
RestartCause cause = new RestartCause();
for (ComputerListener listener: ComputerListener.all()) {
listener.onOffline(computer, cause);
}
}
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return true;
}
private static class RestartCause extends OfflineCause.SimpleOfflineCause {
protected RestartCause() {
super(Messages._Jenkins_IsRestarting());
}
}
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
@RequirePOST
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
@RequirePOST
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static @Nonnull Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
if (channel == null) {
throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if (getSecurityRealm().allowsSignup()) {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
return;
}
req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
@RequirePOST
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
@RequirePOST
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!JDK.isDefaultName(value))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
@Deprecated
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
}, 500, TimeUnit.MILLISECONDS);
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* If set, a currently active setup wizard - e.g. installation
*
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public SetupWizard getSetupWizard() {
return setupWizard;
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
for (String name : ALWAYS_READABLE_PATHS) {
if (rest.startsWith(name)) {
return this;
}
}
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
if (rest.matches("/computer/[^/]+/slave-agent[.]jnlp")
&& "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))) {
return this;
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
String url = a.getUrlName();
if (url == null) continue;
names.add(url);
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
@Override
public Boolean isUnix() {
return !Functions.isWindows();
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@WebMethod(name="config.xml")
@Override
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return FilePath.localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
@RequirePOST
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*
* @deprecated as of 1.558
* Use {@link FilePath#localChannel}
*/
@Deprecated
public static final LocalChannel localChannel = FilePath.localChannel;
}
/**
* Shortcut for {@code Jenkins.getInstanceOrNull()?.lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstanceOrNull();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Jenkins.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM;
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver = UNCOMPUTED_VERSION;
if(Main.isDevelopmentMode && "${build.version}".equals(ver)) {
// in dev mode, unable to get version (ahem Eclipse)
try {
File dir = new File(".").getAbsoluteFile();
while(dir != null) {
File pom = new File(dir, "pom.xml");
if (pom.exists() && "pom".equals(XMLUtils.getValue("/project/artifactId", pom))) {
pom = pom.getCanonicalFile();
LOGGER.info("Reading version from: " + pom.getAbsolutePath());
ver = XMLUtils.getValue("/project/version", pom);
break;
}
dir = dir.getParentFile();
}
LOGGER.info("Jenkins is in dev mode, using version: " + ver);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Unable to read Jenkins version: " + e.getMessage(), e);
}
}
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals(UNCOMPUTED_VERSION) || SystemProperties.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* The version number before it is "computed" (by a call to computeVersion()).
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public static final String UNCOMPUTED_VERSION = "?";
/**
* Version number of this Jenkins.
*/
public static String VERSION = UNCOMPUTED_VERSION;
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
public @CheckForNull static VersionNumber getVersion() {
return toVersion(VERSION);
}
/**
* Get the stored version of Jenkins, as stored by
* {@link #doConfigSubmit(org.kohsuke.stapler.StaplerRequest, org.kohsuke.stapler.StaplerResponse)}.
* <p>
* Parses the version into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public @CheckForNull static VersionNumber getStoredVersion() {
return toVersion(Jenkins.getActiveInstance().version);
}
/**
* Parses a version string into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
private static @CheckForNull VersionNumber toVersion(@CheckForNull String versionString) {
if (versionString == null) {
return null;
}
try {
return new VersionNumber(versionString);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = versionString.indexOf(' ');
if (idx > 0) {
return new VersionNumber(versionString.substring(0,idx));
}
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* @deprecated No longer used.
*/
@Deprecated
public static boolean FLYWEIGHT_SUPPORT = true;
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch an agent when Jenkins is initialized or a new agent computer is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* Urls that are always visible without READ permission.
*
* <p>See also:{@link #getUnprotectedRootActions}.
*/
private static final ImmutableSet<String> ALWAYS_READABLE_PATHS = ImmutableSet.of(
"/login",
"/logout",
"/accessDenied",
"/adjuncts/",
"/error",
"/oops",
"/signup",
"/tcpSlaveAgentListener",
"/federatedLoginService/",
"/securityRealm"
);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS;
static {
try {
ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
XSTREAM = XSTREAM2 = new XStream2();
XSTREAM.alias("jenkins", Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk", JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
XSTREAM2.addCriticalField(Jenkins.class, "securityRealm");
XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy");
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS != null;
assert ADMINISTER != null;
} catch (RuntimeException | Error e) {
// when loaded on an agent and this fails, subsequent NoClassDefFoundError will fail to chain the cause.
// see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847
// As we don't know where the first exception will go, let's also send this to logging so that
// we have a known place to look at.
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
}
}
private static final class JenkinsJVMAccess extends JenkinsJVM {
private static void _setJenkinsJVM(boolean jenkinsJVM) {
JenkinsJVM.setJenkinsJVM(jenkinsJVM);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_3053_0
|
crossvul-java_data_bad_3048_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Red Hat, Inc., Seiji Sogabe, Stephen Connolly, Thomas J. Black, Tom Huybrechts, CloudBees, Inc.
*
* 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.
*/
package hudson.model;
import edu.umd.cs.findbugs.annotations.OverrideMustInvoke;
import edu.umd.cs.findbugs.annotations.When;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Launcher.ProcStarter;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.console.AnnotatedLargeText;
import hudson.init.Initializer;
import hudson.model.Descriptor.FormException;
import hudson.model.Queue.FlyweightTask;
import hudson.model.labels.LabelAtom;
import hudson.model.queue.WorkUnit;
import hudson.node_monitors.NodeMonitor;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.slaves.AbstractCloudSlave;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.ComputerListener;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import hudson.slaves.WorkspaceList;
import hudson.slaves.OfflineCause;
import hudson.slaves.OfflineCause.ByCLI;
import hudson.util.DaemonThreadFactory;
import hudson.util.EditDistance;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.RunList;
import hudson.util.Futures;
import hudson.util.NamingThreadFactory;
import jenkins.model.Jenkins;
import jenkins.util.ContextResettingExecutorService;
import jenkins.security.MasterToSlaveCallable;
import jenkins.security.NotReallyRoleSensitiveCallable;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.nio.charset.Charset;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Inet4Address;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Represents the running state of a remote computer that holds {@link Executor}s.
*
* <p>
* {@link Executor}s on one {@link Computer} are transparently interchangeable
* (that is the definition of {@link Computer}).
*
* <p>
* This object is related to {@link Node} but they have some significant differences.
* {@link Computer} primarily works as a holder of {@link Executor}s, so
* if a {@link Node} is configured (probably temporarily) with 0 executors,
* you won't have a {@link Computer} object for it (except for the master node,
* which always gets its {@link Computer} in case we have no static executors and
* we need to run a {@link FlyweightTask} - see JENKINS-7291 for more discussion.)
*
* Also, even if you remove a {@link Node}, it takes time for the corresponding
* {@link Computer} to be removed, if some builds are already in progress on that
* node. Or when the node configuration is changed, unaffected {@link Computer} object
* remains intact, while all the {@link Node} objects will go away.
*
* <p>
* This object also serves UI (unlike {@link Node}), and can be used along with
* {@link TransientComputerActionFactory} to add {@link Action}s to {@link Computer}s.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public /*transient*/ abstract class Computer extends Actionable implements AccessControlled, ExecutorListener {
private final CopyOnWriteArrayList<Executor> executors = new CopyOnWriteArrayList<Executor>();
// TODO:
private final CopyOnWriteArrayList<OneOffExecutor> oneOffExecutors = new CopyOnWriteArrayList<OneOffExecutor>();
private int numExecutors;
/**
* Contains info about reason behind computer being offline.
*/
protected volatile OfflineCause offlineCause;
private long connectTime = 0;
/**
* True if Jenkins shouldn't start new builds on this node.
*/
private boolean temporarilyOffline;
/**
* {@link Node} object may be created and deleted independently
* from this object.
*/
protected String nodeName;
/**
* @see #getHostName()
*/
private volatile String cachedHostName;
private volatile boolean hostNameCached;
/**
* @see #getEnvironment()
*/
private volatile EnvVars cachedEnvironment;
private final WorkspaceList workspaceList = new WorkspaceList();
protected transient List<Action> transientActions;
protected final Object statusChangeLock = new Object();
/**
* Keeps track of stack traces to track the tremination requests for this computer.
*
* @since 1.607
* @see Executor#resetWorkUnit(String)
*/
private transient final List<TerminationRequest> terminatedBy = Collections.synchronizedList(new ArrayList
<TerminationRequest>());
/**
* This method captures the information of a request to terminate a computer instance. Method is public as
* it needs to be called from {@link AbstractCloudSlave} and {@link jenkins.model.Nodes}. In general you should
* not need to call this method directly, however if implementing a custom node type or a different path
* for removing nodes, it may make sense to call this method in order to capture the originating request.
*
* @since 1.607
*/
public void recordTermination() {
StaplerRequest request = Stapler.getCurrentRequest();
if (request != null) {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d] from HTTP request for %s",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId(),
request.getRequestURL()
)
));
} else {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d]",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId()
)
));
}
}
/**
* Returns the list of captured termination requests for this Computer. This method is used by {@link Executor}
* to provide details on why a Computer was removed in-between work being scheduled against the {@link Executor}
* and the {@link Executor} starting to execute the task.
*
* @return the (possibly empty) list of termination requests.
* @see Executor#resetWorkUnit(String)
* @since 1.607
*/
public List<TerminationRequest> getTerminatedBy() {
return new ArrayList<TerminationRequest>(terminatedBy);
}
public Computer(Node node) {
setNode(node);
}
/**
* Returns list of all boxes {@link ComputerPanelBox}s.
*/
public List<ComputerPanelBox> getComputerPanelBoxs(){
return ComputerPanelBox.all(this);
}
/**
* Returns the transient {@link Action}s associated with the computer.
*/
@SuppressWarnings("deprecation")
public List<Action> getActions() {
List<Action> result = new ArrayList<Action>();
result.addAll(super.getActions());
synchronized (this) {
if (transientActions == null) {
transientActions = TransientComputerActionFactory.createAllFor(this);
}
result.addAll(transientActions);
}
return Collections.unmodifiableList(result);
}
@SuppressWarnings("deprecation")
@Override
public void addAction(Action a) {
if(a==null) throw new IllegalArgumentException();
super.getActions().add(a);
}
/**
* This is where the log from the remote agent goes.
* The method also creates a log directory if required.
* @see #getLogDir(), #relocateOldLogs()
*/
public @Nonnull File getLogFile() {
return new File(getLogDir(),"slave.log");
}
/**
* Directory where rotated slave logs are stored.
*
* The method also creates a log directory if required.
*
* @since 1.613
*/
protected @Nonnull File getLogDir() {
File dir = new File(Jenkins.getInstance().getRootDir(),"logs/slaves/"+nodeName);
if (!dir.exists() && !dir.mkdirs()) {
LOGGER.severe("Failed to create slave log directory " + dir.getAbsolutePath());
}
return dir;
}
/**
* Gets the object that coordinates the workspace allocation on this computer.
*/
public WorkspaceList getWorkspaceList() {
return workspaceList;
}
/**
* Gets the string representation of the slave log.
*/
public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}
/**
* Used to URL-bind {@link AnnotatedLargeText}.
*/
public AnnotatedLargeText<Computer> getLogText() {
return new AnnotatedLargeText<Computer>(getLogFile(), Charset.defaultCharset(), false, this);
}
public ACL getACL() {
return Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
}
public void checkPermission(Permission permission) {
getACL().checkPermission(permission);
}
public boolean hasPermission(Permission permission) {
return getACL().hasPermission(permission);
}
/**
* If the computer was offline (either temporarily or not),
* this method will return the cause.
*
* @return
* null if the system was put offline without given a cause.
*/
@Exported
public OfflineCause getOfflineCause() {
return offlineCause;
}
/**
* If the computer was offline (either temporarily or not),
* this method will return the cause as a string (without user info).
*
* @return
* empty string if the system was put offline without given a cause.
*/
@Exported
public String getOfflineCauseReason() {
if (offlineCause == null) {
return "";
}
// fetch the localized string for "Disconnected By"
String gsub_base = hudson.slaves.Messages.SlaveComputer_DisconnectedBy("","");
// regex to remove commented reason base string
String gsub1 = "^" + gsub_base + "[\\w\\W]* \\: ";
// regex to remove non-commented reason base string
String gsub2 = "^" + gsub_base + "[\\w\\W]*";
String newString = offlineCause.toString().replaceAll(gsub1, "");
return newString.replaceAll(gsub2, "");
}
/**
* Gets the channel that can be used to run a program on this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract @Nullable VirtualChannel getChannel();
/**
* Gets the default charset of this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract Charset getDefaultCharset();
/**
* Gets the logs recorded by this slave.
*/
public abstract List<LogRecord> getLogRecords() throws IOException, InterruptedException;
/**
* If {@link #getChannel()}==null, attempts to relaunch the slave agent.
*/
public abstract void doLaunchSlaveAgent( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException;
/**
* @deprecated since 2009-01-06. Use {@link #connect(boolean)}
*/
@Deprecated
public final void launch() {
connect(true);
}
/**
* Do the same as {@link #doLaunchSlaveAgent(StaplerRequest, StaplerResponse)}
* but outside the context of serving a request.
*
* <p>
* If already connected or if this computer doesn't support proactive launching, no-op.
* This method may return immediately
* while the launch operation happens asynchronously.
*
* @see #disconnect()
*
* @param forceReconnect
* If true and a connect activity is already in progress, it will be cancelled and
* the new one will be started. If false, and a connect activity is already in progress, this method
* will do nothing and just return the pending connection operation.
* @return
* A {@link Future} representing pending completion of the task. The 'completion' includes
* both a successful completion and a non-successful completion (such distinction typically doesn't
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
public final Future<?> connect(boolean forceReconnect) {
connectTime = System.currentTimeMillis();
return _connect(forceReconnect);
}
/**
* Allows implementing-classes to provide an implementation for the connect method.
*
* <p>
* If already connected or if this computer doesn't support proactive launching, no-op.
* This method may return immediately
* while the launch operation happens asynchronously.
*
* @see #disconnect()
*
* @param forceReconnect
* If true and a connect activity is already in progress, it will be cancelled and
* the new one will be started. If false, and a connect activity is already in progress, this method
* will do nothing and just return the pending connection operation.
* @return
* A {@link Future} representing pending completion of the task. The 'completion' includes
* both a successful completion and a non-successful completion (such distinction typically doesn't
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
protected abstract Future<?> _connect(boolean forceReconnect);
/**
* CLI command to reconnect this node.
*/
@CLIMethod(name="connect-node")
public void cliConnect(@Option(name="-f",usage="Cancel any currently pending connect operation and retry from scratch") boolean force) throws ExecutionException, InterruptedException {
checkPermission(CONNECT);
connect(force).get();
}
/**
* Gets the time (since epoch) when this computer connected.
*
* @return The time in ms since epoch when this computer last connected.
*/
public final long getConnectTime() {
return connectTime;
}
/**
* Disconnect this computer.
*
* If this is the master, no-op. This method may return immediately
* while the launch operation happens asynchronously.
*
* @param cause
* Object that identifies the reason the node was disconnected.
*
* @return
* {@link Future} to track the asynchronous disconnect operation.
* @see #connect(boolean)
* @since 1.320
*/
public Future<?> disconnect(OfflineCause cause) {
recordTermination();
offlineCause = cause;
if (Util.isOverridden(Computer.class,getClass(),"disconnect"))
return disconnect(); // legacy subtypes that extend disconnect().
connectTime=0;
return Futures.precomputed(null);
}
/**
* Equivalent to {@code disconnect(null)}
*
* @deprecated as of 1.320.
* Use {@link #disconnect(OfflineCause)} and specify the cause.
*/
@Deprecated
public Future<?> disconnect() {
recordTermination();
if (Util.isOverridden(Computer.class,getClass(),"disconnect",OfflineCause.class))
// if the subtype already derives disconnect(OfflineCause), delegate to it
return disconnect(null);
connectTime=0;
return Futures.precomputed(null);
}
/**
* CLI command to disconnects this node.
*/
@CLIMethod(name="disconnect-node")
public void cliDisconnect(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
disconnect(new ByCLI(cause)).get();
}
/**
* CLI command to mark the node offline.
*/
@CLIMethod(name="offline-node")
public void cliOffline(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
setTemporarilyOffline(true, new ByCLI(cause));
}
@CLIMethod(name="online-node")
public void cliOnline() throws ExecutionException, InterruptedException {
checkPermission(CONNECT);
setTemporarilyOffline(false, null);
}
/**
* Number of {@link Executor}s that are configured for this computer.
*
* <p>
* When this value is decreased, it is temporarily possible
* for {@link #executors} to have a larger number than this.
*/
// ugly name to let EL access this
@Exported
public int getNumExecutors() {
return numExecutors;
}
/**
* Returns {@link Node#getNodeName() the name of the node}.
*/
public @Nonnull String getName() {
return nodeName != null ? nodeName : "";
}
/**
* True if this computer is a Unix machine (as opposed to Windows machine).
*
* @since 1.624
* @return
* null if the computer is disconnected and therefore we don't know whether it is Unix or not.
*/
public abstract @CheckForNull Boolean isUnix();
/**
* Returns the {@link Node} that this computer represents.
*
* @return
* null if the configuration has changed and the node is removed, yet the corresponding {@link Computer}
* is not yet gone.
*/
public @CheckForNull Node getNode() {
Jenkins j = Jenkins.getInstance();
if (j == null) {
return null;
}
if (nodeName == null) {
return j;
}
return j.getNode(nodeName);
}
@Exported
public LoadStatistics getLoadStatistics() {
return LabelAtom.get(nodeName != null ? nodeName : Jenkins.getInstance().getSelfLabel().toString()).loadStatistics;
}
public BuildTimelineWidget getTimeline() {
return new BuildTimelineWidget(getBuilds());
}
/**
* {@inheritDoc}
*/
public void taskAccepted(Executor executor, Queue.Task task) {
// dummy implementation
}
/**
* {@inheritDoc}
*/
public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
// dummy implementation
}
/**
* {@inheritDoc}
*/
public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) {
// dummy implementation
}
@Exported
public boolean isOffline() {
return temporarilyOffline || getChannel()==null;
}
public final boolean isOnline() {
return !isOffline();
}
/**
* This method is called to determine whether manual launching of the slave is allowed at this point in time.
* @return {@code true} if manual launching of the slave is allowed at this point in time.
*/
@Exported
public boolean isManualLaunchAllowed() {
return getRetentionStrategy().isManualLaunchAllowed(this);
}
/**
* Is a {@link #connect(boolean)} operation in progress?
*/
public abstract boolean isConnecting();
/**
* Returns true if this computer is supposed to be launched via JNLP.
* @deprecated since 2008-05-18.
* See {@linkplain #isLaunchSupported()} and {@linkplain ComputerLauncher}
*/
@Exported
@Deprecated
public boolean isJnlpAgent() {
return false;
}
/**
* Returns true if this computer can be launched by Hudson proactively and automatically.
*
* <p>
* For example, JNLP slaves return {@code false} from this, because the launch process
* needs to be initiated from the slave side.
*/
@Exported
public boolean isLaunchSupported() {
return true;
}
/**
* Returns true if this node is marked temporarily offline by the user.
*
* <p>
* In contrast, {@link #isOffline()} represents the actual online/offline
* state. For example, this method may return false while {@link #isOffline()}
* returns true if the slave agent failed to launch.
*
* @deprecated
* You should almost always want {@link #isOffline()}.
* This method is marked as deprecated to warn people when they
* accidentally call this method.
*/
@Exported
@Deprecated
public boolean isTemporarilyOffline() {
return temporarilyOffline;
}
/**
* @deprecated as of 1.320.
* Use {@link #setTemporarilyOffline(boolean, OfflineCause)}
*/
@Deprecated
public void setTemporarilyOffline(boolean temporarilyOffline) {
setTemporarilyOffline(temporarilyOffline,null);
}
/**
* Marks the computer as temporarily offline. This retains the underlying
* {@link Channel} connection, but prevent builds from executing.
*
* @param cause
* If the first argument is true, specify the reason why the node is being put
* offline.
*/
public void setTemporarilyOffline(boolean temporarilyOffline, OfflineCause cause) {
offlineCause = temporarilyOffline ? cause : null;
this.temporarilyOffline = temporarilyOffline;
Node node = getNode();
if (node != null) {
node.setTemporaryOfflineCause(offlineCause);
}
Jenkins.getInstance().getQueue().scheduleMaintenance();
synchronized (statusChangeLock) {
statusChangeLock.notifyAll();
}
for (ComputerListener cl : ComputerListener.all()) {
if (temporarilyOffline) cl.onTemporarilyOffline(this,cause);
else cl.onTemporarilyOnline(this);
}
}
@Exported
public String getIcon() {
if(isOffline())
return "computer-x.png";
else
return "computer.png";
}
@Exported
public String getIconClassName() {
if(isOffline())
return "icon-computer-x";
else
return "icon-computer";
}
public String getIconAltText() {
if(isOffline())
return "[offline]";
else
return "[online]";
}
@Exported
@Override public @Nonnull String getDisplayName() {
return nodeName;
}
public String getCaption() {
return Messages.Computer_Caption(nodeName);
}
public String getUrl() {
return "computer/" + Util.rawEncode(getName()) + "/";
}
/**
* Returns projects that are tied on this node.
*/
public List<AbstractProject> getTiedJobs() {
Node node = getNode();
return (node != null) ? node.getSelfLabel().getTiedJobs() : Collections.EMPTY_LIST;
}
public RunList getBuilds() {
return new RunList(Jenkins.getInstance().getAllItems(Job.class)).node(getNode());
}
/**
* Called to notify {@link Computer} that its corresponding {@link Node}
* configuration is updated.
*/
protected void setNode(Node node) {
assert node!=null;
if(node instanceof Slave)
this.nodeName = node.getNodeName();
else
this.nodeName = null;
setNumExecutors(node.getNumExecutors());
if (this.temporarilyOffline) {
// When we get a new node, push our current temp offline
// status to it (as the status is not carried across
// configuration changes that recreate the node).
// Since this is also called the very first time this
// Computer is created, avoid pushing an empty status
// as that could overwrite any status that the Node
// brought along from its persisted config data.
node.setTemporaryOfflineCause(this.offlineCause);
}
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* @see #onRemoved()
*/
protected void kill() {
// On most code paths, this should already be zero, and thus this next call becomes a no-op... and more
// importantly it will not acquire a lock on the Queue... not that the lock is bad, more that the lock
// may delay unnecessarily
setNumExecutors(0);
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* <p>
* Note that the Queue lock is already held when this method is called.
*
* @see #onRemoved()
*/
@Restricted(NoExternalUse.class)
@GuardedBy("hudson.model.Queue.lock")
/*package*/ void inflictMortalWound() {
setNumExecutors(0);
}
/**
* Called by {@link Jenkins} when this computer is removed.
*
* <p>
* This happens when list of nodes are updated (for example by {@link Jenkins#setNodes(List)} and
* the computer becomes redundant. Such {@link Computer}s get {@linkplain #kill() killed}, then
* after all its executors are finished, this method is called.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* @see #kill()
* @since 1.510
*/
protected void onRemoved(){
}
private synchronized void setNumExecutors(int n) {
this.numExecutors = n;
final int diff = executors.size()-n;
if (diff>0) {
// we have too many executors
// send signal to all idle executors to potentially kill them off
// need the Queue maintenance lock held to prevent concurrent job assignment on the idle executors
Queue.withLock(new Runnable() {
@Override
public void run() {
for( Executor e : executors )
if(e.isIdle())
e.interrupt();
}
});
}
if (diff<0) {
// if the number is increased, add new ones
addNewExecutorIfNecessary();
}
}
private void addNewExecutorIfNecessary() {
Set<Integer> availableNumbers = new HashSet<Integer>();
for (int i = 0; i < numExecutors; i++)
availableNumbers.add(i);
for (Executor executor : executors)
availableNumbers.remove(executor.getNumber());
for (Integer number : availableNumbers) {
/* There may be busy executors with higher index, so only
fill up until numExecutors is reached.
Extra executors will call removeExecutor(...) and that
will create any necessary executors from #0 again. */
if (executors.size() < numExecutors) {
Executor e = new Executor(this, number);
executors.add(e);
}
}
}
/**
* Returns the number of idle {@link Executor}s that can start working immediately.
*/
public int countIdle() {
int n = 0;
for (Executor e : executors) {
if(e.isIdle())
n++;
}
return n;
}
/**
* Returns the number of {@link Executor}s that are doing some work right now.
*/
public final int countBusy() {
return countExecutors()-countIdle();
}
/**
* Returns the current size of the executor pool for this computer.
* This number may temporarily differ from {@link #getNumExecutors()} if there
* are busy tasks when the configured size is decreased. OneOffExecutors are
* not included in this count.
*/
public final int countExecutors() {
return executors.size();
}
/**
* Gets the read-only snapshot view of all {@link Executor}s.
*/
@Exported
public List<Executor> getExecutors() {
return new ArrayList<Executor>(executors);
}
/**
* Gets the read-only snapshot view of all {@link OneOffExecutor}s.
*/
@Exported
public List<OneOffExecutor> getOneOffExecutors() {
return new ArrayList<OneOffExecutor>(oneOffExecutors);
}
/**
* Used to render the list of executors.
* @return a snapshot of the executor display information
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public List<DisplayExecutor> getDisplayExecutors() {
// The size may change while we are populating, but let's start with a reasonable guess to minimize resizing
List<DisplayExecutor> result = new ArrayList<DisplayExecutor>(executors.size()+oneOffExecutors.size());
int index = 0;
for (Executor e: executors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor(Integer.toString(index + 1), String.format("executors/%d", index), e));
}
index++;
}
index = 0;
for (OneOffExecutor e: oneOffExecutors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor("", String.format("oneOffExecutors/%d", index), e));
}
index++;
}
return result;
}
/**
* Returns true if all the executors of this computer are idle.
*/
@Exported
public final boolean isIdle() {
if (!oneOffExecutors.isEmpty())
return false;
for (Executor e : executors)
if(!e.isIdle())
return false;
return true;
}
/**
* Returns true if this computer has some idle executors that can take more workload.
*/
public final boolean isPartiallyIdle() {
for (Executor e : executors)
if(e.isIdle())
return true;
return false;
}
/**
* Returns the time when this computer last became idle.
*
* <p>
* If this computer is already idle, the return value will point to the
* time in the past since when this computer has been idle.
*
* <p>
* If this computer is busy, the return value will point to the
* time in the future where this computer will be expected to become free.
*/
public final long getIdleStartMilliseconds() {
long firstIdle = Long.MIN_VALUE;
for (Executor e : oneOffExecutors) {
firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
}
for (Executor e : executors) {
firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
}
return firstIdle;
}
/**
* Returns the time when this computer first became in demand.
*/
public final long getDemandStartMilliseconds() {
long firstDemand = Long.MAX_VALUE;
for (Queue.BuildableItem item : Jenkins.getInstance().getQueue().getBuildableItems(this)) {
firstDemand = Math.min(item.buildableStartMilliseconds, firstDemand);
}
return firstDemand;
}
/**
* Called by {@link Executor} to kill excessive executors from this computer.
*/
/*package*/ void removeExecutor(final Executor e) {
final Runnable task = new Runnable() {
@Override
public void run() {
synchronized (Computer.this) {
executors.remove(e);
addNewExecutorIfNecessary();
if (!isAlive()) {
AbstractCIBase ciBase = Jenkins.getInstance();
if (ciBase != null) {
ciBase.removeComputer(Computer.this);
}
}
}
}
};
if (!Queue.tryWithLock(task)) {
// JENKINS-28840 if we couldn't get the lock push the operation to a separate thread to avoid deadlocks
threadPoolForRemoting.submit(Queue.wrapWithLock(task));
}
}
/**
* Returns true if any of the executors are {@linkplain Executor#isActive active}.
*
* Note that if an executor dies, we'll leave it in {@link #executors} until
* the administrator yanks it out, so that we can see why it died.
*
* @since 1.509
*/
protected boolean isAlive() {
for (Executor e : executors)
if (e.isActive())
return true;
return false;
}
/**
* Interrupt all {@link Executor}s.
* Called from {@link Jenkins#cleanUp}.
*/
public void interrupt() {
Queue.withLock(new Runnable() {
@Override
public void run() {
for (Executor e : executors) {
e.interruptForShutdown();
}
}
});
}
public String getSearchUrl() {
return getUrl();
}
/**
* {@link RetentionStrategy} associated with this computer.
*
* @return
* never null. This method return {@code RetentionStrategy<? super T>} where
* {@code T=this.getClass()}.
*/
public abstract RetentionStrategy getRetentionStrategy();
/**
* Expose monitoring data for the remote API.
*/
@Exported(inline=true)
public Map<String/*monitor name*/,Object> getMonitorData() {
Map<String,Object> r = new HashMap<String, Object>();
for (NodeMonitor monitor : NodeMonitor.getAll())
r.put(monitor.getClass().getName(),monitor.data(this));
return r;
}
/**
* Gets the system properties of the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public Map<Object,Object> getSystemProperties() throws IOException, InterruptedException {
return RemotingDiagnostics.getSystemProperties(getChannel());
}
/**
* @deprecated as of 1.292
* Use {@link #getEnvironment()} instead.
*/
@Deprecated
public Map<String,String> getEnvVars() throws IOException, InterruptedException {
return getEnvironment();
}
/**
* Returns cached environment variables (copy to prevent modification) for the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public EnvVars getEnvironment() throws IOException, InterruptedException {
EnvVars cachedEnvironment = this.cachedEnvironment;
if (cachedEnvironment != null) {
return new EnvVars(cachedEnvironment);
}
cachedEnvironment = EnvVars.getRemote(getChannel());
this.cachedEnvironment = cachedEnvironment;
return new EnvVars(cachedEnvironment);
}
/**
* Creates an environment variable override to be used for launching processes on this node.
*
* @see ProcStarter#envs(Map)
* @since 1.489
*/
public @Nonnull EnvVars buildEnvironment(@Nonnull TaskListener listener) throws IOException, InterruptedException {
EnvVars env = new EnvVars();
Node node = getNode();
if (node==null) return env; // bail out
for (NodeProperty nodeProperty: Jenkins.getInstance().getGlobalNodeProperties()) {
nodeProperty.buildEnvVars(env,listener);
}
for (NodeProperty nodeProperty: node.getNodeProperties()) {
nodeProperty.buildEnvVars(env,listener);
}
// TODO: hmm, they don't really belong
String rootUrl = Jenkins.getInstance().getRootUrl();
if(rootUrl!=null) {
env.put("HUDSON_URL", rootUrl); // Legacy.
env.put("JENKINS_URL", rootUrl);
}
return env;
}
/**
* Gets the thread dump of the slave JVM.
* @return
* key is the thread name, and the value is the pre-formatted dump.
*/
public Map<String,String> getThreadDump() throws IOException, InterruptedException {
return RemotingDiagnostics.getThreadDump(getChannel());
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,getChannel());
}
/**
* This method tries to compute the name of the host that's reachable by all the other nodes.
*
* <p>
* Since it's possible that the slave is not reachable from the master (it may be behind a firewall,
* connecting to master via JNLP), this method may return null.
*
* It's surprisingly tricky for a machine to know a name that other systems can get to,
* especially between things like DNS search suffix, the hosts file, and YP.
*
* <p>
* So the technique here is to compute possible interfaces and names on the slave,
* then try to ping them from the master, and pick the one that worked.
*
* <p>
* The computation may take some time, so it employs caching to make the successive lookups faster.
*
* @since 1.300
* @return
* null if the host name cannot be computed (for example because this computer is offline,
* because the slave is behind the firewall, etc.)
*/
public String getHostName() throws IOException, InterruptedException {
if(hostNameCached)
// in the worst case we end up having multiple threads computing the host name simultaneously, but that's not harmful, just wasteful.
return cachedHostName;
VirtualChannel channel = getChannel();
if(channel==null) return null; // can't compute right now
for( String address : channel.call(new ListPossibleNames())) {
try {
InetAddress ia = InetAddress.getByName(address);
if(!(ia instanceof Inet4Address)) {
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address);
continue;
}
if(!ComputerPinger.checkIsReachable(ia, 3)) {
LOGGER.log(Level.FINE, "{0} didn't respond to ping", address);
continue;
}
cachedHostName = ia.getCanonicalHostName();
hostNameCached = true;
return cachedHostName;
} catch (IOException e) {
// if a given name fails to parse on this host, we get this error
LogRecord lr = new LogRecord(Level.FINE, "Failed to parse {0}");
lr.setThrown(e);
lr.setParameters(new Object[]{address});
LOGGER.log(lr);
}
}
// allow the administrator to manually specify the host name as a fallback. HUDSON-5373
cachedHostName = channel.call(new GetFallbackName());
hostNameCached = true;
return cachedHostName;
}
/**
* Starts executing a fly-weight task.
*/
/*package*/ final void startFlyWeightTask(WorkUnit p) {
OneOffExecutor e = new OneOffExecutor(this);
e.start(p);
oneOffExecutors.add(e);
}
/*package*/ final void remove(OneOffExecutor e) {
oneOffExecutors.remove(e);
}
private static class ListPossibleNames extends MasterToSlaveCallable<List<String>,IOException> {
/**
* In the normal case we would use {@link Computer} as the logger's name, however to
* do that we would have to send the {@link Computer} class over to the remote classloader
* and then it would need to be loaded, which pulls in {@link Jenkins} and loads that
* and then that fails to load as you are not supposed to do that. Another option
* would be to export the logger over remoting, with increased complexity as a result.
* Instead we just use a loger based on this class name and prevent any references to
* other classes from being transferred over remoting.
*/
private static final Logger LOGGER = Logger.getLogger(ListPossibleNames.class.getName());
public List<String> call() throws IOException {
List<String> names = new ArrayList<String>();
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
LOGGER.log(Level.FINE, "Listing up IP addresses for {0}", ni.getDisplayName());
Enumeration<InetAddress> e = ni.getInetAddresses();
while (e.hasMoreElements()) {
InetAddress ia = e.nextElement();
if(ia.isLoopbackAddress()) {
LOGGER.log(Level.FINE, "{0} is a loopback address", ia);
continue;
}
if(!(ia instanceof Inet4Address)) {
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", ia);
continue;
}
LOGGER.log(Level.FINE, "{0} is a viable candidate", ia);
names.add(ia.getHostAddress());
}
}
return names;
}
private static final long serialVersionUID = 1L;
}
private static class GetFallbackName extends MasterToSlaveCallable<String,IOException> {
public String call() throws IOException {
return System.getProperty("host.name");
}
private static final long serialVersionUID = 1L;
}
public static final ExecutorService threadPoolForRemoting = new ContextResettingExecutorService(
Executors.newCachedThreadPool(
new ExceptionCatchingThreadFactory(
new NamingThreadFactory(new DaemonThreadFactory(), "Computer.threadPoolForRemoting"))));
//
//
// UI
//
//
public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " all builds", getBuilds());
}
public void doRssFailed(StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " failed builds", getBuilds().failureOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName() + suffix, getUrl(),
runs.newBuilds(), Run.FEED_ADAPTER, req, rsp);
}
@RequirePOST
public HttpResponse doToggleOffline(@QueryParameter String offlineMessage) throws IOException, ServletException {
if(!temporarilyOffline) {
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(!temporarilyOffline,
new OfflineCause.UserCause(User.current(), offlineMessage));
} else {
checkPermission(CONNECT);
setTemporarilyOffline(!temporarilyOffline,null);
}
return HttpResponses.redirectToDot();
}
@RequirePOST
public HttpResponse doChangeOfflineCause(@QueryParameter String offlineMessage) throws IOException, ServletException {
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(true,
new OfflineCause.UserCause(User.current(), offlineMessage));
return HttpResponses.redirectToDot();
}
public Api getApi() {
return new Api(this);
}
/**
* Dumps the contents of the export table.
*/
public void doDumpExportTable( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
// this is a debug probe and may expose sensitive information
checkPermission(Jenkins.ADMINISTER);
rsp.setContentType("text/plain");
PrintWriter w = new PrintWriter(rsp.getCompressedWriter(req));
VirtualChannel vc = getChannel();
if (vc instanceof Channel) {
w.println("Master to slave");
((Channel)vc).dumpExportTable(w);
w.flush(); // flush here once so that even if the dump from the slave fails, the client gets some useful info
w.println("\n\n\nSlave to master");
w.print(vc.call(new DumpExportTableTask()));
} else {
w.println(Messages.Computer_BadChannel());
}
w.close();
}
private static final class DumpExportTableTask extends MasterToSlaveCallable<String,IOException> {
public String call() throws IOException {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Channel.current().dumpExportTable(pw);
pw.close();
return sw.toString();
}
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, "_script.jelly");
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, "_scriptText.jelly");
}
protected void _doScript(StaplerRequest req, StaplerResponse rsp, String view) throws IOException, ServletException {
Jenkins._doScript(req, rsp, req.getView(this, view), getChannel(), getACL());
}
/**
* Accepts the update to the node configuration.
*/
@RequirePOST
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(CONFIGURE);
String name = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name"));
Jenkins.checkGoodName(name);
Node node = getNode();
if (node == null) {
throw new ServletException("No such node " + nodeName);
}
Node result = node.reconfigure(req, req.getSubmittedForm());
replaceBy(result);
// take the user back to the slave top page.
rsp.sendRedirect2("../" + result.getNodeName() + '/');
}
/**
* Accepts <tt>config.xml</tt> submission, as well as serve it.
*/
@WebMethod(name = "config.xml")
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
if (req.getMethod().equals("GET")) {
// read
checkPermission(EXTENDED_READ);
rsp.setContentType("application/xml");
Node node = getNode();
if (node == null) {
throw HttpResponses.notFound();
}
Jenkins.XSTREAM2.toXMLUTF8(node, rsp.getOutputStream());
return;
}
if (req.getMethod().equals("POST")) {
// submission
updateByXml(req.getInputStream());
return;
}
// huh?
rsp.sendError(SC_BAD_REQUEST);
}
/**
* Replaces the current {@link Node} by another one.
*/
private void replaceBy(final Node newNode) throws ServletException, IOException {
final Jenkins app = Jenkins.getInstance();
// use the queue lock until Nodes has a way of directly modifying a single node.
Queue.withLock(new NotReallyRoleSensitiveCallable<Void, IOException>() {
public Void call() throws IOException {
List<Node> nodes = new ArrayList<Node>(app.getNodes());
Node node = getNode();
int i = (node != null) ? nodes.indexOf(node) : -1;
if(i<0) {
throw new IOException("This slave appears to be removed while you were editing the configuration");
}
nodes.set(i, newNode);
app.setNodes(nodes);
return null;
}
});
}
/**
* Updates Job by its XML definition.
*
* @since 1.526
*/
public void updateByXml(final InputStream source) throws IOException, ServletException {
checkPermission(CONFIGURE);
Node result = (Node)Jenkins.XSTREAM2.fromXML(source);
replaceBy(result);
}
/**
* Really deletes the slave.
*/
@RequirePOST
public HttpResponse doDoDelete() throws IOException {
checkPermission(DELETE);
Node node = getNode();
if (node != null) {
Jenkins.getInstance().removeNode(node);
} else {
AbstractCIBase app = Jenkins.getInstance();
app.removeComputer(this);
}
return new HttpRedirect("..");
}
/**
* Blocks until the node becomes online/offline.
*/
@CLIMethod(name="wait-node-online")
public void waitUntilOnline() throws InterruptedException {
synchronized (statusChangeLock) {
while (!isOnline())
statusChangeLock.wait(1000);
}
}
@CLIMethod(name="wait-node-offline")
public void waitUntilOffline() throws InterruptedException {
synchronized (statusChangeLock) {
while (!isOffline())
statusChangeLock.wait(1000);
}
}
/**
* Handles incremental log.
*/
public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
getLogText().doProgressText(req, rsp);
}
/**
* Gets the current {@link Computer} that the build is running.
* This method only works when called during a build, such as by
* {@link hudson.tasks.Publisher}, {@link hudson.tasks.BuildWrapper}, etc.
* @return the {@link Computer} associated with {@link Executor#currentExecutor}, or (consistently as of 1.591) null if not on an executor thread
*/
public static @Nullable Computer currentComputer() {
Executor e = Executor.currentExecutor();
return e != null ? e.getOwner() : null;
}
/**
* Returns {@code true} if the computer is accepting tasks. Needed to allow slaves programmatic suspension of task
* scheduling that does not overlap with being offline.
*
* @return {@code true} if the computer is accepting tasks
* @see hudson.slaves.RetentionStrategy#isAcceptingTasks(Computer)
* @see hudson.model.Node#isAcceptingTasks()
*/
@OverrideMustInvoke(When.ANYTIME)
public boolean isAcceptingTasks() {
final Node node = getNode();
return getRetentionStrategy().isAcceptingTasks(this) && (node == null || node.isAcceptingTasks());
}
/**
* Used for CLI binding.
*/
@CLIResolver
public static Computer resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Slave name, or empty string for master") String name) throws CmdLineException {
Jenkins h = Jenkins.getInstance();
Computer item = h.getComputer(name);
if (item==null) {
List<String> names = new ArrayList<String>();
for (Computer c : h.getComputers())
if (c.getName().length()>0)
names.add(c.getName());
throw new CmdLineException(null,Messages.Computer_NoSuchSlaveExists(name,EditDistance.findNearest(name,names)));
}
return item;
}
/**
* Relocate log files in the old location to the new location.
*
* Files were used to be $JENKINS_ROOT/slave-NAME.log (and .1, .2, ...)
* but now they are at $JENKINS_ROOT/logs/slaves/NAME/slave.log (and .1, .2, ...)
*
* @see #getLogFile()
*/
@Initializer
public static void relocateOldLogs() {
relocateOldLogs(Jenkins.getInstance().getRootDir());
}
/*package*/ static void relocateOldLogs(File dir) {
final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?");
File[] logfiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return logfile.matcher(name).matches();
}
});
if (logfiles==null) return;
for (File f : logfiles) {
Matcher m = logfile.matcher(f.getName());
if (m.matches()) {
File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2)));
newLocation.getParentFile().mkdirs();
boolean relocationSuccessfull=f.renameTo(newLocation);
if (relocationSuccessfull) { // The operation will fail if mkdir fails
LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
} else {
LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
}
} else {
assert false;
}
}
}
/**
* A value class to provide a consistent snapshot view of the state of an executor to avoid race conditions
* during rendering of the executors list.
*
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public static class DisplayExecutor implements ModelObject {
@Nonnull
private final String displayName;
@Nonnull
private final String url;
@Nonnull
private final Executor executor;
public DisplayExecutor(@Nonnull String displayName, @Nonnull String url, @Nonnull Executor executor) {
this.displayName = displayName;
this.url = url;
this.executor = executor;
}
@Override
@Nonnull
public String getDisplayName() {
return displayName;
}
@Nonnull
public String getUrl() {
return url;
}
@Nonnull
public Executor getExecutor() {
return executor;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DisplayExecutor{");
sb.append("displayName='").append(displayName).append('\'');
sb.append(", url='").append(url).append('\'');
sb.append(", executor=").append(executor);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DisplayExecutor that = (DisplayExecutor) o;
if (!executor.equals(that.executor)) {
return false;
}
return true;
}
@Extension(ordinal = Double.MAX_VALUE)
@Restricted(DoNotUse.class)
public static class InternalComputerListener extends ComputerListener {
@Override
public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
c.cachedEnvironment = null;
}
}
@Override
public int hashCode() {
return executor.hashCode();
}
}
/**
* Used to trace requests to terminate a computer.
*
* @since 1.607
*/
public static class TerminationRequest extends RuntimeException {
private final long when;
public TerminationRequest(String message) {
super(message);
this.when = System.currentTimeMillis();
}
/**
* Returns the when the termination request was created.
*
* @return the difference, measured in milliseconds, between
* the time of the termination request and midnight, January 1, 1970 UTC.
*/
public long getWhen() {
return when;
}
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Computer.class,Messages._Computer_Permissions_Title());
public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._Computer_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.COMPUTER);
/**
* @since 1.532
*/
public static final Permission EXTENDED_READ = new Permission(PERMISSIONS,"ExtendedRead", Messages._Computer_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.COMPUTER});
public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._Computer_DeletePermission_Description(), Permission.DELETE, PermissionScope.COMPUTER);
public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._Computer_CreatePermission_Description(), Permission.CREATE, PermissionScope.COMPUTER);
public static final Permission DISCONNECT = new Permission(PERMISSIONS,"Disconnect", Messages._Computer_DisconnectPermission_Description(), Jenkins.ADMINISTER, PermissionScope.COMPUTER);
public static final Permission CONNECT = new Permission(PERMISSIONS,"Connect", Messages._Computer_ConnectPermission_Description(), DISCONNECT, PermissionScope.COMPUTER);
public static final Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._Computer_BuildPermission_Description(), Permission.WRITE, PermissionScope.COMPUTER);
private static final Logger LOGGER = Logger.getLogger(Computer.class.getName());
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_3048_0
|
crossvul-java_data_good_5809_2
|
package org.jboss.seam.remoting;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jboss.seam.log.LogProvider;
import org.jboss.seam.log.Logging;
import org.jboss.seam.remoting.messaging.PollError;
import org.jboss.seam.remoting.messaging.PollRequest;
import org.jboss.seam.remoting.wrapper.Wrapper;
import org.jboss.seam.servlet.ContextualHttpServletRequest;
import org.jboss.seam.util.XML;
/**
* Handles JMS Message poll requests.
*
* @author Shane Bryzak
*/
public class PollHandler extends BaseRequestHandler implements RequestHandler
{
private static final LogProvider log = Logging.getLogProvider(SubscriptionHandler.class);
private static final byte[] ERRORS_TAG_OPEN_START = "<errors token=\"".getBytes();
private static final byte[] ERRORS_TAG_OPEN_END = "\">".getBytes();
private static final byte[] ERROR_TAG_OPEN_START = "<error code=\"".getBytes();
private static final byte[] ERROR_TAG_OPEN_END = "\">".getBytes();
private static final byte[] ERROR_TAG_CLOSE = "</error>".getBytes();
private static final byte[] MESSAGES_TAG_OPEN_START = "<messages token=\"".getBytes();
private static final byte[] MESSAGES_TAG_OPEN_END = "\">".getBytes();
private static final byte[] MESSAGES_TAG_CLOSE = "</messages>".getBytes();
private static final byte[] MESSAGE_TAG_OPEN_START = "<message type=\"".getBytes();
private static final byte[] MESSAGE_TAG_OPEN_END = "\">".getBytes();
private static final byte[] MESSAGE_TAG_CLOSE = "</message>".getBytes();
private static final byte[] VALUE_TAG_OPEN = "<value>".getBytes();
private static final byte[] VALUE_TAG_CLOSE = "</value>".getBytes();
public void handle(HttpServletRequest request, final HttpServletResponse response)
throws Exception
{
// We're sending an XML response, so set the response content type to text/xml
response.setContentType("text/xml");
// Parse the incoming request as XML
SAXReader xmlReader = XML.getSafeSaxReader();
Document doc = xmlReader.read(request.getInputStream());
Element env = doc.getRootElement();
final List<PollRequest> polls = unmarshalRequests(env);
new ContextualHttpServletRequest(request)
{
@Override
public void process() throws Exception
{
for (PollRequest req : polls)
{
req.poll();
}
// Package up the response
marshalResponse(polls, response.getOutputStream());
}
}.run();
}
private List<PollRequest> unmarshalRequests(Element env)
throws Exception
{
try
{
List<PollRequest> requests = new ArrayList<PollRequest>();
List<Element> requestElements = env.element("body").elements("poll");
for (Element e : requestElements)
{
requests.add(new PollRequest(e.attributeValue("token"),
Integer.parseInt(e.attributeValue("timeout"))));
}
return requests;
}
catch (Exception ex)
{
log.error("Error unmarshalling subscriptions from request", ex);
throw ex;
}
}
private void marshalResponse(List<PollRequest> reqs, OutputStream out)
throws IOException
{
out.write(ENVELOPE_TAG_OPEN);
out.write(BODY_TAG_OPEN);
for (PollRequest req : reqs)
{
if (req.getErrors() != null && req.getErrors().size() > 0)
{
out.write(ERRORS_TAG_OPEN_START);
out.write(req.getToken().getBytes());
out.write(ERRORS_TAG_OPEN_END);
for (PollError err : req.getErrors())
{
writeError(err, out);
}
}
else if (req.getMessages() != null && req.getMessages().size() > 0)
{
out.write(MESSAGES_TAG_OPEN_START);
out.write(req.getToken().getBytes());
out.write(MESSAGES_TAG_OPEN_END);
for (Message m : req.getMessages()) {
try {
writeMessage(m, out);
}
catch (JMSException ex) {
}
catch (IOException ex) {
}
}
out.write(MESSAGES_TAG_CLOSE);
}
}
out.write(BODY_TAG_CLOSE);
out.write(ENVELOPE_TAG_CLOSE);
out.flush();
}
private void writeMessage(Message m, OutputStream out)
throws IOException, JMSException
{
out.write(MESSAGE_TAG_OPEN_START);
// We need one of these to maintain a list of outbound references
CallContext ctx = new CallContext();
Object value = null;
if (m instanceof TextMessage)
{
out.write("text".getBytes());
value = ((TextMessage) m).getText();
}
else if (m instanceof ObjectMessage)
{
out.write("object".getBytes());
value = ((ObjectMessage) m).getObject();
}
out.write(MESSAGE_TAG_OPEN_END);
out.write(VALUE_TAG_OPEN);
ctx.createWrapperFromObject(value, "").marshal(out);
out.write(VALUE_TAG_CLOSE);
out.write(REFS_TAG_OPEN);
// Using a for-loop, because stuff can get added to outRefs as we recurse the object graph
for (int i = 0; i < ctx.getOutRefs().size(); i++)
{
Wrapper wrapper = ctx.getOutRefs().get(i);
out.write(REF_TAG_OPEN_START);
out.write(Integer.toString(i).getBytes());
out.write(REF_TAG_OPEN_END);
wrapper.serialize(out);
out.write(REF_TAG_CLOSE);
}
out.write(REFS_TAG_CLOSE);
out.write(MESSAGE_TAG_CLOSE);
}
private void writeError(PollError error, OutputStream out)
throws IOException
{
out.write(ERROR_TAG_OPEN_START);
out.write(error.getCode().getBytes());
out.write(ERROR_TAG_OPEN_END);
out.write(error.getMessage().getBytes());
out.write(ERROR_TAG_CLOSE);
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/good_5809_2
|
crossvul-java_data_bad_4347_5
|
/*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* Aspecto encargado de trazar la información de los servicios implementados.
*/
@Configuration
@ConditionalOnProperty(name = "application.log.enabled", havingValue = "true", matchIfMissing = true)
public class MethodLoggerAspectConfiguration {
private static final Logger log = LoggerFactory.getLogger("org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable");
@Aspect
@Component
public class MethodLoggerAspect {
@Before("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..business.impl..*(..))")
public void logBefore(JoinPoint joinPoint) {
if (log.isDebugEnabled()) {
log.debug(" ************************* INIT SERVICE ******************************");
log.debug(" Service : Entering in Method : {}", joinPoint.getSignature().getDeclaringTypeName());
log.debug(" Service : Method : {}", joinPoint.getSignature().getName());
log.debug(" Service : Arguments : {}", Arrays.toString(joinPoint.getArgs()));
log.debug(" Service : Target class : {}", joinPoint.getTarget().getClass().getName());
}
}
@AfterThrowing(pointcut = "execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..business.impl..*(..))", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
log.error(" Service : An exception has been thrown in {} ()", joinPoint.getSignature().getName());
log.error(" Service : Cause : {}", exception.getCause());
log.error(" Service : Message : {}", exception.getMessage());
log.debug(" ************************** END SERVICE ******************************");
}
@Around("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable * *..business.impl..*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
try {
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - start;
log.debug(" Service : {}.{} () execution time: {} ms", className, methodName, elapsedTime);
log.debug(" ************************** END SERVICE ******************************");
return result;
} catch (IllegalArgumentException e) {
log.error(" Service : Illegal argument {} in {}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getName(), e);
log.debug(" ************************** END SERVICE ******************************");
throw e;
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_4347_5
|
crossvul-java_data_bad_4348_4
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_4348_4
|
crossvul-java_data_bad_5809_1
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_5809_1
|
crossvul-java_data_bad_4348_5
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-200/java/bad_4348_5
|
crossvul-java_data_good_2300_0
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.logging;
import static org.jboss.weld.logging.WeldLogger.WELD_PROJECT_CODE;
import org.jboss.logging.Logger;
import org.jboss.logging.Logger.Level;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.Message.Format;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.weld.exceptions.IllegalStateException;
import org.jboss.weld.servlet.ServletContextService;
/**
* Error messages relating to Servlet integration
*
* Message ids: 000700 - 000799
*/
@MessageLogger(projectCode = WELD_PROJECT_CODE)
public interface ServletLogger extends WeldLogger {
ServletLogger LOG = Logger.getMessageLogger(ServletLogger.class, Category.SERVLET.getName());
@Message(id = 707, value = "Non Http-Servlet lifecycle not defined")
IllegalStateException onlyHttpServletLifecycleDefined();
@LogMessage(level = Level.TRACE)
@Message(id = 708, value = "Initializing request {0}", format = Format.MESSAGE_FORMAT)
void requestInitialized(Object param1);
@LogMessage(level = Level.TRACE)
@Message(id = 709, value = "Destroying request {0}", format = Format.MESSAGE_FORMAT)
void requestDestroyed(Object param1);
@Message(id = 710, value = "Cannot inject {0} outside of a Servlet request", format = Format.MESSAGE_FORMAT)
IllegalStateException cannotInjectObjectOutsideOfServletRequest(Object param1, @Cause Throwable cause);
@LogMessage(level = Level.WARN)
@Message(id = 711, value = "Context activation pattern {0} ignored as it is overriden by the integrator.", format = Format.MESSAGE_FORMAT)
void webXmlMappingPatternIgnored(String pattern);
@LogMessage(level = Level.WARN)
@Message(id = 712, value = "Unable to dissociate context {0} from the storage {1}", format = Format.MESSAGE_FORMAT)
void unableToDissociateContext(Object context, Object storage);
@Message(id = 713, value = "Unable to inject ServletContext. None is associated with {0}, {1}", format = Format.MESSAGE_FORMAT)
IllegalStateException cannotInjectServletContext(ClassLoader classLoader, ServletContextService service);
@LogMessage(level = Level.WARN)
@Message(id = 714, value = "HttpContextLifecycle guard leak detected. The Servlet container is not fully compliant. The value was {0}", format = Format.MESSAGE_FORMAT)
void guardLeak(int value);
@LogMessage(level = Level.WARN)
@Message(id = 715, value = "HttpContextLifecycle guard not set. The Servlet container is not fully compliant.", format = Format.MESSAGE_FORMAT)
void guardNotSet();
@LogMessage(level = Level.INFO)
@Message(id = 716, value = "Running in Servlet 2.x environment. Asynchronous request support is disabled.")
void servlet2Environment();
@LogMessage(level = Level.WARN)
@Message(id = 717, value = "Unable to deactivate context {0} when destroying request {1}", format = Format.MESSAGE_FORMAT)
void unableToDeactivateContext(Object context, Object request);
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_2300_0
|
crossvul-java_data_bad_2300_2
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jboss.weld.Container;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.context.cache.RequestScopedCache;
import org.jboss.weld.context.http.HttpRequestContext;
import org.jboss.weld.context.http.HttpRequestContextImpl;
import org.jboss.weld.context.http.HttpSessionContext;
import org.jboss.weld.context.http.HttpSessionDestructionContext;
import org.jboss.weld.event.FastEvent;
import org.jboss.weld.literal.DestroyedLiteral;
import org.jboss.weld.literal.InitializedLiteral;
import org.jboss.weld.logging.ServletLogger;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.servlet.spi.HttpContextActivationFilter;
import org.jboss.weld.util.reflection.Reflections;
/**
* Takes care of setting up and tearing down CDI contexts around an HTTP request and dispatching context lifecycle events.
*
* @author Jozef Hartinger
* @author Marko Luksa
*
*/
public class HttpContextLifecycle implements Service {
private static final String HTTP_SESSION = "org.jboss.weld." + HttpSession.class.getName();
private static final String INCLUDE_HEADER = "javax.servlet.include.request_uri";
private static final String FORWARD_HEADER = "javax.servlet.forward.request_uri";
private static final String REQUEST_DESTROYED = HttpContextLifecycle.class.getName() + ".request.destroyed";
private static final String GUARD_PARAMETER_NAME = "org.jboss.weld.context.ignore.guard.marker";
private static final Object GUARD_PARAMETER_VALUE = new Object();
private HttpSessionDestructionContext sessionDestructionContextCache;
private HttpSessionContext sessionContextCache;
private HttpRequestContext requestContextCache;
private volatile Boolean conversationActivationEnabled;
private final boolean ignoreForwards;
private final boolean ignoreIncludes;
private final BeanManagerImpl beanManager;
private final ConversationContextActivator conversationContextActivator;
private final HttpContextActivationFilter contextActivationFilter;
private final FastEvent<ServletContext> applicationInitializedEvent;
private final FastEvent<ServletContext> applicationDestroyedEvent;
private final FastEvent<HttpServletRequest> requestInitializedEvent;
private final FastEvent<HttpServletRequest> requestDestroyedEvent;
private final FastEvent<HttpSession> sessionInitializedEvent;
private final FastEvent<HttpSession> sessionDestroyedEvent;
private final ServletApiAbstraction servletApi;
private final ServletContextService servletContextService;
private final Container container;
private static final ThreadLocal<Counter> nestedInvocationGuard = new ThreadLocal<HttpContextLifecycle.Counter>();
private final boolean nestedInvocationGuardEnabled;
private static class Counter {
private int value = 1;
}
public HttpContextLifecycle(BeanManagerImpl beanManager, HttpContextActivationFilter contextActivationFilter, boolean ignoreForwards, boolean ignoreIncludes, boolean lazyConversationContext, boolean nestedInvocationGuardEnabled) {
this.beanManager = beanManager;
this.conversationContextActivator = new ConversationContextActivator(beanManager, lazyConversationContext);
this.conversationActivationEnabled = null;
this.ignoreForwards = ignoreForwards;
this.ignoreIncludes = ignoreIncludes;
this.contextActivationFilter = contextActivationFilter;
this.applicationInitializedEvent = FastEvent.of(ServletContext.class, beanManager, InitializedLiteral.APPLICATION);
this.applicationDestroyedEvent = FastEvent.of(ServletContext.class, beanManager, DestroyedLiteral.APPLICATION);
this.requestInitializedEvent = FastEvent.of(HttpServletRequest.class, beanManager, InitializedLiteral.REQUEST);
this.requestDestroyedEvent = FastEvent.of(HttpServletRequest.class, beanManager, DestroyedLiteral.REQUEST);
this.sessionInitializedEvent = FastEvent.of(HttpSession.class, beanManager, InitializedLiteral.SESSION);
this.sessionDestroyedEvent = FastEvent.of(HttpSession.class, beanManager, DestroyedLiteral.SESSION);
this.servletApi = beanManager.getServices().get(ServletApiAbstraction.class);
this.servletContextService = beanManager.getServices().get(ServletContextService.class);
this.nestedInvocationGuardEnabled = nestedInvocationGuardEnabled;
this.container = Container.instance(beanManager);
}
private HttpSessionDestructionContext getSessionDestructionContext() {
if (sessionDestructionContextCache == null) {
this.sessionDestructionContextCache = beanManager.instance().select(HttpSessionDestructionContext.class).get();
}
return sessionDestructionContextCache;
}
private HttpSessionContext getSessionContext() {
if (sessionContextCache == null) {
this.sessionContextCache = beanManager.instance().select(HttpSessionContext.class).get();
}
return sessionContextCache;
}
public HttpRequestContext getRequestContext() {
if (requestContextCache == null) {
this.requestContextCache = beanManager.instance().select(HttpRequestContext.class).get();
}
return requestContextCache;
}
public void contextInitialized(ServletContext ctx) {
servletContextService.contextInitialized(ctx);
synchronized (container) {
applicationInitializedEvent.fire(ctx);
}
}
public void contextDestroyed(ServletContext ctx) {
synchronized (container) {
applicationDestroyedEvent.fire(ctx);
}
}
public void sessionCreated(HttpSession session) {
SessionHolder.sessionCreated(session);
conversationContextActivator.sessionCreated(session);
sessionInitializedEvent.fire(session);
}
public void sessionDestroyed(HttpSession session) {
// Mark the session context and conversation contexts to destroy
// instances when appropriate
deactivateSessionDestructionContext(session);
boolean destroyed = getSessionContext().destroy(session);
SessionHolder.clear();
RequestScopedCache.endRequest();
if (destroyed) {
// we are outside of a request (the session timed out) and therefore the session was destroyed immediately
// we can fire the @Destroyed(SessionScoped.class) event immediately
sessionDestroyedEvent.fire(session);
} else {
// the old session won't be available at the time we destroy this request
// let's store its reference until then
if (getRequestContext() instanceof HttpRequestContextImpl) {
HttpServletRequest request = Reflections.<HttpRequestContextImpl> cast(getRequestContext()).getHttpServletRequest();
request.setAttribute(HTTP_SESSION, session);
}
}
}
private void deactivateSessionDestructionContext(HttpSession session) {
HttpSessionDestructionContext context = getSessionDestructionContext();
if (context.isActive()) {
context.deactivate();
context.dissociate(session);
}
}
public void requestInitialized(HttpServletRequest request, ServletContext ctx) {
if (nestedInvocationGuardEnabled) {
Counter counter = nestedInvocationGuard.get();
Object marker = request.getAttribute(GUARD_PARAMETER_NAME);
if (counter != null && marker != null) {
// this is a nested invocation, increment the counter and ignore this invocation
counter.value++;
return;
} else {
if (counter != null && marker == null) {
/*
* This request has not been processed yet but the guard is set already.
* That indicates, that the guard leaked from a previous request processing - most likely
* the Servlet container did not invoke listener methods symmetrically.
* Log a warning and recover by re-initializing the guard
*/
ServletLogger.LOG.guardLeak(counter.value);
}
// this is the initial (outer) invocation
nestedInvocationGuard.set(new Counter());
request.setAttribute(GUARD_PARAMETER_NAME, GUARD_PARAMETER_VALUE);
}
}
if (ignoreForwards && isForwardedRequest(request)) {
return;
}
if (ignoreIncludes && isIncludedRequest(request)) {
return;
}
if (!contextActivationFilter.accepts(request)) {
return;
}
ServletLogger.LOG.requestInitialized(request);
SessionHolder.requestInitialized(request);
getRequestContext().associate(request);
getSessionContext().associate(request);
if (conversationActivationEnabled) {
conversationContextActivator.associateConversationContext(request);
}
getRequestContext().activate();
getSessionContext().activate();
try {
if (conversationActivationEnabled) {
conversationContextActivator.activateConversationContext(request);
}
requestInitializedEvent.fire(request);
} catch (RuntimeException e) {
try {
requestDestroyed(request);
} catch (Exception ignored) {
// ignored in order to let the original exception be thrown
}
/*
* If the servlet container happens to call the destroyed callback again, ignore it.
*/
request.setAttribute(REQUEST_DESTROYED, Boolean.TRUE);
throw e;
}
}
public void requestDestroyed(HttpServletRequest request) {
if (isRequestDestroyed(request)) {
return;
}
if (nestedInvocationGuardEnabled) {
Counter counter = nestedInvocationGuard.get();
if (counter != null) {
counter.value--;
if (counter.value > 0) {
return; // this is a nested invocation, ignore it
} else {
nestedInvocationGuard.remove(); // this is the outer invocation
request.removeAttribute(GUARD_PARAMETER_NAME);
}
} else {
ServletLogger.LOG.guardNotSet();
return;
}
}
if (ignoreForwards && isForwardedRequest(request)) {
return;
}
if (ignoreIncludes && isIncludedRequest(request)) {
return;
}
if (!contextActivationFilter.accepts(request)) {
return;
}
ServletLogger.LOG.requestDestroyed(request);
try {
conversationContextActivator.deactivateConversationContext(request);
/*
* if this request has been switched to async then do not invalidate the context now
* as it will be invalidated at the end of the async operation.
*/
if (!servletApi.isAsyncSupported() || !servletApi.isAsyncStarted(request)) {
getRequestContext().invalidate();
}
getRequestContext().deactivate();
// fire @Destroyed(RequestScoped.class)
requestDestroyedEvent.fire(request);
getSessionContext().deactivate();
// fire @Destroyed(SessionScoped.class)
if (!getSessionContext().isValid()) {
sessionDestroyedEvent.fire((HttpSession) request.getAttribute(HTTP_SESSION));
}
} finally {
getRequestContext().dissociate(request);
// WFLY-1533 Underlying HTTP session may be invalid
try {
getSessionContext().dissociate(request);
} catch (Exception e) {
ServletLogger.LOG.unableToDissociateContext(getSessionContext(), request);
ServletLogger.LOG.catchingDebug(e);
}
// Catch block is inside the activator method so that we're able to log the context
conversationContextActivator.disassociateConversationContext(request);
SessionHolder.clear();
}
}
public boolean isConversationActivationSet() {
return conversationActivationEnabled != null;
}
public void setConversationActivationEnabled(boolean conversationActivationEnabled) {
this.conversationActivationEnabled = conversationActivationEnabled;
}
/**
* Some Servlet containers fire HttpServletListeners for include requests (inner requests caused by calling the include method of RequestDispatcher). This
* causes problems with context shut down as context manipulation is not reentrant. This method detects if this request is an included request or not.
*/
private boolean isIncludedRequest(HttpServletRequest request) {
return request.getAttribute(INCLUDE_HEADER) != null;
}
/**
* Some Servlet containers fire HttpServletListeners for forward requests (inner requests caused by calling the forward method of RequestDispatcher). This
* causes problems with context shut down as context manipulation is not reentrant. This method detects if this request is an forwarded request or not.
*/
private boolean isForwardedRequest(HttpServletRequest request) {
return request.getAttribute(FORWARD_HEADER) != null;
}
/**
* The way servlet containers react to an exception that occurs in a {@link ServletRequestListener} differs among servlet listeners. In certain containers
* the destroyed callback may be invoked multiple times, causing the latter invocations to fail as thread locals have already been unset. We use the
* {@link #REQUEST_DESTROYED} flag to indicate that all further invocations of the
* {@link ServletRequestListener#requestDestroyed(javax.servlet.ServletRequestEvent)} should be ignored by Weld.
*/
private boolean isRequestDestroyed(HttpServletRequest request) {
return request.getAttribute(REQUEST_DESTROYED) != null;
}
@Override
public void cleanup() {
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_2300_2
|
crossvul-java_data_good_4768_0
|
/**
*
* Copyright 2009 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.ConnectionException;
import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;
import org.jivesoftware.smack.SmackException.SecurityRequiredException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.compress.packet.Compress;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.debugger.SmackDebugger;
import org.jivesoftware.smack.filter.IQReplyFilter;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.filter.StanzaIdFilter;
import org.jivesoftware.smack.iqrequest.IQRequestHandler;
import org.jivesoftware.smack.packet.Bind;
import org.jivesoftware.smack.packet.ErrorIQ;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Mechanisms;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Session;
import org.jivesoftware.smack.packet.StartTls;
import org.jivesoftware.smack.packet.PlainStreamElement;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
import org.jivesoftware.smack.parsing.UnparsablePacket;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.BoundedThreadPoolExecutor;
import org.jivesoftware.smack.util.DNSUtil;
import org.jivesoftware.smack.util.Objects;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.util.ParserUtils;
import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jxmpp.util.XmppStringUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
public abstract class AbstractXMPPConnection implements XMPPConnection {
private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName());
/**
* Counter to uniquely identify connections that are created.
*/
private final static AtomicInteger connectionCounter = new AtomicInteger(0);
static {
// Ensure the SmackConfiguration class is loaded by calling a method in it.
SmackConfiguration.getVersion();
}
/**
* Get the collection of listeners that are interested in connection creation events.
*
* @return a collection of listeners interested on new connections.
*/
protected static Collection<ConnectionCreationListener> getConnectionCreationListeners() {
return XMPPConnectionRegistry.getConnectionCreationListeners();
}
/**
* A collection of ConnectionListeners which listen for connection closing
* and reconnection events.
*/
protected final Set<ConnectionListener> connectionListeners =
new CopyOnWriteArraySet<ConnectionListener>();
/**
* A collection of PacketCollectors which collects packets for a specified filter
* and perform blocking and polling operations on the result queue.
* <p>
* We use a ConcurrentLinkedQueue here, because its Iterator is weakly
* consistent and we want {@link #invokePacketCollectors(Stanza)} for-each
* loop to be lock free. As drawback, removing a PacketCollector is O(n).
* The alternative would be a synchronized HashSet, but this would mean a
* synchronized block around every usage of <code>collectors</code>.
* </p>
*/
private final Collection<PacketCollector> collectors = new ConcurrentLinkedQueue<PacketCollector>();
/**
* List of PacketListeners that will be notified synchronously when a new stanza(/packet) was received.
*/
private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>();
/**
* List of PacketListeners that will be notified asynchronously when a new stanza(/packet) was received.
*/
private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>();
/**
* List of PacketListeners that will be notified when a new stanza(/packet) was sent.
*/
private final Map<StanzaListener, ListenerWrapper> sendListeners =
new HashMap<StanzaListener, ListenerWrapper>();
/**
* List of PacketListeners that will be notified when a new stanza(/packet) is about to be
* sent to the server. These interceptors may modify the stanza(/packet) before it is being
* actually sent to the server.
*/
private final Map<StanzaListener, InterceptorWrapper> interceptors =
new HashMap<StanzaListener, InterceptorWrapper>();
protected final Lock connectionLock = new ReentrantLock();
protected final Map<String, ExtensionElement> streamFeatures = new HashMap<String, ExtensionElement>();
/**
* The full JID of the authenticated user, as returned by the resource binding response of the server.
* <p>
* It is important that we don't infer the user from the login() arguments and the configurations service name, as,
* for example, when SASL External is used, the username is not given to login but taken from the 'external'
* certificate.
* </p>
*/
protected String user;
protected boolean connected = false;
/**
* The stream ID, see RFC 6120 § 4.7.3
*/
protected String streamId;
/**
*
*/
private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout();
/**
* The SmackDebugger allows to log and debug XML traffic.
*/
protected SmackDebugger debugger = null;
/**
* The Reader which is used for the debugger.
*/
protected Reader reader;
/**
* The Writer which is used for the debugger.
*/
protected Writer writer;
/**
* Set to success if the last features stanza from the server has been parsed. A XMPP connection
* handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature
* stanza is send by the server. This is set to true once the last feature stanza has been
* parsed.
*/
protected final SynchronizationPoint<Exception> lastFeaturesReceived = new SynchronizationPoint<Exception>(
AbstractXMPPConnection.this);
/**
* Set to success if the sasl feature has been received.
*/
protected final SynchronizationPoint<SmackException> saslFeatureReceived = new SynchronizationPoint<SmackException>(
AbstractXMPPConnection.this);
/**
* The SASLAuthentication manager that is responsible for authenticating with the server.
*/
protected SASLAuthentication saslAuthentication = new SASLAuthentication(this);
/**
* A number to uniquely identify connections that are created. This is distinct from the
* connection ID, which is a value sent by the server once a connection is made.
*/
protected final int connectionCounterValue = connectionCounter.getAndIncrement();
/**
* Holds the initial configuration used while creating the connection.
*/
protected final ConnectionConfiguration config;
/**
* Defines how the from attribute of outgoing stanzas should be handled.
*/
private FromMode fromMode = FromMode.OMITTED;
protected XMPPInputOutputStream compressionHandler;
private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback();
/**
* ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is
* important that we use a <b>single threaded ExecutorService</b> in order to guarantee that the
* PacketListeners are invoked in the same order the stanzas arrived.
*/
private final BoundedThreadPoolExecutor executorService = new BoundedThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
100, new SmackExecutorThreadFactory(connectionCounterValue, "Incoming Processor"));
/**
* This scheduled thread pool executor is used to remove pending callbacks.
*/
private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor(
new SmackExecutorThreadFactory(connectionCounterValue, "Remove Callbacks"));
/**
* A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set
* them 'daemon'.
*/
private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool(
// @formatter:off
new SmackExecutorThreadFactory( // threadFactory
connectionCounterValue,
"Cached Executor"
)
// @formatter:on
);
/**
* A executor service used to invoke the callbacks of synchronous stanza(/packet) listeners. We use a executor service to
* decouple incoming stanza processing from callback invocation. It is important that order of callback invocation
* is the same as the order of the incoming stanzas. Therefore we use a <i>single</i> threaded executor service.
*/
private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory(
getConnectionCounter(), "Single Threaded Executor"));
/**
* The used host to establish the connection to
*/
protected String host;
/**
* The used port to establish the connection to
*/
protected int port;
/**
* Flag that indicates if the user is currently authenticated with the server.
*/
protected boolean authenticated = false;
/**
* Flag that indicates if the user was authenticated with the server when the connection
* to the server was closed (abruptly or not).
*/
protected boolean wasAuthenticated = false;
private final Map<String, IQRequestHandler> setIqRequestHandler = new HashMap<>();
private final Map<String, IQRequestHandler> getIqRequestHandler = new HashMap<>();
/**
* Create a new XMPPConnection to an XMPP server.
*
* @param configuration The configuration which is used to establish the connection.
*/
protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
config = configuration;
}
/**
* Get the connection configuration used by this connection.
*
* @return the connection configuration.
*/
public ConnectionConfiguration getConfiguration() {
return config;
}
@Override
public String getServiceName() {
if (serviceName != null) {
return serviceName;
}
return config.getServiceName();
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public abstract boolean isSecureConnection();
protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException;
@Override
public abstract void send(PlainStreamElement element) throws NotConnectedException;
@Override
public abstract boolean isUsingCompression();
/**
* Establishes a connection to the XMPP server and performs an automatic login
* only if the previous connection state was logged (authenticated). It basically
* creates and maintains a connection to the server.
* <p>
* Listeners will be preserved from a previous connection.
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException
* @throws ConnectionException with detailed information about the failed connection.
* @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
*/
public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException {
// Check if not already connected
throwAlreadyConnectedExceptionIfAppropriate();
// Reset the connection state
saslAuthentication.init();
saslFeatureReceived.init();
lastFeaturesReceived.init();
streamId = null;
// Perform the actual connection to the XMPP service
connectInternal();
return this;
}
/**
* Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
* way of XMPP connection establishment. Implementations are required to perform an automatic
* login if the previous connection state was logged (authenticated).
*
* @throws SmackException
* @throws IOException
* @throws XMPPException
*/
protected abstract void connectInternal() throws SmackException, IOException, XMPPException;
private String usedUsername, usedPassword, usedResource;
/**
* Logs in to the server using the strongest SASL mechanism supported by
* the server. If more than the connection's default stanza(/packet) timeout elapses in each step of the
* authentication process without a response from the server, a
* {@link SmackException.NoResponseException} will be thrown.
* <p>
* Before logging in (i.e. authenticate) to the server the connection must be connected
* by calling {@link #connect}.
* </p>
* <p>
* It is possible to log in without sending an initial available presence by using
* {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}.
* Finally, if you want to not pass a password and instead use a more advanced mechanism
* while using SASL then you may be interested in using
* {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}.
* For more advanced login settings see {@link ConnectionConfiguration}.
* </p>
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException if an I/O error occurs during login.
*/
public synchronized void login() throws XMPPException, SmackException, IOException {
if (isAnonymous()) {
throwNotConnectedExceptionIfAppropriate("Did you call connect() before login()?");
throwAlreadyLoggedInExceptionIfAppropriate();
loginAnonymously();
} else {
// The previously used username, password and resource take over precedence over the
// ones from the connection configuration
CharSequence username = usedUsername != null ? usedUsername : config.getUsername();
String password = usedPassword != null ? usedPassword : config.getPassword();
String resource = usedResource != null ? usedResource : config.getResource();
login(username, password, resource);
}
}
/**
* Same as {@link #login(CharSequence, String, String)}, but takes the resource from the connection
* configuration.
*
* @param username
* @param password
* @throws XMPPException
* @throws SmackException
* @throws IOException
* @see #login
*/
public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException,
IOException {
login(username, password, config.getResource());
}
/**
* Login with the given username (authorization identity). You may omit the password if a callback handler is used.
* If resource is null, then the server will generate one.
*
* @param username
* @param password
* @param resource
* @throws XMPPException
* @throws SmackException
* @throws IOException
* @see #login
*/
public synchronized void login(CharSequence username, String password, String resource) throws XMPPException,
SmackException, IOException {
if (!config.allowNullOrEmptyUsername) {
StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty");
}
throwNotConnectedExceptionIfAppropriate();
throwAlreadyLoggedInExceptionIfAppropriate();
usedUsername = username != null ? username.toString() : null;
usedPassword = password;
usedResource = resource;
loginNonAnonymously(usedUsername, usedPassword, usedResource);
}
protected abstract void loginNonAnonymously(String username, String password, String resource)
throws XMPPException, SmackException, IOException;
protected abstract void loginAnonymously() throws XMPPException, SmackException, IOException;
@Override
public final boolean isConnected() {
return connected;
}
@Override
public final boolean isAuthenticated() {
return authenticated;
}
@Override
public final String getUser() {
return user;
}
@Override
public String getStreamId() {
if (!isConnected()) {
return null;
}
return streamId;
}
// TODO remove this suppression once "disable legacy session" code has been removed from Smack
@SuppressWarnings("deprecation")
protected void bindResourceAndEstablishSession(String resource) throws XMPPErrorException,
IOException, SmackException {
// Wait until either:
// - the servers last features stanza has been parsed
// - the timeout occurs
LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
lastFeaturesReceived.checkIfSuccessOrWait();
if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
// Server never offered resource binding, which is REQURIED in XMPP client and
// server implementations as per RFC6120 7.2
throw new ResourceBindingNotOfferedException();
}
// Resource binding, see RFC6120 7.
// Note that we can not use IQReplyFilter here, since the users full JID is not yet
// available. It will become available right after the resource has been successfully bound.
Bind bindResource = Bind.newSet(resource);
PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
Bind response = packetCollector.nextResultOrThrow();
// Set the connections user to the result of resource binding. It is important that we don't infer the user
// from the login() arguments and the configurations service name, as, for example, when SASL External is used,
// the username is not given to login but taken from the 'external' certificate.
user = response.getJid();
serviceName = XmppStringUtils.parseDomain(user);
Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE);
// Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
// For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
if (sessionFeature != null && !sessionFeature.isOptional() && !getConfiguration().isLegacySessionDisabled()) {
Session session = new Session();
packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session);
packetCollector.nextResultOrThrow();
}
}
protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException {
// Indicate that we're now authenticated.
this.authenticated = true;
// If debugging is enabled, change the the debug window title to include the
// name we are now logged-in as.
// If DEBUG was set to true AFTER the connection was created the debugger
// will be null
if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user);
}
callConnectionAuthenticatedListener(resumed);
// Set presence to online. It is important that this is done after
// callConnectionAuthenticatedListener(), as this call will also
// eventually load the roster. And we should load the roster before we
// send the initial presence.
if (config.isSendPresence() && !resumed) {
sendStanza(new Presence(Presence.Type.available));
}
}
@Override
public final boolean isAnonymous() {
return config.getUsername() == null && usedUsername == null
&& !config.allowNullOrEmptyUsername;
}
private String serviceName;
protected List<HostAddress> hostAddresses;
/**
* Populates {@link #hostAddresses} with at least one host address.
*
* @return a list of host addresses where DNS (SRV) RR resolution failed.
*/
protected List<HostAddress> populateHostAddresses() {
List<HostAddress> failedAddresses = new LinkedList<>();
// N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName
if (config.host != null) {
hostAddresses = new ArrayList<HostAddress>(1);
HostAddress hostAddress;
hostAddress = new HostAddress(config.host, config.port);
hostAddresses.add(hostAddress);
} else {
hostAddresses = DNSUtil.resolveXMPPDomain(config.serviceName, failedAddresses);
}
// If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the
// config.host one or the host representing the service name by DNSUtil
assert(!hostAddresses.isEmpty());
return failedAddresses;
}
protected Lock getConnectionLock() {
return connectionLock;
}
protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
throwNotConnectedExceptionIfAppropriate(null);
}
protected void throwNotConnectedExceptionIfAppropriate(String optionalHint) throws NotConnectedException {
if (!isConnected()) {
throw new NotConnectedException(optionalHint);
}
}
protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
if (isConnected()) {
throw new AlreadyConnectedException();
}
}
protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
if (isAuthenticated()) {
throw new AlreadyLoggedInException();
}
}
@Deprecated
@Override
public void sendPacket(Stanza packet) throws NotConnectedException {
sendStanza(packet);
}
@Override
public void sendStanza(Stanza packet) throws NotConnectedException {
Objects.requireNonNull(packet, "Packet must not be null");
throwNotConnectedExceptionIfAppropriate();
switch (fromMode) {
case OMITTED:
packet.setFrom(null);
break;
case USER:
packet.setFrom(getUser());
break;
case UNCHANGED:
default:
break;
}
// Invoke interceptors for the new packet that is about to be sent. Interceptors may modify
// the content of the packet.
firePacketInterceptors(packet);
sendStanzaInternal(packet);
}
/**
* Returns the SASLAuthentication manager that is responsible for authenticating with
* the server.
*
* @return the SASLAuthentication manager that is responsible for authenticating with
* the server.
*/
protected SASLAuthentication getSASLAuthentication() {
return saslAuthentication;
}
/**
* Closes the connection by setting presence to unavailable then closing the connection to
* the XMPP server. The XMPPConnection can still be used for connecting to the server
* again.
*
*/
public void disconnect() {
try {
disconnect(new Presence(Presence.Type.unavailable));
}
catch (NotConnectedException e) {
LOGGER.log(Level.FINEST, "Connection is already disconnected", e);
}
}
/**
* Closes the connection. A custom unavailable presence is sent to the server, followed
* by closing the stream. The XMPPConnection can still be used for connecting to the server
* again. A custom unavailable presence is useful for communicating offline presence
* information such as "On vacation". Typically, just the status text of the presence
* stanza(/packet) is set with online information, but most XMPP servers will deliver the full
* presence stanza(/packet) with whatever data is set.
*
* @param unavailablePresence the presence stanza(/packet) to send during shutdown.
* @throws NotConnectedException
*/
public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException {
sendStanza(unavailablePresence);
shutdown();
callConnectionClosedListener();
}
/**
* Shuts the current connection down.
*/
protected abstract void shutdown();
@Override
public void addConnectionListener(ConnectionListener connectionListener) {
if (connectionListener == null) {
return;
}
connectionListeners.add(connectionListener);
}
@Override
public void removeConnectionListener(ConnectionListener connectionListener) {
connectionListeners.remove(connectionListener);
}
@Override
public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException {
StanzaFilter packetFilter = new IQReplyFilter(packet, this);
// Create the packet collector before sending the packet
PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet);
return packetCollector;
}
@Override
public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
throws NotConnectedException {
// Create the packet collector before sending the packet
PacketCollector packetCollector = createPacketCollector(packetFilter);
try {
// Now we can send the packet as the collector has been created
sendStanza(packet);
}
catch (NotConnectedException | RuntimeException e) {
packetCollector.cancel();
throw e;
}
return packetCollector;
}
@Override
public PacketCollector createPacketCollector(StanzaFilter packetFilter) {
PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter);
return createPacketCollector(configuration);
}
@Override
public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) {
PacketCollector collector = new PacketCollector(this, configuration);
// Add the collector to the list of active collectors.
collectors.add(collector);
return collector;
}
@Override
public void removePacketCollector(PacketCollector collector) {
collectors.remove(collector);
}
@Override
@Deprecated
public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) {
addAsyncStanzaListener(packetListener, packetFilter);
}
@Override
@Deprecated
public boolean removePacketListener(StanzaListener packetListener) {
return removeAsyncStanzaListener(packetListener);
}
@Override
public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (syncRecvListeners) {
syncRecvListeners.put(packetListener, wrapper);
}
}
@Override
public boolean removeSyncStanzaListener(StanzaListener packetListener) {
synchronized (syncRecvListeners) {
return syncRecvListeners.remove(packetListener) != null;
}
}
@Override
public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (asyncRecvListeners) {
asyncRecvListeners.put(packetListener, wrapper);
}
}
@Override
public boolean removeAsyncStanzaListener(StanzaListener packetListener) {
synchronized (asyncRecvListeners) {
return asyncRecvListeners.remove(packetListener) != null;
}
}
@Override
public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (sendListeners) {
sendListeners.put(packetListener, wrapper);
}
}
@Override
public void removePacketSendingListener(StanzaListener packetListener) {
synchronized (sendListeners) {
sendListeners.remove(packetListener);
}
}
/**
* Process all stanza(/packet) listeners for sending packets.
* <p>
* Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread.
* </p>
*
* @param packet the stanza(/packet) to process.
*/
@SuppressWarnings("javadoc")
protected void firePacketSendingListeners(final Stanza packet) {
final List<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
synchronized (sendListeners) {
for (ListenerWrapper listenerWrapper : sendListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
if (listenersToNotify.isEmpty()) {
return;
}
// Notify in a new thread, because we can
asyncGo(new Runnable() {
@Override
public void run() {
for (StanzaListener listener : listenersToNotify) {
try {
listener.processPacket(packet);
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Sending listener threw exception", e);
continue;
}
}
}});
}
@Override
public void addPacketInterceptor(StanzaListener packetInterceptor,
StanzaFilter packetFilter) {
if (packetInterceptor == null) {
throw new NullPointerException("Packet interceptor is null.");
}
InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
synchronized (interceptors) {
interceptors.put(packetInterceptor, interceptorWrapper);
}
}
@Override
public void removePacketInterceptor(StanzaListener packetInterceptor) {
synchronized (interceptors) {
interceptors.remove(packetInterceptor);
}
}
/**
* Process interceptors. Interceptors may modify the stanza(/packet) that is about to be sent.
* Since the thread that requested to send the stanza(/packet) will invoke all interceptors, it
* is important that interceptors perform their work as soon as possible so that the
* thread does not remain blocked for a long period.
*
* @param packet the stanza(/packet) that is going to be sent to the server
*/
private void firePacketInterceptors(Stanza packet) {
List<StanzaListener> interceptorsToInvoke = new LinkedList<StanzaListener>();
synchronized (interceptors) {
for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
if (interceptorWrapper.filterMatches(packet)) {
interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
}
}
}
for (StanzaListener interceptor : interceptorsToInvoke) {
try {
interceptor.processPacket(packet);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
}
}
}
/**
* Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger}
* by setup the system property <code>smack.debuggerClass</code> to the implementation.
*
* @throws IllegalStateException if the reader or writer isn't yet initialized.
* @throws IllegalArgumentException if the SmackDebugger can't be loaded.
*/
protected void initDebugger() {
if (reader == null || writer == null) {
throw new NullPointerException("Reader or writer isn't initialized.");
}
// If debugging is enabled, we open a window and write out all network traffic.
if (config.isDebuggerEnabled()) {
if (debugger == null) {
debugger = SmackConfiguration.createDebugger(this, writer, reader);
}
if (debugger == null) {
LOGGER.severe("Debugging enabled but could not find debugger class");
} else {
// Obtain new reader and writer from the existing debugger
reader = debugger.newConnectionReader(reader);
writer = debugger.newConnectionWriter(writer);
}
}
}
@Override
public long getPacketReplyTimeout() {
return packetReplyTimeout;
}
@Override
public void setPacketReplyTimeout(long timeout) {
packetReplyTimeout = timeout;
}
private static boolean replyToUnknownIqDefault = true;
/**
* Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured
* default is 'true'.
*
* @param replyToUnkownIqDefault
* @see #setReplyToUnknownIq(boolean)
*/
public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) {
AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault;
}
private boolean replyToUnkownIq = replyToUnknownIqDefault;
/**
* Set if Smack will automatically send
* {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a
* registered {@link IQRequestHandler} is received.
*
* @param replyToUnknownIq
*/
public void setReplyToUnknownIq(boolean replyToUnknownIq) {
this.replyToUnkownIq = replyToUnknownIq;
}
protected void parseAndProcessStanza(XmlPullParser parser) throws Exception {
ParserUtils.assertAtStartTag(parser);
int parserDepth = parser.getDepth();
Stanza stanza = null;
try {
stanza = PacketParserUtils.parseStanza(parser);
}
catch (Exception e) {
CharSequence content = PacketParserUtils.parseContentDepth(parser,
parserDepth);
UnparsablePacket message = new UnparsablePacket(content, e);
ParsingExceptionCallback callback = getParsingExceptionCallback();
if (callback != null) {
callback.handleUnparsablePacket(message);
}
}
ParserUtils.assertAtEndTag(parser);
if (stanza != null) {
processPacket(stanza);
}
}
/**
* Processes a stanza(/packet) after it's been fully parsed by looping through the installed
* stanza(/packet) collectors and listeners and letting them examine the stanza(/packet) to see if
* they are a match with the filter.
*
* @param packet the stanza(/packet) to process.
* @throws InterruptedException
*/
protected void processPacket(Stanza packet) throws InterruptedException {
assert(packet != null);
lastStanzaReceived = System.currentTimeMillis();
// Deliver the incoming packet to listeners.
executorService.executeBlocking(new ListenerNotification(packet));
}
/**
* A runnable to notify all listeners and stanza(/packet) collectors of a packet.
*/
private class ListenerNotification implements Runnable {
private final Stanza packet;
public ListenerNotification(Stanza packet) {
this.packet = packet;
}
public void run() {
invokePacketCollectorsAndNotifyRecvListeners(packet);
}
}
/**
* Invoke {@link PacketCollector#processPacket(Stanza)} for every
* PacketCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet.
*
* @param packet the stanza(/packet) to notify the PacketCollectors and receive listeners about.
*/
protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) {
if (packet instanceof IQ) {
final IQ iq = (IQ) packet;
final IQ.Type type = iq.getType();
switch (type) {
case set:
case get:
final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace());
IQRequestHandler iqRequestHandler = null;
switch (type) {
case set:
synchronized (setIqRequestHandler) {
iqRequestHandler = setIqRequestHandler.get(key);
}
break;
case get:
synchronized (getIqRequestHandler) {
iqRequestHandler = getIqRequestHandler.get(key);
}
break;
default:
throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
}
if (iqRequestHandler == null) {
if (!replyToUnkownIq) {
return;
}
// If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
// IQ of type "error" with code 501 ("feature-not-implemented")
ErrorIQ errorIQ = IQ.createErrorResponse(iq, new XMPPError(
XMPPError.Condition.feature_not_implemented));
try {
sendStanza(errorIQ);
}
catch (NotConnectedException e) {
LOGGER.log(Level.WARNING, "NotConnectedException while sending error IQ to unkown IQ request", e);
}
} else {
ExecutorService executorService = null;
switch (iqRequestHandler.getMode()) {
case sync:
executorService = singleThreadedExecutorService;
break;
case async:
executorService = cachedExecutorService;
break;
}
final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
executorService.execute(new Runnable() {
@Override
public void run() {
IQ response = finalIqRequestHandler.handleIQRequest(iq);
if (response == null) {
// It is not ideal if the IQ request handler does not return an IQ response, because RFC
// 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the
// file transfer one, does not always return a result, so we need to handle this case.
// Also sometimes a request handler may decide that it's better to not send a response,
// e.g. to avoid presence leaks.
return;
}
try {
sendStanza(response);
}
catch (NotConnectedException e) {
LOGGER.log(Level.WARNING, "NotConnectedException while sending response to IQ request", e);
}
}
});
// The following returns makes it impossible for packet listeners and collectors to
// filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the
// desired behavior.
return;
}
break;
default:
break;
}
}
// First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
// the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
// their own thread.
final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
synchronized (asyncRecvListeners) {
for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
for (final StanzaListener listener : listenersToNotify) {
asyncGo(new Runnable() {
@Override
public void run() {
try {
listener.processPacket(packet);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
}
}
});
}
// Loop through all collectors and notify the appropriate ones.
for (PacketCollector collector: collectors) {
collector.processPacket(packet);
}
// Notify the receive listeners interested in the packet
listenersToNotify.clear();
synchronized (syncRecvListeners) {
for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
// Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
// threaded executor service and therefore keeps the order.
singleThreadedExecutorService.execute(new Runnable() {
@Override
public void run() {
for (StanzaListener listener : listenersToNotify) {
try {
listener.processPacket(packet);
} catch(NotConnectedException e) {
LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
break;
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
}
}
}
});
}
/**
* Sets whether the connection has already logged in the server. This method assures that the
* {@link #wasAuthenticated} flag is never reset once it has ever been set.
*
*/
protected void setWasAuthenticated() {
// Never reset the flag if the connection has ever been authenticated
if (!wasAuthenticated) {
wasAuthenticated = authenticated;
}
}
protected void callConnectionConnectedListener() {
for (ConnectionListener listener : connectionListeners) {
listener.connected(this);
}
}
protected void callConnectionAuthenticatedListener(boolean resumed) {
for (ConnectionListener listener : connectionListeners) {
try {
listener.authenticated(this, resumed);
} catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e);
}
}
}
void callConnectionClosedListener() {
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionClosed();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
}
}
}
protected void callConnectionClosedOnErrorListener(Exception e) {
LOGGER.log(Level.WARNING, "Connection closed with error", e);
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionClosedOnError(e);
}
catch (Exception e2) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
}
}
}
/**
* Sends a notification indicating that the connection was reconnected successfully.
*/
protected void notifyReconnection() {
// Notify connection listeners of the reconnection.
for (ConnectionListener listener : connectionListeners) {
try {
listener.reconnectionSuccessful();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.WARNING, "notifyReconnection()", e);
}
}
}
/**
* A wrapper class to associate a stanza(/packet) filter with a listener.
*/
protected static class ListenerWrapper {
private final StanzaListener packetListener;
private final StanzaFilter packetFilter;
/**
* Create a class which associates a stanza(/packet) filter with a listener.
*
* @param packetListener the stanza(/packet) listener.
* @param packetFilter the associated filter or null if it listen for all packets.
*/
public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) {
this.packetListener = packetListener;
this.packetFilter = packetFilter;
}
public boolean filterMatches(Stanza packet) {
return packetFilter == null || packetFilter.accept(packet);
}
public StanzaListener getListener() {
return packetListener;
}
}
/**
* A wrapper class to associate a stanza(/packet) filter with an interceptor.
*/
protected static class InterceptorWrapper {
private final StanzaListener packetInterceptor;
private final StanzaFilter packetFilter;
/**
* Create a class which associates a stanza(/packet) filter with an interceptor.
*
* @param packetInterceptor the interceptor.
* @param packetFilter the associated filter or null if it intercepts all packets.
*/
public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) {
this.packetInterceptor = packetInterceptor;
this.packetFilter = packetFilter;
}
public boolean filterMatches(Stanza packet) {
return packetFilter == null || packetFilter.accept(packet);
}
public StanzaListener getInterceptor() {
return packetInterceptor;
}
}
@Override
public int getConnectionCounter() {
return connectionCounterValue;
}
@Override
public void setFromMode(FromMode fromMode) {
this.fromMode = fromMode;
}
@Override
public FromMode getFromMode() {
return this.fromMode;
}
@Override
protected void finalize() throws Throwable {
LOGGER.fine("finalizing XMPPConnection ( " + getConnectionCounter()
+ "): Shutting down executor services");
try {
// It's usually not a good idea to rely on finalize. But this is the easiest way to
// avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a
// reference to their ExecutorService which prevents the ExecutorService from being
// gc'ed. It is possible that the XMPPConnection instance is gc'ed while the
// listenerExecutor ExecutorService call not be gc'ed until it got shut down.
executorService.shutdownNow();
cachedExecutorService.shutdown();
removeCallbacksService.shutdownNow();
singleThreadedExecutorService.shutdownNow();
} catch (Throwable t) {
LOGGER.log(Level.WARNING, "finalize() threw trhowable", t);
}
finally {
super.finalize();
}
}
protected final void parseFeatures(XmlPullParser parser) throws XmlPullParserException,
IOException, SmackException {
streamFeatures.clear();
final int initialDepth = parser.getDepth();
while (true) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) {
ExtensionElement streamFeature = null;
String name = parser.getName();
String namespace = parser.getNamespace();
switch (name) {
case StartTls.ELEMENT:
streamFeature = PacketParserUtils.parseStartTlsFeature(parser);
break;
case Mechanisms.ELEMENT:
streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser));
break;
case Bind.ELEMENT:
streamFeature = Bind.Feature.INSTANCE;
break;
case Session.ELEMENT:
streamFeature = PacketParserUtils.parseSessionFeature(parser);
break;
case Compress.Feature.ELEMENT:
streamFeature = PacketParserUtils.parseCompressionFeature(parser);
break;
default:
ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace);
if (provider != null) {
streamFeature = provider.parse(parser);
}
break;
}
if (streamFeature != null) {
addStreamFeature(streamFeature);
}
}
else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) {
break;
}
}
if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
// Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
|| config.getSecurityMode() == SecurityMode.disabled) {
saslFeatureReceived.reportSuccess();
}
}
// If the server reported the bind feature then we are that that we did SASL and maybe
// STARTTLS. We can then report that the last 'stream:features' have been parsed
if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
|| !config.isCompressionEnabled()) {
// This was was last features from the server is either it did not contain
// compression or if we disabled it
lastFeaturesReceived.reportSuccess();
}
}
afterFeaturesReceived();
}
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException {
// Default implementation does nothing
}
@SuppressWarnings("unchecked")
@Override
public <F extends ExtensionElement> F getFeature(String element, String namespace) {
return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace));
}
@Override
public boolean hasFeature(String element, String namespace) {
return getFeature(element, namespace) != null;
}
private void addStreamFeature(ExtensionElement feature) {
String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace());
streamFeatures.put(key, feature);
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
StanzaListener callback) throws NotConnectedException {
sendStanzaWithResponseCallback(stanza, replyFilter, callback, null);
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
StanzaListener callback, ExceptionCallback exceptionCallback)
throws NotConnectedException {
sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback,
getPacketReplyTimeout());
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter,
final StanzaListener callback, final ExceptionCallback exceptionCallback,
long timeout) throws NotConnectedException {
Objects.requireNonNull(stanza, "stanza must not be null");
// While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
// disallow it here in the async API as it makes no sense
Objects.requireNonNull(replyFilter, "replyFilter must not be null");
Objects.requireNonNull(callback, "callback must not be null");
final StanzaListener packetListener = new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws NotConnectedException {
try {
XMPPErrorException.ifHasErrorThenThrow(packet);
callback.processPacket(packet);
}
catch (XMPPErrorException e) {
if (exceptionCallback != null) {
exceptionCallback.processException(e);
}
}
finally {
removeAsyncStanzaListener(this);
}
}
};
removeCallbacksService.schedule(new Runnable() {
@Override
public void run() {
boolean removed = removeAsyncStanzaListener(packetListener);
// If the packetListener got removed, then it was never run and
// we never received a response, inform the exception callback
if (removed && exceptionCallback != null) {
exceptionCallback.processException(NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter));
}
}
}, timeout, TimeUnit.MILLISECONDS);
addAsyncStanzaListener(packetListener, replyFilter);
sendStanza(stanza);
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback)
throws NotConnectedException {
sendIqWithResponseCallback(iqRequest, callback, null);
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback,
ExceptionCallback exceptionCallback) throws NotConnectedException {
sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout());
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback,
final ExceptionCallback exceptionCallback, long timeout)
throws NotConnectedException {
StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this);
sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout);
}
@Override
public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
final StanzaListener packetListener = new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws NotConnectedException {
try {
callback.processPacket(packet);
} finally {
removeSyncStanzaListener(this);
}
}
};
addSyncStanzaListener(packetListener, packetFilter);
removeCallbacksService.schedule(new Runnable() {
@Override
public void run() {
removeSyncStanzaListener(packetListener);
}
}, getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
}
@Override
public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) {
final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace());
switch (iqRequestHandler.getType()) {
case set:
synchronized (setIqRequestHandler) {
return setIqRequestHandler.put(key, iqRequestHandler);
}
case get:
synchronized (getIqRequestHandler) {
return getIqRequestHandler.put(key, iqRequestHandler);
}
default:
throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
}
}
@Override
public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) {
return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(),
iqRequestHandler.getType());
}
@Override
public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
final String key = XmppStringUtils.generateKey(element, namespace);
switch (type) {
case set:
synchronized (setIqRequestHandler) {
return setIqRequestHandler.remove(key);
}
case get:
synchronized (getIqRequestHandler) {
return getIqRequestHandler.remove(key);
}
default:
throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
}
}
private long lastStanzaReceived;
public long getLastStanzaReceived() {
return lastStanzaReceived;
}
/**
* Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a
* stanza
*
* @param callback the callback to install
*/
public void setParsingExceptionCallback(ParsingExceptionCallback callback) {
parsingExceptionCallback = callback;
}
/**
* Get the current active parsing exception callback.
*
* @return the active exception callback or null if there is none
*/
public ParsingExceptionCallback getParsingExceptionCallback() {
return parsingExceptionCallback;
}
protected final void asyncGo(Runnable runnable) {
cachedExecutorService.execute(runnable);
}
protected final ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) {
return removeCallbacksService.schedule(runnable, delay, unit);
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_4768_0
|
crossvul-java_data_good_4769_1
|
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.tcp;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.DnssecMode;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.ConnectionException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByServerException;
import org.jivesoftware.smack.SynchronizationPoint;
import org.jivesoftware.smack.XMPPException.StreamErrorException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.compress.packet.Compressed;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.compress.packet.Compress;
import org.jivesoftware.smack.packet.Element;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.StreamOpen;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.StartTls;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Challenge;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.SASLFailure;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Success;
import org.jivesoftware.smack.sm.SMUtils;
import org.jivesoftware.smack.sm.StreamManagementException;
import org.jivesoftware.smack.sm.StreamManagementException.StreamIdDoesNotMatchException;
import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementCounterError;
import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementNotEnabledException;
import org.jivesoftware.smack.sm.packet.StreamManagement;
import org.jivesoftware.smack.sm.packet.StreamManagement.AckAnswer;
import org.jivesoftware.smack.sm.packet.StreamManagement.AckRequest;
import org.jivesoftware.smack.sm.packet.StreamManagement.Enable;
import org.jivesoftware.smack.sm.packet.StreamManagement.Enabled;
import org.jivesoftware.smack.sm.packet.StreamManagement.Failed;
import org.jivesoftware.smack.sm.packet.StreamManagement.Resume;
import org.jivesoftware.smack.sm.packet.StreamManagement.Resumed;
import org.jivesoftware.smack.sm.packet.StreamManagement.StreamManagementFeature;
import org.jivesoftware.smack.sm.predicates.Predicate;
import org.jivesoftware.smack.sm.provider.ParseStreamManagement;
import org.jivesoftware.smack.packet.Nonza;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.proxy.ProxyInfo;
import org.jivesoftware.smack.util.ArrayBlockingQueueWithShutdown;
import org.jivesoftware.smack.util.Async;
import org.jivesoftware.smack.util.DNSUtil;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.TLSUtils;
import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jivesoftware.smack.util.dns.SmackDaneProvider;
import org.jivesoftware.smack.util.dns.SmackDaneVerifier;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.jid.parts.Resourcepart;
import org.jxmpp.stringprep.XmppStringprepException;
import org.jxmpp.util.XmppStringUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Creates a socket connection to an XMPP server. This is the default connection
* to an XMPP server and is specified in the XMPP Core (RFC 6120).
*
* @see XMPPConnection
* @author Matt Tucker
*/
public class XMPPTCPConnection extends AbstractXMPPConnection {
private static final int QUEUE_SIZE = 500;
private static final Logger LOGGER = Logger.getLogger(XMPPTCPConnection.class.getName());
/**
* The socket which is used for this connection.
*/
private Socket socket;
/**
*
*/
private boolean disconnectedButResumeable = false;
private boolean usingTLS = false;
/**
* Protected access level because of unit test purposes
*/
protected PacketWriter packetWriter;
/**
* Protected access level because of unit test purposes
*/
protected PacketReader packetReader;
private final SynchronizationPoint<Exception> initalOpenStreamSend = new SynchronizationPoint<>(
this, "initial open stream element send to server");
/**
*
*/
private final SynchronizationPoint<XMPPException> maybeCompressFeaturesReceived = new SynchronizationPoint<XMPPException>(
this, "stream compression feature");
/**
*
*/
private final SynchronizationPoint<SmackException> compressSyncPoint = new SynchronizationPoint<>(
this, "stream compression");
/**
* A synchronization point which is successful if this connection has received the closing
* stream element from the remote end-point, i.e. the server.
*/
private final SynchronizationPoint<Exception> closingStreamReceived = new SynchronizationPoint<>(
this, "stream closing element received");
/**
* The default bundle and defer callback, used for new connections.
* @see bundleAndDeferCallback
*/
private static BundleAndDeferCallback defaultBundleAndDeferCallback;
/**
* The used bundle and defer callback.
* <p>
* Although this field may be set concurrently, the 'volatile' keyword was deliberately not added, in order to avoid
* having a 'volatile' read within the writer threads loop.
* </p>
*/
private BundleAndDeferCallback bundleAndDeferCallback = defaultBundleAndDeferCallback;
private static boolean useSmDefault = true;
private static boolean useSmResumptionDefault = true;
/**
* The stream ID of the stream that is currently resumable, ie. the stream we hold the state
* for in {@link #clientHandledStanzasCount}, {@link #serverHandledStanzasCount} and
* {@link #unacknowledgedStanzas}.
*/
private String smSessionId;
private final SynchronizationPoint<XMPPException> smResumedSyncPoint = new SynchronizationPoint<XMPPException>(
this, "stream resumed element");
private final SynchronizationPoint<XMPPException> smEnabledSyncPoint = new SynchronizationPoint<XMPPException>(
this, "stream enabled element");
/**
* The client's preferred maximum resumption time in seconds.
*/
private int smClientMaxResumptionTime = -1;
/**
* The server's preferred maximum resumption time in seconds.
*/
private int smServerMaxResumptimTime = -1;
/**
* Indicates whether Stream Management (XEP-198) should be used if it's supported by the server.
*/
private boolean useSm = useSmDefault;
private boolean useSmResumption = useSmResumptionDefault;
/**
* The counter that the server sends the client about it's current height. For example, if the server sends
* {@code <a h='42'/>}, then this will be set to 42 (while also handling the {@link #unacknowledgedStanzas} queue).
*/
private long serverHandledStanzasCount = 0;
/**
* The counter for stanzas handled ("received") by the client.
* <p>
* Note that we don't need to synchronize this counter. Although JLS 17.7 states that reads and writes to longs are
* not atomic, it guarantees that there are at most 2 separate writes, one to each 32-bit half. And since
* {@link SMUtils#incrementHeight(long)} masks the lower 32 bit, we only operate on one half of the long and
* therefore have no concurrency problem because the read/write operations on one half are guaranteed to be atomic.
* </p>
*/
private long clientHandledStanzasCount = 0;
private BlockingQueue<Stanza> unacknowledgedStanzas;
/**
* Set to true if Stream Management was at least once enabled for this connection.
*/
private boolean smWasEnabledAtLeastOnce = false;
/**
* This listeners are invoked for every stanza that got acknowledged.
* <p>
* We use a {@link ConccurrentLinkedQueue} here in order to allow the listeners to remove
* themselves after they have been invoked.
* </p>
*/
private final Collection<StanzaListener> stanzaAcknowledgedListeners = new ConcurrentLinkedQueue<StanzaListener>();
/**
* This listeners are invoked for a acknowledged stanza that has the given stanza ID. They will
* only be invoked once and automatically removed after that.
*/
private final Map<String, StanzaListener> stanzaIdAcknowledgedListeners = new ConcurrentHashMap<String, StanzaListener>();
/**
* Predicates that determine if an stream management ack should be requested from the server.
* <p>
* We use a linked hash set here, so that the order how the predicates are added matches the
* order in which they are invoked in order to determine if an ack request should be send or not.
* </p>
*/
private final Set<StanzaFilter> requestAckPredicates = new LinkedHashSet<StanzaFilter>();
private final XMPPTCPConnectionConfiguration config;
/**
* Creates a new XMPP connection over TCP (optionally using proxies).
* <p>
* Note that XMPPTCPConnection constructors do not establish a connection to the server
* and you must call {@link #connect()}.
* </p>
*
* @param config the connection configuration.
*/
public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) {
super(config);
this.config = config;
addConnectionListener(new AbstractConnectionListener() {
@Override
public void connectionClosedOnError(Exception e) {
if (e instanceof XMPPException.StreamErrorException) {
dropSmState();
}
}
});
}
/**
* Creates a new XMPP connection over TCP.
* <p>
* Note that {@code jid} must be the bare JID, e.g. "user@example.org". More fine-grained control over the
* connection settings is available using the {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)}
* constructor.
* </p>
*
* @param jid the bare JID used by the client.
* @param password the password or authentication token.
* @throws XmppStringprepException
*/
public XMPPTCPConnection(CharSequence jid, String password) throws XmppStringprepException {
this(XmppStringUtils.parseLocalpart(jid.toString()), password, XmppStringUtils.parseDomain(jid.toString()));
}
/**
* Creates a new XMPP connection over TCP.
* <p>
* This is the simplest constructor for connecting to an XMPP server. Alternatively,
* you can get fine-grained control over connection settings using the
* {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)} constructor.
* </p>
* @param username
* @param password
* @param serviceName
* @throws XmppStringprepException
*/
public XMPPTCPConnection(CharSequence username, String password, String serviceName) throws XmppStringprepException {
this(XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(username, password).setXmppDomain(
JidCreate.domainBareFrom(serviceName)).build());
}
@Override
protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
if (packetWriter == null) {
throw new NotConnectedException();
}
packetWriter.throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
}
@Override
protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
if (isConnected() && !disconnectedButResumeable) {
throw new AlreadyConnectedException();
}
}
@Override
protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
if (isAuthenticated() && !disconnectedButResumeable) {
throw new AlreadyLoggedInException();
}
}
@Override
protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException, InterruptedException {
// Reset the flag in case it was set
disconnectedButResumeable = false;
super.afterSuccessfulLogin(resumed);
}
@Override
protected synchronized void loginInternal(String username, String password, Resourcepart resource) throws XMPPException,
SmackException, IOException, InterruptedException {
// Authenticate using SASL
saslAuthentication.authenticate(username, password, config.getAuthzid());
// If compression is enabled then request the server to use stream compression. XEP-170
// recommends to perform stream compression before resource binding.
maybeEnableCompression();
if (isSmResumptionPossible()) {
smResumedSyncPoint.sendAndWaitForResponse(new Resume(clientHandledStanzasCount, smSessionId));
if (smResumedSyncPoint.wasSuccessful()) {
// We successfully resumed the stream, be done here
afterSuccessfulLogin(true);
return;
}
// SM resumption failed, what Smack does here is to report success of
// lastFeaturesReceived in case of sm resumption was answered with 'failed' so that
// normal resource binding can be tried.
LOGGER.fine("Stream resumption failed, continuing with normal stream establishment process");
}
List<Stanza> previouslyUnackedStanzas = new LinkedList<Stanza>();
if (unacknowledgedStanzas != null) {
// There was a previous connection with SM enabled but that was either not resumable or
// failed to resume. Make sure that we (re-)send the unacknowledged stanzas.
unacknowledgedStanzas.drainTo(previouslyUnackedStanzas);
// Reset unacknowledged stanzas to 'null' to signal that we never send 'enable' in this
// XMPP session (There maybe was an enabled in a previous XMPP session of this
// connection instance though). This is used in writePackets to decide if stanzas should
// be added to the unacknowledged stanzas queue, because they have to be added right
// after the 'enable' stream element has been sent.
dropSmState();
}
// Now bind the resource. It is important to do this *after* we dropped an eventually
// existing Stream Management state. As otherwise <bind/> and <session/> may end up in
// unacknowledgedStanzas and become duplicated on reconnect. See SMACK-706.
bindResourceAndEstablishSession(resource);
if (isSmAvailable() && useSm) {
// Remove what is maybe left from previously stream managed sessions
serverHandledStanzasCount = 0;
// XEP-198 3. Enabling Stream Management. If the server response to 'Enable' is 'Failed'
// then this is a non recoverable error and we therefore throw an exception.
smEnabledSyncPoint.sendAndWaitForResponseOrThrow(new Enable(useSmResumption, smClientMaxResumptionTime));
synchronized (requestAckPredicates) {
if (requestAckPredicates.isEmpty()) {
// Assure that we have at lest one predicate set up that so that we request acks
// for the server and eventually flush some stanzas from the unacknowledged
// stanza queue
requestAckPredicates.add(Predicate.forMessagesOrAfter5Stanzas());
}
}
}
// (Re-)send the stanzas *after* we tried to enable SM
for (Stanza stanza : previouslyUnackedStanzas) {
sendStanzaInternal(stanza);
}
afterSuccessfulLogin(false);
}
@Override
public boolean isSecureConnection() {
return usingTLS;
}
/**
* Shuts the current connection down. After this method returns, the connection must be ready
* for re-use by connect.
*/
@Override
protected void shutdown() {
if (isSmEnabled()) {
try {
// Try to send a last SM Acknowledgement. Most servers won't find this information helpful, as the SM
// state is dropped after a clean disconnect anyways. OTOH it doesn't hurt much either.
sendSmAcknowledgementInternal();
} catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.FINE, "Can not send final SM ack as connection is not connected", e);
}
}
shutdown(false);
}
/**
* Performs an unclean disconnect and shutdown of the connection. Does not send a closing stream stanza.
*/
public synchronized void instantShutdown() {
shutdown(true);
}
private void shutdown(boolean instant) {
if (disconnectedButResumeable) {
return;
}
// First shutdown the writer, this will result in a closing stream element getting send to
// the server
if (packetWriter != null) {
LOGGER.finer("PacketWriter shutdown()");
packetWriter.shutdown(instant);
}
LOGGER.finer("PacketWriter has been shut down");
try {
// After we send the closing stream element, check if there was already a
// closing stream element sent by the server or wait with a timeout for a
// closing stream element to be received from the server.
@SuppressWarnings("unused")
Exception res = closingStreamReceived.checkIfSuccessOrWait();
} catch (InterruptedException | NoResponseException e) {
LOGGER.log(Level.INFO, "Exception while waiting for closing stream element from the server " + this, e);
}
if (packetReader != null) {
LOGGER.finer("PacketReader shutdown()");
packetReader.shutdown();
}
LOGGER.finer("PacketReader has been shut down");
try {
socket.close();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "shutdown", e);
}
setWasAuthenticated();
// If we are able to resume the stream, then don't set
// connected/authenticated/usingTLS to false since we like behave like we are still
// connected (e.g. sendStanza should not throw a NotConnectedException).
if (isSmResumptionPossible() && instant) {
disconnectedButResumeable = true;
} else {
disconnectedButResumeable = false;
// Reset the stream management session id to null, since if the stream is cleanly closed, i.e. sending a closing
// stream tag, there is no longer a stream to resume.
smSessionId = null;
}
authenticated = false;
connected = false;
usingTLS = false;
reader = null;
writer = null;
maybeCompressFeaturesReceived.init();
compressSyncPoint.init();
smResumedSyncPoint.init();
smEnabledSyncPoint.init();
initalOpenStreamSend.init();
}
@Override
public void sendNonza(Nonza element) throws NotConnectedException, InterruptedException {
packetWriter.sendStreamElement(element);
}
@Override
protected void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException {
packetWriter.sendStreamElement(packet);
if (isSmEnabled()) {
for (StanzaFilter requestAckPredicate : requestAckPredicates) {
if (requestAckPredicate.accept(packet)) {
requestSmAcknowledgementInternal();
break;
}
}
}
}
private void connectUsingConfiguration() throws ConnectionException, IOException {
List<HostAddress> failedAddresses = populateHostAddresses();
SocketFactory socketFactory = config.getSocketFactory();
ProxyInfo proxyInfo = config.getProxyInfo();
int timeout = config.getConnectTimeout();
if (socketFactory == null) {
socketFactory = SocketFactory.getDefault();
}
for (HostAddress hostAddress : hostAddresses) {
Iterator<InetAddress> inetAddresses = null;
String host = hostAddress.getFQDN();
int port = hostAddress.getPort();
if (proxyInfo == null) {
inetAddresses = hostAddress.getInetAddresses().iterator();
assert(inetAddresses.hasNext());
innerloop: while (inetAddresses.hasNext()) {
// Create a *new* Socket before every connection attempt, i.e. connect() call, since Sockets are not
// re-usable after a failed connection attempt. See also SMACK-724.
socket = socketFactory.createSocket();
final InetAddress inetAddress = inetAddresses.next();
final String inetAddressAndPort = inetAddress + " at port " + port;
LOGGER.finer("Trying to establish TCP connection to " + inetAddressAndPort);
try {
socket.connect(new InetSocketAddress(inetAddress, port), timeout);
} catch (Exception e) {
hostAddress.setException(inetAddress, e);
if (inetAddresses.hasNext()) {
continue innerloop;
} else {
break innerloop;
}
}
LOGGER.finer("Established TCP connection to " + inetAddressAndPort);
// We found a host to connect to, return here
this.host = host;
this.port = port;
return;
}
failedAddresses.add(hostAddress);
} else {
final String hostAndPort = host + " at port " + port;
LOGGER.finer("Trying to establish TCP connection via Proxy to " + hostAndPort);
try {
proxyInfo.getProxySocketConnection().connect(socket, host, port, timeout);
} catch (IOException e) {
hostAddress.setException(e);
continue;
}
LOGGER.finer("Established TCP connection to " + hostAndPort);
// We found a host to connect to, return here
this.host = host;
this.port = port;
return;
}
}
// There are no more host addresses to try
// throw an exception and report all tried
// HostAddresses in the exception
throw ConnectionException.from(failedAddresses);
}
/**
* Initializes the connection by creating a stanza(/packet) reader and writer and opening a
* XMPP stream to the server.
*
* @throws XMPPException if establishing a connection to the server fails.
* @throws SmackException if the server failes to respond back or if there is anther error.
* @throws IOException
*/
private void initConnection() throws IOException {
boolean isFirstInitialization = packetReader == null || packetWriter == null;
compressionHandler = null;
// Set the reader and writer instance variables
initReaderAndWriter();
if (isFirstInitialization) {
packetWriter = new PacketWriter();
packetReader = new PacketReader();
// If debugging is enabled, we should start the thread that will listen for
// all packets and then log them.
if (config.isDebuggerEnabled()) {
addAsyncStanzaListener(debugger.getReaderListener(), null);
if (debugger.getWriterListener() != null) {
addPacketSendingListener(debugger.getWriterListener(), null);
}
}
}
// Start the packet writer. This will open an XMPP stream to the server
packetWriter.init();
// Start the packet reader. The startup() method will block until we
// get an opening stream packet back from server
packetReader.init();
}
private void initReaderAndWriter() throws IOException {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
if (compressionHandler != null) {
is = compressionHandler.getInputStream(is);
os = compressionHandler.getOutputStream(os);
}
// OutputStreamWriter is already buffered, no need to wrap it into a BufferedWriter
writer = new OutputStreamWriter(os, "UTF-8");
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// If debugging is enabled, we open a window and write out all network traffic.
initDebugger();
}
/**
* The server has indicated that TLS negotiation can start. We now need to secure the
* existing plain connection and perform a handshake. This method won't return until the
* connection has finished the handshake or an error occurred while securing the connection.
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
* @throws SmackException
* @throws Exception if an exception occurs.
*/
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
SSLContext context = this.config.getCustomSSLContext();
KeyStore ks = null;
KeyManager[] kms = null;
PasswordCallback pcb = null;
SmackDaneVerifier daneVerifier = null;
if (config.getDnssecMode() == DnssecMode.needsDnssecAndDane) {
SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
if (daneProvider == null) {
throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
}
daneVerifier = daneProvider.newInstance();
if (daneVerifier == null) {
throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
}
}
if (context == null) {
final String keyStoreType = config.getKeystoreType();
final CallbackHandler callbackHandler = config.getCallbackHandler();
final String keystorePath = config.getKeystorePath();
if ("PKCS11".equals(keyStoreType)) {
try {
Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library();
ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
Provider p = (Provider)c.newInstance(config);
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11",p);
pcb = new PasswordCallback("PKCS11 Password: ",false);
callbackHandler.handle(new Callback[]{pcb});
ks.load(null,pcb.getPassword());
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
}
else if ("Apple".equals(keyStoreType)) {
ks = KeyStore.getInstance("KeychainStore","Apple");
ks.load(null,null);
//pcb = new PasswordCallback("Apple Keychain",false);
//pcb.setPassword(null);
}
else if (keyStoreType != null){
ks = KeyStore.getInstance(keyStoreType);
if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
try {
pcb = new PasswordCallback("Keystore Password: ", false);
callbackHandler.handle(new Callback[] { pcb });
ks.load(new FileInputStream(keystorePath), pcb.getPassword());
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
} else {
ks.load(null, null);
}
}
if (ks != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
try {
if (pcb == null) {
kmf.init(ks, null);
}
else {
kmf.init(ks, pcb.getPassword());
pcb.clearPassword();
}
kms = kmf.getKeyManagers();
}
catch (NullPointerException npe) {
LOGGER.log(Level.WARNING, "NullPointerException", npe);
}
}
// If the user didn't specify a SSLContext, use the default one
context = SSLContext.getInstance("TLS");
final SecureRandom secureRandom = new java.security.SecureRandom();
X509TrustManager customTrustManager = config.getCustomX509TrustManager();
if (daneVerifier != null) {
// User requested DANE verification.
daneVerifier.init(context, kms, customTrustManager, secureRandom);
} else {
TrustManager[] customTrustManagers = null;
if (customTrustManager != null) {
customTrustManagers = new TrustManager[] { customTrustManager };
}
context.init(kms, customTrustManagers, secureRandom);
}
}
Socket plain = socket;
// Secure the plain connection
socket = context.getSocketFactory().createSocket(plain,
host, plain.getPort(), true);
final SSLSocket sslSocket = (SSLSocket) socket;
// Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
// important (at least on certain platforms) and it seems to be a good idea anyways to
// prevent an accidental implicit handshake.
TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
// Initialize the reader and writer with the new secured version
initReaderAndWriter();
// Proceed to do the handshake
sslSocket.startHandshake();
if (daneVerifier != null) {
daneVerifier.finish(sslSocket);
}
final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
if (verifier == null) {
throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
} else if (!verifier.verify(getXMPPServiceDomain().toString(), sslSocket.getSession())) {
throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain());
}
// Set that TLS was successful
usingTLS = true;
}
/**
* Returns the compression handler that can be used for one compression methods offered by the server.
*
* @return a instance of XMPPInputOutputStream or null if no suitable instance was found
*
*/
private static XMPPInputOutputStream maybeGetCompressionHandler(Compress.Feature compression) {
for (XMPPInputOutputStream handler : SmackConfiguration.getCompresionHandlers()) {
String method = handler.getCompressionMethod();
if (compression.getMethods().contains(method))
return handler;
}
return null;
}
@Override
public boolean isUsingCompression() {
return compressionHandler != null && compressSyncPoint.wasSuccessful();
}
/**
* <p>
* Starts using stream compression that will compress network traffic. Traffic can be
* reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
* connection. However, the server and the client will need to use more CPU time in order to
* un/compress network data so under high load the server performance might be affected.
* </p>
* <p>
* Stream compression has to have been previously offered by the server. Currently only the
* zlib method is supported by the client. Stream compression negotiation has to be done
* before authentication took place.
* </p>
*
* @throws NotConnectedException
* @throws SmackException
* @throws NoResponseException
* @throws InterruptedException
*/
private void maybeEnableCompression() throws NotConnectedException, NoResponseException, SmackException, InterruptedException {
if (!config.isCompressionEnabled()) {
return;
}
maybeCompressFeaturesReceived.checkIfSuccessOrWait();
Compress.Feature compression = getFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE);
if (compression == null) {
// Server does not support compression
return;
}
// If stream compression was offered by the server and we want to use
// compression then send compression request to the server
if ((compressionHandler = maybeGetCompressionHandler(compression)) != null) {
compressSyncPoint.sendAndWaitForResponseOrThrow(new Compress(compressionHandler.getCompressionMethod()));
} else {
LOGGER.warning("Could not enable compression because no matching handler/method pair was found");
}
}
/**
* Establishes a connection to the XMPP server. It basically
* creates and maintains a socket connection to the server.
* <p>
* Listeners will be preserved from a previous connection if the reconnection
* occurs after an abrupt termination.
* </p>
*
* @throws XMPPException if an error occurs while trying to establish the connection.
* @throws SmackException
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException {
closingStreamReceived.init();
// Establishes the TCP connection to the server and does setup the reader and writer. Throws an exception if
// there is an error establishing the connection
connectUsingConfiguration();
// We connected successfully to the servers TCP port
initConnection();
}
/**
* Sends out a notification that there was an error with the connection
* and closes the connection. Also prints the stack trace of the given exception
*
* @param e the exception that causes the connection close event.
*/
private synchronized void notifyConnectionError(Exception e) {
// Listeners were already notified of the exception, return right here.
if ((packetReader == null || packetReader.done) &&
(packetWriter == null || packetWriter.done())) return;
// Closes the connection temporary. A reconnection is possible
// Note that a connection listener of XMPPTCPConnection will drop the SM state in
// case the Exception is a StreamErrorException.
instantShutdown();
// Notify connection listeners of the error.
callConnectionClosedOnErrorListener(e);
}
/**
* For unit testing purposes
*
* @param writer
*/
protected void setWriter(Writer writer) {
this.writer = writer;
}
@Override
protected void afterFeaturesReceived() throws NotConnectedException, InterruptedException {
StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
if (startTlsFeature != null) {
if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
notifyConnectionError(new SecurityRequiredByServerException());
return;
}
if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
sendNonza(new StartTls());
}
}
if (getSASLAuthentication().authenticationSuccessful()) {
// If we have received features after the SASL has been successfully completed, then we
// have also *maybe* received, as it is an optional feature, the compression feature
// from the server.
maybeCompressFeaturesReceived.reportSuccess();
}
}
/**
* Resets the parser using the latest connection's reader. Reseting the parser is necessary
* when the plain connection has been secured or when a new opening stream element is going
* to be sent by the server.
*
* @throws SmackException if the parser could not be reset.
* @throws InterruptedException
*/
void openStream() throws SmackException, InterruptedException {
// If possible, provide the receiving entity of the stream open tag, i.e. the server, as much information as
// possible. The 'to' attribute is *always* available. The 'from' attribute if set by the user and no external
// mechanism is used to determine the local entity (user). And the 'id' attribute is available after the first
// response from the server (see e.g. RFC 6120 § 9.1.1 Step 2.)
CharSequence to = getXMPPServiceDomain();
CharSequence from = null;
CharSequence localpart = config.getUsername();
if (localpart != null) {
from = XmppStringUtils.completeJidFrom(localpart, to);
}
String id = getStreamId();
sendNonza(new StreamOpen(to, from, id));
try {
packetReader.parser = PacketParserUtils.newXmppParser(reader);
}
catch (XmlPullParserException e) {
throw new SmackException(e);
}
}
protected class PacketReader {
XmlPullParser parser;
private volatile boolean done;
/**
* Initializes the reader in order to be used. The reader is initialized during the
* first connection and when reconnecting due to an abruptly disconnection.
*/
void init() {
done = false;
Async.go(new Runnable() {
public void run() {
parsePackets();
}
}, "Smack Packet Reader (" + getConnectionCounter() + ")");
}
/**
* Shuts the stanza(/packet) reader down. This method simply sets the 'done' flag to true.
*/
void shutdown() {
done = true;
}
/**
* Parse top-level packets in order to process them further.
*
* @param thread the thread that is being used by the reader to parse incoming packets.
*/
private void parsePackets() {
try {
initalOpenStreamSend.checkIfSuccessOrWait();
int eventType = parser.getEventType();
while (!done) {
switch (eventType) {
case XmlPullParser.START_TAG:
final String name = parser.getName();
switch (name) {
case Message.ELEMENT:
case IQ.IQ_ELEMENT:
case Presence.ELEMENT:
try {
parseAndProcessStanza(parser);
} finally {
clientHandledStanzasCount = SMUtils.incrementHeight(clientHandledStanzasCount);
}
break;
case "stream":
// We found an opening stream.
if ("jabber:client".equals(parser.getNamespace(null))) {
streamId = parser.getAttributeValue("", "id");
String reportedServerDomain = parser.getAttributeValue("", "from");
assert(config.getXMPPServiceDomain().equals(reportedServerDomain));
}
break;
case "error":
throw new StreamErrorException(PacketParserUtils.parseStreamError(parser));
case "features":
parseFeatures(parser);
break;
case "proceed":
try {
// Secure the connection by negotiating TLS
proceedTLSReceived();
// Send a new opening stream to the server
openStream();
}
catch (Exception e) {
// We report any failure regarding TLS in the second stage of XMPP
// connection establishment, namely the SASL authentication
saslFeatureReceived.reportFailure(new SmackException(e));
throw e;
}
break;
case "failure":
String namespace = parser.getNamespace(null);
switch (namespace) {
case "urn:ietf:params:xml:ns:xmpp-tls":
// TLS negotiation has failed. The server will close the connection
// TODO Parse failure stanza
throw new SmackException("TLS negotiation has failed");
case "http://jabber.org/protocol/compress":
// Stream compression has been denied. This is a recoverable
// situation. It is still possible to authenticate and
// use the connection but using an uncompressed connection
// TODO Parse failure stanza
compressSyncPoint.reportFailure(new SmackException(
"Could not establish compression"));
break;
case SaslStreamElements.NAMESPACE:
// SASL authentication has failed. The server may close the connection
// depending on the number of retries
final SASLFailure failure = PacketParserUtils.parseSASLFailure(parser);
getSASLAuthentication().authenticationFailed(failure);
break;
}
break;
case Challenge.ELEMENT:
// The server is challenging the SASL authentication made by the client
String challengeData = parser.nextText();
getSASLAuthentication().challengeReceived(challengeData);
break;
case Success.ELEMENT:
Success success = new Success(parser.nextText());
// We now need to bind a resource for the connection
// Open a new stream and wait for the response
openStream();
// The SASL authentication with the server was successful. The next step
// will be to bind the resource
getSASLAuthentication().authenticated(success);
break;
case Compressed.ELEMENT:
// Server confirmed that it's possible to use stream compression. Start
// stream compression
// Initialize the reader and writer with the new compressed version
initReaderAndWriter();
// Send a new opening stream to the server
openStream();
// Notify that compression is being used
compressSyncPoint.reportSuccess();
break;
case Enabled.ELEMENT:
Enabled enabled = ParseStreamManagement.enabled(parser);
if (enabled.isResumeSet()) {
smSessionId = enabled.getId();
if (StringUtils.isNullOrEmpty(smSessionId)) {
XMPPError.Builder builder = XMPPError.getBuilder(XMPPError.Condition.bad_request);
builder.setDescriptiveEnText("Stream Management 'enabled' element with resume attribute but without session id received");
XMPPErrorException xmppException = new XMPPErrorException(
builder);
smEnabledSyncPoint.reportFailure(xmppException);
throw xmppException;
}
smServerMaxResumptimTime = enabled.getMaxResumptionTime();
} else {
// Mark this a non-resumable stream by setting smSessionId to null
smSessionId = null;
}
clientHandledStanzasCount = 0;
smWasEnabledAtLeastOnce = true;
smEnabledSyncPoint.reportSuccess();
LOGGER.fine("Stream Management (XEP-198): succesfully enabled");
break;
case Failed.ELEMENT:
Failed failed = ParseStreamManagement.failed(parser);
XMPPError.Builder xmppError = XMPPError.getBuilder(failed.getXMPPErrorCondition());
XMPPException xmppException = new XMPPErrorException(xmppError);
// If only XEP-198 would specify different failure elements for the SM
// enable and SM resume failure case. But this is not the case, so we
// need to determine if this is a 'Failed' response for either 'Enable'
// or 'Resume'.
if (smResumedSyncPoint.requestSent()) {
smResumedSyncPoint.reportFailure(xmppException);
}
else {
if (!smEnabledSyncPoint.requestSent()) {
throw new IllegalStateException("Failed element received but SM was not previously enabled");
}
smEnabledSyncPoint.reportFailure(xmppException);
// Report success for last lastFeaturesReceived so that in case a
// failed resumption, we can continue with normal resource binding.
// See text of XEP-198 5. below Example 11.
lastFeaturesReceived.reportSuccess();
}
break;
case Resumed.ELEMENT:
Resumed resumed = ParseStreamManagement.resumed(parser);
if (!smSessionId.equals(resumed.getPrevId())) {
throw new StreamIdDoesNotMatchException(smSessionId, resumed.getPrevId());
}
// Mark SM as enabled and resumption as successful.
smResumedSyncPoint.reportSuccess();
smEnabledSyncPoint.reportSuccess();
// First, drop the stanzas already handled by the server
processHandledCount(resumed.getHandledCount());
// Then re-send what is left in the unacknowledged queue
List<Stanza> stanzasToResend = new ArrayList<>(unacknowledgedStanzas.size());
unacknowledgedStanzas.drainTo(stanzasToResend);
for (Stanza stanza : stanzasToResend) {
sendStanzaInternal(stanza);
}
// If there where stanzas resent, then request a SM ack for them.
// Writer's sendStreamElement() won't do it automatically based on
// predicates.
if (!stanzasToResend.isEmpty()) {
requestSmAcknowledgementInternal();
}
LOGGER.fine("Stream Management (XEP-198): Stream resumed");
break;
case AckAnswer.ELEMENT:
AckAnswer ackAnswer = ParseStreamManagement.ackAnswer(parser);
processHandledCount(ackAnswer.getHandledCount());
break;
case AckRequest.ELEMENT:
ParseStreamManagement.ackRequest(parser);
if (smEnabledSyncPoint.wasSuccessful()) {
sendSmAcknowledgementInternal();
} else {
LOGGER.warning("SM Ack Request received while SM is not enabled");
}
break;
default:
LOGGER.warning("Unknown top level stream element: " + name);
break;
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("stream")) {
if (!parser.getNamespace().equals("http://etherx.jabber.org/streams")) {
LOGGER.warning(XMPPTCPConnection.this + " </stream> but different namespace " + parser.getNamespace());
break;
}
// Check if the queue was already shut down before reporting success on closing stream tag
// received. This avoids a race if there is a disconnect(), followed by a connect(), which
// did re-start the queue again, causing this writer to assume that the queue is not
// shutdown, which results in a call to disconnect().
final boolean queueWasShutdown = packetWriter.queue.isShutdown();
closingStreamReceived.reportSuccess();
if (queueWasShutdown) {
// We received a closing stream element *after* we initiated the
// termination of the session by sending a closing stream element to
// the server first
return;
} else {
// We received a closing stream element from the server without us
// sending a closing stream element first. This means that the
// server wants to terminate the session, therefore disconnect
// the connection
LOGGER.info(XMPPTCPConnection.this
+ " received closing </stream> element."
+ " Server wants to terminate the connection, calling disconnect()");
disconnect();
}
}
break;
case XmlPullParser.END_DOCUMENT:
// END_DOCUMENT only happens in an error case, as otherwise we would see a
// closing stream element before.
throw new SmackException(
"Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element");
}
eventType = parser.next();
}
}
catch (Exception e) {
closingStreamReceived.reportFailure(e);
// The exception can be ignored if the the connection is 'done'
// or if the it was caused because the socket got closed
if (!(done || packetWriter.queue.isShutdown())) {
// Close the connection and notify connection listeners of the
// error.
notifyConnectionError(e);
}
}
}
}
protected class PacketWriter {
public static final int QUEUE_SIZE = XMPPTCPConnection.QUEUE_SIZE;
private final ArrayBlockingQueueWithShutdown<Element> queue = new ArrayBlockingQueueWithShutdown<Element>(
QUEUE_SIZE, true);
/**
* Needs to be protected for unit testing purposes.
*/
protected SynchronizationPoint<NoResponseException> shutdownDone = new SynchronizationPoint<NoResponseException>(
XMPPTCPConnection.this, "shutdown completed");
/**
* If set, the stanza(/packet) writer is shut down
*/
protected volatile Long shutdownTimestamp = null;
private volatile boolean instantShutdown;
/**
* True if some preconditions are given to start the bundle and defer mechanism.
* <p>
* This will likely get set to true right after the start of the writer thread, because
* {@link #nextStreamElement()} will check if {@link queue} is empty, which is probably the case, and then set
* this field to true.
* </p>
*/
private boolean shouldBundleAndDefer;
/**
* Initializes the writer in order to be used. It is called at the first connection and also
* is invoked if the connection is disconnected by an error.
*/
void init() {
shutdownDone.init();
shutdownTimestamp = null;
if (unacknowledgedStanzas != null) {
// It's possible that there are new stanzas in the writer queue that
// came in while we were disconnected but resumable, drain those into
// the unacknowledged queue so that they get resent now
drainWriterQueueToUnacknowledgedStanzas();
}
queue.start();
Async.go(new Runnable() {
@Override
public void run() {
writePackets();
}
}, "Smack Packet Writer (" + getConnectionCounter() + ")");
}
private boolean done() {
return shutdownTimestamp != null;
}
protected void throwNotConnectedExceptionIfDoneAndResumptionNotPossible() throws NotConnectedException {
final boolean done = done();
if (done) {
final boolean smResumptionPossbile = isSmResumptionPossible();
// Don't throw a NotConnectedException is there is an resumable stream available
if (!smResumptionPossbile) {
throw new NotConnectedException(XMPPTCPConnection.this, "done=" + done
+ " smResumptionPossible=" + smResumptionPossbile);
}
}
}
/**
* Sends the specified element to the server.
*
* @param element the element to send.
* @throws NotConnectedException
* @throws InterruptedException
*/
protected void sendStreamElement(Element element) throws NotConnectedException, InterruptedException {
throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
try {
queue.put(element);
}
catch (InterruptedException e) {
// put() may throw an InterruptedException for two reasons:
// 1. If the queue was shut down
// 2. If the thread was interrupted
// so we have to check which is the case
throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
// If the method above did not throw, then the sending thread was interrupted
throw e;
}
}
/**
* Shuts down the stanza(/packet) writer. Once this method has been called, no further
* packets will be written to the server.
* @throws InterruptedException
*/
void shutdown(boolean instant) {
instantShutdown = instant;
queue.shutdown();
shutdownTimestamp = System.currentTimeMillis();
try {
shutdownDone.checkIfSuccessOrWait();
}
catch (NoResponseException | InterruptedException e) {
LOGGER.log(Level.WARNING, "shutdownDone was not marked as successful by the writer thread", e);
}
}
/**
* Maybe return the next available element from the queue for writing. If the queue is shut down <b>or</b> a
* spurious interrupt occurs, <code>null</code> is returned. So it is important to check the 'done' condition in
* that case.
*
* @return the next element for writing or null.
*/
private Element nextStreamElement() {
// It is important the we check if the queue is empty before removing an element from it
if (queue.isEmpty()) {
shouldBundleAndDefer = true;
}
Element packet = null;
try {
packet = queue.take();
}
catch (InterruptedException e) {
if (!queue.isShutdown()) {
// Users shouldn't try to interrupt the packet writer thread
LOGGER.log(Level.WARNING, "Packet writer thread was interrupted. Don't do that. Use disconnect() instead.", e);
}
}
return packet;
}
private void writePackets() {
Exception writerException = null;
try {
openStream();
initalOpenStreamSend.reportSuccess();
// Write out packets from the queue.
while (!done()) {
Element element = nextStreamElement();
if (element == null) {
continue;
}
// Get a local version of the bundle and defer callback, in case it's unset
// between the null check and the method invocation
final BundleAndDeferCallback localBundleAndDeferCallback = bundleAndDeferCallback;
// If the preconditions are given (e.g. bundleAndDefer callback is set, queue is
// empty), then we could wait a bit for further stanzas attempting to decrease
// our energy consumption
if (localBundleAndDeferCallback != null && isAuthenticated() && shouldBundleAndDefer) {
// Reset shouldBundleAndDefer to false, nextStreamElement() will set it to true once the
// queue is empty again.
shouldBundleAndDefer = false;
final AtomicBoolean bundlingAndDeferringStopped = new AtomicBoolean();
final int bundleAndDeferMillis = localBundleAndDeferCallback.getBundleAndDeferMillis(new BundleAndDefer(
bundlingAndDeferringStopped));
if (bundleAndDeferMillis > 0) {
long remainingWait = bundleAndDeferMillis;
final long waitStart = System.currentTimeMillis();
synchronized (bundlingAndDeferringStopped) {
while (!bundlingAndDeferringStopped.get() && remainingWait > 0) {
bundlingAndDeferringStopped.wait(remainingWait);
remainingWait = bundleAndDeferMillis
- (System.currentTimeMillis() - waitStart);
}
}
}
}
Stanza packet = null;
if (element instanceof Stanza) {
packet = (Stanza) element;
}
else if (element instanceof Enable) {
// The client needs to add messages to the unacknowledged stanzas queue
// right after it sent 'enabled'. Stanza will be added once
// unacknowledgedStanzas is not null.
unacknowledgedStanzas = new ArrayBlockingQueue<>(QUEUE_SIZE);
}
// Check if the stream element should be put to the unacknowledgedStanza
// queue. Note that we can not do the put() in sendStanzaInternal() and the
// packet order is not stable at this point (sendStanzaInternal() can be
// called concurrently).
if (unacknowledgedStanzas != null && packet != null) {
// If the unacknowledgedStanza queue is nearly full, request an new ack
// from the server in order to drain it
if (unacknowledgedStanzas.size() == 0.8 * XMPPTCPConnection.QUEUE_SIZE) {
writer.write(AckRequest.INSTANCE.toXML().toString());
writer.flush();
}
try {
// It is important the we put the stanza in the unacknowledged stanza
// queue before we put it on the wire
unacknowledgedStanzas.put(packet);
}
catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
CharSequence elementXml = element.toXML();
if (elementXml instanceof XmlStringBuilder) {
((XmlStringBuilder) elementXml).write(writer);
}
else {
writer.write(elementXml.toString());
}
if (queue.isEmpty()) {
writer.flush();
}
if (packet != null) {
firePacketSendingListeners(packet);
}
}
if (!instantShutdown) {
// Flush out the rest of the queue.
try {
while (!queue.isEmpty()) {
Element packet = queue.remove();
writer.write(packet.toXML().toString());
}
writer.flush();
}
catch (Exception e) {
LOGGER.log(Level.WARNING,
"Exception flushing queue during shutdown, ignore and continue",
e);
}
// Close the stream.
try {
writer.write("</stream:stream>");
writer.flush();
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception writing closing stream element", e);
}
// Delete the queue contents (hopefully nothing is left).
queue.clear();
} else if (instantShutdown && isSmEnabled()) {
// This was an instantShutdown and SM is enabled, drain all remaining stanzas
// into the unacknowledgedStanzas queue
drainWriterQueueToUnacknowledgedStanzas();
}
// Do *not* close the writer here, as it will cause the socket
// to get closed. But we may want to receive further stanzas
// until the closing stream tag is received. The socket will be
// closed in shutdown().
}
catch (Exception e) {
// The exception can be ignored if the the connection is 'done'
// or if the it was caused because the socket got closed
if (!(done() || queue.isShutdown())) {
writerException = e;
} else {
LOGGER.log(Level.FINE, "Ignoring Exception in writePackets()", e);
}
} finally {
LOGGER.fine("Reporting shutdownDone success in writer thread");
shutdownDone.reportSuccess();
}
// Delay notifyConnectionError after shutdownDone has been reported in the finally block.
if (writerException != null) {
notifyConnectionError(writerException);
}
}
private void drainWriterQueueToUnacknowledgedStanzas() {
List<Element> elements = new ArrayList<Element>(queue.size());
queue.drainTo(elements);
for (Element element : elements) {
if (element instanceof Stanza) {
unacknowledgedStanzas.add((Stanza) element);
}
}
}
}
/**
* Set if Stream Management should be used by default for new connections.
*
* @param useSmDefault true to use Stream Management for new connections.
*/
public static void setUseStreamManagementDefault(boolean useSmDefault) {
XMPPTCPConnection.useSmDefault = useSmDefault;
}
/**
* Set if Stream Management resumption should be used by default for new connections.
*
* @param useSmResumptionDefault true to use Stream Management resumption for new connections.
* @deprecated use {@link #setUseStreamManagementResumptionDefault(boolean)} instead.
*/
@Deprecated
public static void setUseStreamManagementResumptiodDefault(boolean useSmResumptionDefault) {
setUseStreamManagementResumptionDefault(useSmResumptionDefault);
}
/**
* Set if Stream Management resumption should be used by default for new connections.
*
* @param useSmResumptionDefault true to use Stream Management resumption for new connections.
*/
public static void setUseStreamManagementResumptionDefault(boolean useSmResumptionDefault) {
if (useSmResumptionDefault) {
// Also enable SM is resumption is enabled
setUseStreamManagementDefault(useSmResumptionDefault);
}
XMPPTCPConnection.useSmResumptionDefault = useSmResumptionDefault;
}
/**
* Set if Stream Management should be used if supported by the server.
*
* @param useSm true to use Stream Management.
*/
public void setUseStreamManagement(boolean useSm) {
this.useSm = useSm;
}
/**
* Set if Stream Management resumption should be used if supported by the server.
*
* @param useSmResumption true to use Stream Management resumption.
*/
public void setUseStreamManagementResumption(boolean useSmResumption) {
if (useSmResumption) {
// Also enable SM is resumption is enabled
setUseStreamManagement(useSmResumption);
}
this.useSmResumption = useSmResumption;
}
/**
* Set the preferred resumption time in seconds.
* @param resumptionTime the preferred resumption time in seconds
*/
public void setPreferredResumptionTime(int resumptionTime) {
smClientMaxResumptionTime = resumptionTime;
}
/**
* Add a predicate for Stream Management acknowledgment requests.
* <p>
* Those predicates are used to determine when a Stream Management acknowledgement request is send to the server.
* Some pre-defined predicates are found in the <code>org.jivesoftware.smack.sm.predicates</code> package.
* </p>
* <p>
* If not predicate is configured, the {@link Predicate#forMessagesOrAfter5Stanzas()} will be used.
* </p>
*
* @param predicate the predicate to add.
* @return if the predicate was not already active.
*/
public boolean addRequestAckPredicate(StanzaFilter predicate) {
synchronized (requestAckPredicates) {
return requestAckPredicates.add(predicate);
}
}
/**
* Remove the given predicate for Stream Management acknowledgment request.
* @param predicate the predicate to remove.
* @return true if the predicate was removed.
*/
public boolean removeRequestAckPredicate(StanzaFilter predicate) {
synchronized (requestAckPredicates) {
return requestAckPredicates.remove(predicate);
}
}
/**
* Remove all predicates for Stream Management acknowledgment requests.
*/
public void removeAllRequestAckPredicates() {
synchronized (requestAckPredicates) {
requestAckPredicates.clear();
}
}
/**
* Send an unconditional Stream Management acknowledgement request to the server.
*
* @throws StreamManagementNotEnabledException if Stream Mangement is not enabled.
* @throws NotConnectedException if the connection is not connected.
* @throws InterruptedException
*/
public void requestSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException, InterruptedException {
if (!isSmEnabled()) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
requestSmAcknowledgementInternal();
}
private void requestSmAcknowledgementInternal() throws NotConnectedException, InterruptedException {
packetWriter.sendStreamElement(AckRequest.INSTANCE);
}
/**
* Send a unconditional Stream Management acknowledgment to the server.
* <p>
* See <a href="http://xmpp.org/extensions/xep-0198.html#acking">XEP-198: Stream Management § 4. Acks</a>:
* "Either party MAY send an <a/> element at any time (e.g., after it has received a certain number of stanzas,
* or after a certain period of time), even if it has not received an <r/> element from the other party."
* </p>
*
* @throws StreamManagementNotEnabledException if Stream Management is not enabled.
* @throws NotConnectedException if the connection is not connected.
* @throws InterruptedException
*/
public void sendSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException, InterruptedException {
if (!isSmEnabled()) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
sendSmAcknowledgementInternal();
}
private void sendSmAcknowledgementInternal() throws NotConnectedException, InterruptedException {
packetWriter.sendStreamElement(new AckAnswer(clientHandledStanzasCount));
}
/**
* Add a Stanza acknowledged listener.
* <p>
* Those listeners will be invoked every time a Stanza has been acknowledged by the server. The will not get
* automatically removed. Consider using {@link #addStanzaIdAcknowledgedListener(String, StanzaListener)} when
* possible.
* </p>
*
* @param listener the listener to add.
*/
public void addStanzaAcknowledgedListener(StanzaListener listener) {
stanzaAcknowledgedListeners.add(listener);
}
/**
* Remove the given Stanza acknowledged listener.
*
* @param listener the listener.
* @return true if the listener was removed.
*/
public boolean removeStanzaAcknowledgedListener(StanzaListener listener) {
return stanzaAcknowledgedListeners.remove(listener);
}
/**
* Remove all stanza acknowledged listeners.
*/
public void removeAllStanzaAcknowledgedListeners() {
stanzaAcknowledgedListeners.clear();
}
/**
* Add a new Stanza ID acknowledged listener for the given ID.
* <p>
* The listener will be invoked if the stanza with the given ID was acknowledged by the server. It will
* automatically be removed after the listener was run.
* </p>
*
* @param id the stanza ID.
* @param listener the listener to invoke.
* @return the previous listener for this stanza ID or null.
* @throws StreamManagementNotEnabledException if Stream Management is not enabled.
*/
public StanzaListener addStanzaIdAcknowledgedListener(final String id, StanzaListener listener) throws StreamManagementNotEnabledException {
// Prevent users from adding callbacks that will never get removed
if (!smWasEnabledAtLeastOnce) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
// Remove the listener after max. 12 hours
final int removeAfterSeconds = Math.min(getMaxSmResumptionTime(), 12 * 60 * 60);
schedule(new Runnable() {
@Override
public void run() {
stanzaIdAcknowledgedListeners.remove(id);
}
}, removeAfterSeconds, TimeUnit.SECONDS);
return stanzaIdAcknowledgedListeners.put(id, listener);
}
/**
* Remove the Stanza ID acknowledged listener for the given ID.
*
* @param id the stanza ID.
* @return true if the listener was found and removed, false otherwise.
*/
public StanzaListener removeStanzaIdAcknowledgedListener(String id) {
return stanzaIdAcknowledgedListeners.remove(id);
}
/**
* Removes all Stanza ID acknowledged listeners.
*/
public void removeAllStanzaIdAcknowledgedListeners() {
stanzaIdAcknowledgedListeners.clear();
}
/**
* Returns true if Stream Management is supported by the server.
*
* @return true if Stream Management is supported by the server.
*/
public boolean isSmAvailable() {
return hasFeature(StreamManagementFeature.ELEMENT, StreamManagement.NAMESPACE);
}
/**
* Returns true if Stream Management was successfully negotiated with the server.
*
* @return true if Stream Management was negotiated.
*/
public boolean isSmEnabled() {
return smEnabledSyncPoint.wasSuccessful();
}
/**
* Returns true if the stream was successfully resumed with help of Stream Management.
*
* @return true if the stream was resumed.
*/
public boolean streamWasResumed() {
return smResumedSyncPoint.wasSuccessful();
}
/**
* Returns true if the connection is disconnected by a Stream resumption via Stream Management is possible.
*
* @return true if disconnected but resumption possible.
*/
public boolean isDisconnectedButSmResumptionPossible() {
return disconnectedButResumeable && isSmResumptionPossible();
}
/**
* Returns true if the stream is resumable.
*
* @return true if the stream is resumable.
*/
public boolean isSmResumptionPossible() {
// There is no resumable stream available
if (smSessionId == null)
return false;
final Long shutdownTimestamp = packetWriter.shutdownTimestamp;
// Seems like we are already reconnected, report true
if (shutdownTimestamp == null) {
return true;
}
// See if resumption time is over
long current = System.currentTimeMillis();
long maxResumptionMillies = ((long) getMaxSmResumptionTime()) * 1000;
if (current > shutdownTimestamp + maxResumptionMillies) {
// Stream resumption is *not* possible if the current timestamp is greater then the greatest timestamp where
// resumption is possible
return false;
} else {
return true;
}
}
/**
* Drop the stream management state. Sets {@link #smSessionId} and
* {@link #unacknowledgedStanzas} to <code>null</code>.
*/
private void dropSmState() {
// clientHandledCount and serverHandledCount will be reset on <enable/> and <enabled/>
// respective. No need to reset them here.
smSessionId = null;
unacknowledgedStanzas = null;
}
/**
* Get the maximum resumption time in seconds after which a managed stream can be resumed.
* <p>
* This method will return {@link Integer#MAX_VALUE} if neither the client nor the server specify a maximum
* resumption time. Be aware of integer overflows when using this value, e.g. do not add arbitrary values to it
* without checking for overflows before.
* </p>
*
* @return the maximum resumption time in seconds or {@link Integer#MAX_VALUE} if none set.
*/
public int getMaxSmResumptionTime() {
int clientResumptionTime = smClientMaxResumptionTime > 0 ? smClientMaxResumptionTime : Integer.MAX_VALUE;
int serverResumptionTime = smServerMaxResumptimTime > 0 ? smServerMaxResumptimTime : Integer.MAX_VALUE;
return Math.min(clientResumptionTime, serverResumptionTime);
}
private void processHandledCount(long handledCount) throws StreamManagementCounterError {
long ackedStanzasCount = SMUtils.calculateDelta(handledCount, serverHandledStanzasCount);
final List<Stanza> ackedStanzas = new ArrayList<Stanza>(
ackedStanzasCount <= Integer.MAX_VALUE ? (int) ackedStanzasCount
: Integer.MAX_VALUE);
for (long i = 0; i < ackedStanzasCount; i++) {
Stanza ackedStanza = unacknowledgedStanzas.poll();
// If the server ack'ed a stanza, then it must be in the
// unacknowledged stanza queue. There can be no exception.
if (ackedStanza == null) {
throw new StreamManagementCounterError(handledCount, serverHandledStanzasCount,
ackedStanzasCount, ackedStanzas);
}
ackedStanzas.add(ackedStanza);
}
boolean atLeastOneStanzaAcknowledgedListener = false;
if (!stanzaAcknowledgedListeners.isEmpty()) {
// If stanzaAcknowledgedListeners is not empty, the we have at least one
atLeastOneStanzaAcknowledgedListener = true;
}
else {
// Otherwise we look for a matching id in the stanza *id* acknowledged listeners
for (Stanza ackedStanza : ackedStanzas) {
String id = ackedStanza.getStanzaId();
if (id != null && stanzaIdAcknowledgedListeners.containsKey(id)) {
atLeastOneStanzaAcknowledgedListener = true;
break;
}
}
}
// Only spawn a new thread if there is a chance that some listener is invoked
if (atLeastOneStanzaAcknowledgedListener) {
asyncGo(new Runnable() {
@Override
public void run() {
for (Stanza ackedStanza : ackedStanzas) {
for (StanzaListener listener : stanzaAcknowledgedListeners) {
try {
listener.processPacket(ackedStanza);
}
catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.FINER, "Received exception", e);
}
}
String id = ackedStanza.getStanzaId();
if (StringUtils.isNullOrEmpty(id)) {
continue;
}
StanzaListener listener = stanzaIdAcknowledgedListeners.remove(id);
if (listener != null) {
try {
listener.processPacket(ackedStanza);
}
catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.FINER, "Received exception", e);
}
}
}
}
});
}
serverHandledStanzasCount = handledCount;
}
/**
* Set the default bundle and defer callback used for new connections.
*
* @param defaultBundleAndDeferCallback
* @see BundleAndDeferCallback
* @since 4.1
*/
public static void setDefaultBundleAndDeferCallback(BundleAndDeferCallback defaultBundleAndDeferCallback) {
XMPPTCPConnection.defaultBundleAndDeferCallback = defaultBundleAndDeferCallback;
}
/**
* Set the bundle and defer callback used for this connection.
* <p>
* You can use <code>null</code> as argument to reset the callback. Outgoing stanzas will then
* no longer get deferred.
* </p>
*
* @param bundleAndDeferCallback the callback or <code>null</code>.
* @see BundleAndDeferCallback
* @since 4.1
*/
public void setBundleandDeferCallback(BundleAndDeferCallback bundleAndDeferCallback) {
this.bundleAndDeferCallback = bundleAndDeferCallback;
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_4769_1
|
crossvul-java_data_good_2300_1
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.servlet;
import java.util.function.Consumer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jboss.weld.context.AbstractConversationContext;
import org.jboss.weld.context.ConversationContext;
import org.jboss.weld.context.http.HttpConversationContext;
import org.jboss.weld.context.http.LazyHttpConversationContextImpl;
import org.jboss.weld.event.FastEvent;
import org.jboss.weld.literal.DestroyedLiteral;
import org.jboss.weld.literal.InitializedLiteral;
import org.jboss.weld.logging.ConversationLogger;
import org.jboss.weld.logging.ServletLogger;
import org.jboss.weld.manager.BeanManagerImpl;
/**
* This component takes care of activation/deactivation of the conversation context for a servlet request.
*
* @see ConversationFilter
* @see org.jboss.weld.servlet.WeldInitialListener
*
* @author Jozef Hartinger
* @author Marko Luksa
*
*/
public class ConversationContextActivator {
private static final String NO_CID = "nocid";
private static final String CONVERSATION_PROPAGATION = "conversationPropagation";
private static final String CONVERSATION_PROPAGATION_NONE = "none";
private static final String CONTEXT_ACTIVATED_IN_REQUEST = ConversationContextActivator.class.getName() + "CONTEXT_ACTIVATED_IN_REQUEST";
private final BeanManagerImpl beanManager;
private HttpConversationContext httpConversationContextCache;
private final FastEvent<HttpServletRequest> conversationInitializedEvent;
private final FastEvent<HttpServletRequest> conversationDestroyedEvent;
private final Consumer<HttpServletRequest> lazyInitializationCallback;
private final boolean lazy;
protected ConversationContextActivator(BeanManagerImpl beanManager, boolean lazy) {
this.beanManager = beanManager;
conversationInitializedEvent = FastEvent.of(HttpServletRequest.class, beanManager, InitializedLiteral.CONVERSATION);
conversationDestroyedEvent = FastEvent.of(HttpServletRequest.class, beanManager, DestroyedLiteral.CONVERSATION);
lazyInitializationCallback = lazy ? conversationInitializedEvent::fire : null;
this.lazy = lazy;
}
private HttpConversationContext httpConversationContext() {
if (httpConversationContextCache == null) {
this.httpConversationContextCache = beanManager.instance().select(HttpConversationContext.class).get();
}
return httpConversationContextCache;
}
public void startConversationContext(HttpServletRequest request) {
associateConversationContext(request);
activateConversationContext(request);
}
public void stopConversationContext(HttpServletRequest request) {
deactivateConversationContext(request);
}
// Conversation handling
protected void activateConversationContext(HttpServletRequest request) {
HttpConversationContext conversationContext = httpConversationContext();
/*
* Don't try to reactivate the ConversationContext if we have already activated it for this request WELD-877
*/
if (!isContextActivatedInRequest(request)) {
setContextActivatedInRequest(request);
activate(conversationContext, request);
} else {
/*
* We may have previously been associated with a ConversationContext, but the reference to that context may have been lost during a Servlet forward
* WELD-877
*/
conversationContext.dissociate(request);
conversationContext.associate(request);
activate(conversationContext, request);
}
}
private void activate(HttpConversationContext conversationContext, final HttpServletRequest request) {
if (lazy && conversationContext instanceof LazyHttpConversationContextImpl) {
LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext;
// Activation API should be improved so that it's possible to pass a callback for later execution
lazyConversationContext.activate(lazyInitializationCallback);
} else {
String cid = determineConversationId(request, conversationContext.getParameterName());
conversationContext.activate(cid);
if (cid == null) { // transient conversation
conversationInitializedEvent.fire(request);
}
}
}
protected void associateConversationContext(HttpServletRequest request) {
httpConversationContext().associate(request);
}
private void setContextActivatedInRequest(HttpServletRequest request) {
request.setAttribute(CONTEXT_ACTIVATED_IN_REQUEST, true);
}
private boolean isContextActivatedInRequest(HttpServletRequest request) {
Object result = request.getAttribute(CONTEXT_ACTIVATED_IN_REQUEST);
if (result == null) {
return false;
}
return (Boolean) result;
}
protected void deactivateConversationContext(HttpServletRequest request) {
try {
ConversationContext conversationContext = httpConversationContext();
if (conversationContext.isActive()) {
// Only deactivate the context if one is already active, otherwise we get Exceptions
if (conversationContext instanceof LazyHttpConversationContextImpl) {
LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext;
if (!lazyConversationContext.isInitialized()) {
// if this lazy conversation has not been touched yet, just deactivate it
lazyConversationContext.deactivate();
return;
}
}
boolean isTransient = conversationContext.getCurrentConversation().isTransient();
if (ConversationLogger.LOG.isTraceEnabled()) {
if (isTransient) {
ConversationLogger.LOG.cleaningUpTransientConversation();
} else {
ConversationLogger.LOG.cleaningUpConversation(conversationContext.getCurrentConversation().getId());
}
}
conversationContext.invalidate();
conversationContext.deactivate();
if (isTransient) {
conversationDestroyedEvent.fire(request);
}
}
} catch (Exception e) {
ServletLogger.LOG.unableToDeactivateContext(httpConversationContext(), request);
ServletLogger.LOG.catchingDebug(e);
}
}
protected void disassociateConversationContext(HttpServletRequest request) {
try {
httpConversationContext().dissociate(request);
} catch (Exception e) {
ServletLogger.LOG.unableToDissociateContext(httpConversationContext(), request);
ServletLogger.LOG.catchingDebug(e);
}
}
public void sessionCreated(HttpSession session) {
HttpConversationContext httpConversationContext = httpConversationContext();
if (httpConversationContext instanceof AbstractConversationContext) {
AbstractConversationContext<?, ?> abstractConversationContext = (AbstractConversationContext<?, ?>) httpConversationContext;
abstractConversationContext.sessionCreated();
}
}
public static String determineConversationId(HttpServletRequest request, String parameterName) {
if (request == null) {
throw ConversationLogger.LOG.mustCallAssociateBeforeActivate();
}
if (request.getParameter(NO_CID) != null) {
return null; // ignore cid; WELD-919
}
if (CONVERSATION_PROPAGATION_NONE.equals(request.getParameter(CONVERSATION_PROPAGATION))) {
return null; // conversationPropagation=none (CDI-135)
}
String cidName = parameterName;
String cid = request.getParameter(cidName);
ConversationLogger.LOG.foundConversationFromRequest(cid);
return cid;
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_2300_1
|
crossvul-java_data_bad_4769_0
|
/**
*
* Copyright 2009 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;
import org.jivesoftware.smack.SmackException.SecurityRequiredException;
import org.jivesoftware.smack.XMPPException.StreamErrorException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.compress.packet.Compress;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.debugger.SmackDebugger;
import org.jivesoftware.smack.filter.IQReplyFilter;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.filter.StanzaIdFilter;
import org.jivesoftware.smack.iqrequest.IQRequestHandler;
import org.jivesoftware.smack.packet.Bind;
import org.jivesoftware.smack.packet.ErrorIQ;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Mechanisms;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Session;
import org.jivesoftware.smack.packet.StartTls;
import org.jivesoftware.smack.packet.Nonza;
import org.jivesoftware.smack.packet.StreamError;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.sasl.core.SASLAnonymous;
import org.jivesoftware.smack.util.BoundedThreadPoolExecutor;
import org.jivesoftware.smack.util.DNSUtil;
import org.jivesoftware.smack.util.Objects;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.util.ParserUtils;
import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.EntityFullJid;
import org.jxmpp.jid.Jid;
import org.jxmpp.jid.parts.Resourcepart;
import org.jxmpp.util.XmppStringUtils;
import org.xmlpull.v1.XmlPullParser;
public abstract class AbstractXMPPConnection implements XMPPConnection {
private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName());
/**
* Counter to uniquely identify connections that are created.
*/
private final static AtomicInteger connectionCounter = new AtomicInteger(0);
static {
// Ensure the SmackConfiguration class is loaded by calling a method in it.
SmackConfiguration.getVersion();
}
/**
* A collection of ConnectionListeners which listen for connection closing
* and reconnection events.
*/
protected final Set<ConnectionListener> connectionListeners =
new CopyOnWriteArraySet<ConnectionListener>();
/**
* A collection of PacketCollectors which collects packets for a specified filter
* and perform blocking and polling operations on the result queue.
* <p>
* We use a ConcurrentLinkedQueue here, because its Iterator is weakly
* consistent and we want {@link #invokePacketCollectors(Stanza)} for-each
* loop to be lock free. As drawback, removing a PacketCollector is O(n).
* The alternative would be a synchronized HashSet, but this would mean a
* synchronized block around every usage of <code>collectors</code>.
* </p>
*/
private final Collection<PacketCollector> collectors = new ConcurrentLinkedQueue<PacketCollector>();
/**
* List of PacketListeners that will be notified synchronously when a new stanza(/packet) was received.
*/
private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>();
/**
* List of PacketListeners that will be notified asynchronously when a new stanza(/packet) was received.
*/
private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>();
/**
* List of PacketListeners that will be notified when a new stanza(/packet) was sent.
*/
private final Map<StanzaListener, ListenerWrapper> sendListeners =
new HashMap<StanzaListener, ListenerWrapper>();
/**
* List of PacketListeners that will be notified when a new stanza(/packet) is about to be
* sent to the server. These interceptors may modify the stanza(/packet) before it is being
* actually sent to the server.
*/
private final Map<StanzaListener, InterceptorWrapper> interceptors =
new HashMap<StanzaListener, InterceptorWrapper>();
protected final Lock connectionLock = new ReentrantLock();
protected final Map<String, ExtensionElement> streamFeatures = new HashMap<String, ExtensionElement>();
/**
* The full JID of the authenticated user, as returned by the resource binding response of the server.
* <p>
* It is important that we don't infer the user from the login() arguments and the configurations service name, as,
* for example, when SASL External is used, the username is not given to login but taken from the 'external'
* certificate.
* </p>
*/
protected EntityFullJid user;
protected boolean connected = false;
/**
* The stream ID, see RFC 6120 § 4.7.3
*/
protected String streamId;
/**
*
*/
private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout();
/**
* The SmackDebugger allows to log and debug XML traffic.
*/
protected SmackDebugger debugger = null;
/**
* The Reader which is used for the debugger.
*/
protected Reader reader;
/**
* The Writer which is used for the debugger.
*/
protected Writer writer;
/**
* Set to success if the last features stanza from the server has been parsed. A XMPP connection
* handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature
* stanza is send by the server. This is set to true once the last feature stanza has been
* parsed.
*/
protected final SynchronizationPoint<Exception> lastFeaturesReceived = new SynchronizationPoint<Exception>(
AbstractXMPPConnection.this, "last stream features received from server");
/**
* Set to success if the sasl feature has been received.
*/
protected final SynchronizationPoint<SmackException> saslFeatureReceived = new SynchronizationPoint<SmackException>(
AbstractXMPPConnection.this, "SASL mechanisms stream feature from server");
/**
* The SASLAuthentication manager that is responsible for authenticating with the server.
*/
protected final SASLAuthentication saslAuthentication;
/**
* A number to uniquely identify connections that are created. This is distinct from the
* connection ID, which is a value sent by the server once a connection is made.
*/
protected final int connectionCounterValue = connectionCounter.getAndIncrement();
/**
* Holds the initial configuration used while creating the connection.
*/
protected final ConnectionConfiguration config;
/**
* Defines how the from attribute of outgoing stanzas should be handled.
*/
private FromMode fromMode = FromMode.OMITTED;
protected XMPPInputOutputStream compressionHandler;
private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback();
/**
* ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is
* important that we use a <b>single threaded ExecutorService</b> in order to guarantee that the
* PacketListeners are invoked in the same order the stanzas arrived.
*/
private final BoundedThreadPoolExecutor executorService = new BoundedThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
100, new SmackExecutorThreadFactory(this, "Incoming Processor"));
/**
* This scheduled thread pool executor is used to remove pending callbacks.
*/
private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor(
new SmackExecutorThreadFactory(this, "Remove Callbacks"));
/**
* A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set
* them 'daemon'.
*/
private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool(
// @formatter:off
new SmackExecutorThreadFactory( // threadFactory
this,
"Cached Executor"
)
// @formatter:on
);
/**
* A executor service used to invoke the callbacks of synchronous stanza(/packet) listeners. We use a executor service to
* decouple incoming stanza processing from callback invocation. It is important that order of callback invocation
* is the same as the order of the incoming stanzas. Therefore we use a <i>single</i> threaded executor service.
*/
private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory(
this, "Single Threaded Executor"));
/**
* The used host to establish the connection to
*/
protected String host;
/**
* The used port to establish the connection to
*/
protected int port;
/**
* Flag that indicates if the user is currently authenticated with the server.
*/
protected boolean authenticated = false;
/**
* Flag that indicates if the user was authenticated with the server when the connection
* to the server was closed (abruptly or not).
*/
protected boolean wasAuthenticated = false;
private final Map<String, IQRequestHandler> setIqRequestHandler = new HashMap<>();
private final Map<String, IQRequestHandler> getIqRequestHandler = new HashMap<>();
/**
* Create a new XMPPConnection to an XMPP server.
*
* @param configuration The configuration which is used to establish the connection.
*/
protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
saslAuthentication = new SASLAuthentication(this, configuration);
config = configuration;
// Notify listeners that a new connection has been established
for (ConnectionCreationListener listener : XMPPConnectionRegistry.getConnectionCreationListeners()) {
listener.connectionCreated(this);
}
}
/**
* Get the connection configuration used by this connection.
*
* @return the connection configuration.
*/
public ConnectionConfiguration getConfiguration() {
return config;
}
@SuppressWarnings("deprecation")
@Override
public DomainBareJid getServiceName() {
return getXMPPServiceDomain();
}
@Override
public DomainBareJid getXMPPServiceDomain() {
if (xmppServiceDomain != null) {
return xmppServiceDomain;
}
return config.getXMPPServiceDomain();
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public abstract boolean isSecureConnection();
protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException;
@Override
public abstract void sendNonza(Nonza element) throws NotConnectedException, InterruptedException;
@Override
public abstract boolean isUsingCompression();
/**
* Establishes a connection to the XMPP server. It basically
* creates and maintains a connection to the server.
* <p>
* Listeners will be preserved from a previous connection.
* </p>
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException
* @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
* @throws InterruptedException
*/
public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException, InterruptedException {
// Check if not already connected
throwAlreadyConnectedExceptionIfAppropriate();
// Reset the connection state
saslAuthentication.init();
saslFeatureReceived.init();
lastFeaturesReceived.init();
streamId = null;
// Perform the actual connection to the XMPP service
connectInternal();
// Wait with SASL auth until the SASL mechanisms have been received
saslFeatureReceived.checkIfSuccessOrWaitOrThrow();
// Make note of the fact that we're now connected.
connected = true;
callConnectionConnectedListener();
return this;
}
/**
* Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
* way of XMPP connection establishment. Implementations are required to perform an automatic
* login if the previous connection state was logged (authenticated).
*
* @throws SmackException
* @throws IOException
* @throws XMPPException
* @throws InterruptedException
*/
protected abstract void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException;
private String usedUsername, usedPassword;
/**
* The resourcepart used for this connection. May not be the resulting resourcepart if it's null or overridden by the XMPP service.
*/
private Resourcepart usedResource;
/**
* Logs in to the server using the strongest SASL mechanism supported by
* the server. If more than the connection's default stanza(/packet) timeout elapses in each step of the
* authentication process without a response from the server, a
* {@link SmackException.NoResponseException} will be thrown.
* <p>
* Before logging in (i.e. authenticate) to the server the connection must be connected
* by calling {@link #connect}.
* </p>
* <p>
* It is possible to log in without sending an initial available presence by using
* {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}.
* Finally, if you want to not pass a password and instead use a more advanced mechanism
* while using SASL then you may be interested in using
* {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}.
* For more advanced login settings see {@link ConnectionConfiguration}.
* </p>
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException if an I/O error occurs during login.
* @throws InterruptedException
*/
public synchronized void login() throws XMPPException, SmackException, IOException, InterruptedException {
// The previously used username, password and resource take over precedence over the
// ones from the connection configuration
CharSequence username = usedUsername != null ? usedUsername : config.getUsername();
String password = usedPassword != null ? usedPassword : config.getPassword();
Resourcepart resource = usedResource != null ? usedResource : config.getResource();
login(username, password, resource);
}
/**
* Same as {@link #login(CharSequence, String, Resourcepart)}, but takes the resource from the connection
* configuration.
*
* @param username
* @param password
* @throws XMPPException
* @throws SmackException
* @throws IOException
* @throws InterruptedException
* @see #login
*/
public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException,
IOException, InterruptedException {
login(username, password, config.getResource());
}
/**
* Login with the given username (authorization identity). You may omit the password if a callback handler is used.
* If resource is null, then the server will generate one.
*
* @param username
* @param password
* @param resource
* @throws XMPPException
* @throws SmackException
* @throws IOException
* @throws InterruptedException
* @see #login
*/
public synchronized void login(CharSequence username, String password, Resourcepart resource) throws XMPPException,
SmackException, IOException, InterruptedException {
if (!config.allowNullOrEmptyUsername) {
StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty");
}
throwNotConnectedExceptionIfAppropriate("Did you call connect() before login()?");
throwAlreadyLoggedInExceptionIfAppropriate();
usedUsername = username != null ? username.toString() : null;
usedPassword = password;
usedResource = resource;
loginInternal(usedUsername, usedPassword, usedResource);
}
protected abstract void loginInternal(String username, String password, Resourcepart resource)
throws XMPPException, SmackException, IOException, InterruptedException;
@Override
public final boolean isConnected() {
return connected;
}
@Override
public final boolean isAuthenticated() {
return authenticated;
}
@Override
public final EntityFullJid getUser() {
return user;
}
@Override
public String getStreamId() {
if (!isConnected()) {
return null;
}
return streamId;
}
protected void bindResourceAndEstablishSession(Resourcepart resource) throws XMPPErrorException,
SmackException, InterruptedException {
// Wait until either:
// - the servers last features stanza has been parsed
// - the timeout occurs
LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
lastFeaturesReceived.checkIfSuccessOrWait();
if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
// Server never offered resource binding, which is REQURIED in XMPP client and
// server implementations as per RFC6120 7.2
throw new ResourceBindingNotOfferedException();
}
// Resource binding, see RFC6120 7.
// Note that we can not use IQReplyFilter here, since the users full JID is not yet
// available. It will become available right after the resource has been successfully bound.
Bind bindResource = Bind.newSet(resource);
PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
Bind response = packetCollector.nextResultOrThrow();
// Set the connections user to the result of resource binding. It is important that we don't infer the user
// from the login() arguments and the configurations service name, as, for example, when SASL External is used,
// the username is not given to login but taken from the 'external' certificate.
user = response.getJid();
xmppServiceDomain = user.asDomainBareJid();
Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE);
// Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
// For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
// TODO remove this suppression once "disable legacy session" code has been removed from Smack
@SuppressWarnings("deprecation")
boolean legacySessionDisabled = getConfiguration().isLegacySessionDisabled();
if (sessionFeature != null && !sessionFeature.isOptional() && !legacySessionDisabled) {
Session session = new Session();
packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session);
packetCollector.nextResultOrThrow();
}
}
protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException, InterruptedException {
// Indicate that we're now authenticated.
this.authenticated = true;
// If debugging is enabled, change the the debug window title to include the
// name we are now logged-in as.
// If DEBUG was set to true AFTER the connection was created the debugger
// will be null
if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user);
}
callConnectionAuthenticatedListener(resumed);
// Set presence to online. It is important that this is done after
// callConnectionAuthenticatedListener(), as this call will also
// eventually load the roster. And we should load the roster before we
// send the initial presence.
if (config.isSendPresence() && !resumed) {
sendStanza(new Presence(Presence.Type.available));
}
}
@Override
public final boolean isAnonymous() {
return isAuthenticated() && SASLAnonymous.NAME.equals(getUsedSaslMechansism());
}
/**
* Get the name of the SASL mechanism that was used to authenticate this connection. This returns the name of
* mechanism which was used the last time this conneciton was authenticated, and will return <code>null</code> if
* this connection was not authenticated before.
*
* @return the name of the used SASL mechanism.
* @since 4.2
*/
public final String getUsedSaslMechansism() {
return saslAuthentication.getNameOfLastUsedSaslMechansism();
}
private DomainBareJid xmppServiceDomain;
protected List<HostAddress> hostAddresses;
/**
* Populates {@link #hostAddresses} with at least one host address.
*
* @return a list of host addresses where DNS (SRV) RR resolution failed.
*/
protected List<HostAddress> populateHostAddresses() {
List<HostAddress> failedAddresses = new LinkedList<>();
// N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName
if (config.host != null) {
hostAddresses = new ArrayList<HostAddress>(1);
HostAddress hostAddress = DNSUtil.getDNSResolver().lookupHostAddress(config.host, failedAddresses, config.getDnssecMode());
hostAddresses.add(hostAddress);
} else {
hostAddresses = DNSUtil.resolveXMPPServiceDomain(config.getXMPPServiceDomain().toString(), failedAddresses, config.getDnssecMode());
}
// If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the
// config.host one or the host representing the service name by DNSUtil
assert(!hostAddresses.isEmpty());
return failedAddresses;
}
protected Lock getConnectionLock() {
return connectionLock;
}
protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
throwNotConnectedExceptionIfAppropriate(null);
}
protected void throwNotConnectedExceptionIfAppropriate(String optionalHint) throws NotConnectedException {
if (!isConnected()) {
throw new NotConnectedException(optionalHint);
}
}
protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
if (isConnected()) {
throw new AlreadyConnectedException();
}
}
protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
if (isAuthenticated()) {
throw new AlreadyLoggedInException();
}
}
@Deprecated
@Override
public void sendPacket(Stanza packet) throws NotConnectedException, InterruptedException {
sendStanza(packet);
}
@Override
public void sendStanza(Stanza stanza) throws NotConnectedException, InterruptedException {
Objects.requireNonNull(stanza, "Stanza must not be null");
assert(stanza instanceof Message || stanza instanceof Presence || stanza instanceof IQ);
throwNotConnectedExceptionIfAppropriate();
switch (fromMode) {
case OMITTED:
stanza.setFrom((Jid) null);
break;
case USER:
stanza.setFrom(getUser());
break;
case UNCHANGED:
default:
break;
}
// Invoke interceptors for the new stanza that is about to be sent. Interceptors may modify
// the content of the stanza.
firePacketInterceptors(stanza);
sendStanzaInternal(stanza);
}
/**
* Returns the SASLAuthentication manager that is responsible for authenticating with
* the server.
*
* @return the SASLAuthentication manager that is responsible for authenticating with
* the server.
*/
protected SASLAuthentication getSASLAuthentication() {
return saslAuthentication;
}
/**
* Closes the connection by setting presence to unavailable then closing the connection to
* the XMPP server. The XMPPConnection can still be used for connecting to the server
* again.
*
*/
public void disconnect() {
try {
disconnect(new Presence(Presence.Type.unavailable));
}
catch (NotConnectedException e) {
LOGGER.log(Level.FINEST, "Connection is already disconnected", e);
}
}
/**
* Closes the connection. A custom unavailable presence is sent to the server, followed
* by closing the stream. The XMPPConnection can still be used for connecting to the server
* again. A custom unavailable presence is useful for communicating offline presence
* information such as "On vacation". Typically, just the status text of the presence
* stanza(/packet) is set with online information, but most XMPP servers will deliver the full
* presence stanza(/packet) with whatever data is set.
*
* @param unavailablePresence the presence stanza(/packet) to send during shutdown.
* @throws NotConnectedException
*/
public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException {
try {
sendStanza(unavailablePresence);
}
catch (InterruptedException e) {
LOGGER.log(Level.FINE, "Was interrupted while sending unavailable presence. Continuing to disconnect the connection", e);
}
shutdown();
callConnectionClosedListener();
}
/**
* Shuts the current connection down.
*/
protected abstract void shutdown();
@Override
public void addConnectionListener(ConnectionListener connectionListener) {
if (connectionListener == null) {
return;
}
connectionListeners.add(connectionListener);
}
@Override
public void removeConnectionListener(ConnectionListener connectionListener) {
connectionListeners.remove(connectionListener);
}
@Override
public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException, InterruptedException {
StanzaFilter packetFilter = new IQReplyFilter(packet, this);
// Create the packet collector before sending the packet
PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet);
return packetCollector;
}
@Override
public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
throws NotConnectedException, InterruptedException {
// Create the packet collector before sending the packet
PacketCollector packetCollector = createPacketCollector(packetFilter);
try {
// Now we can send the packet as the collector has been created
sendStanza(packet);
}
catch (InterruptedException | NotConnectedException | RuntimeException e) {
packetCollector.cancel();
throw e;
}
return packetCollector;
}
@Override
public PacketCollector createPacketCollector(StanzaFilter packetFilter) {
PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter);
return createPacketCollector(configuration);
}
@Override
public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) {
PacketCollector collector = new PacketCollector(this, configuration);
// Add the collector to the list of active collectors.
collectors.add(collector);
return collector;
}
@Override
public void removePacketCollector(PacketCollector collector) {
collectors.remove(collector);
}
@Override
@Deprecated
public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) {
addAsyncStanzaListener(packetListener, packetFilter);
}
@Override
@Deprecated
public boolean removePacketListener(StanzaListener packetListener) {
return removeAsyncStanzaListener(packetListener);
}
@Override
public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (syncRecvListeners) {
syncRecvListeners.put(packetListener, wrapper);
}
}
@Override
public boolean removeSyncStanzaListener(StanzaListener packetListener) {
synchronized (syncRecvListeners) {
return syncRecvListeners.remove(packetListener) != null;
}
}
@Override
public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (asyncRecvListeners) {
asyncRecvListeners.put(packetListener, wrapper);
}
}
@Override
public boolean removeAsyncStanzaListener(StanzaListener packetListener) {
synchronized (asyncRecvListeners) {
return asyncRecvListeners.remove(packetListener) != null;
}
}
@Override
public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (sendListeners) {
sendListeners.put(packetListener, wrapper);
}
}
@Override
public void removePacketSendingListener(StanzaListener packetListener) {
synchronized (sendListeners) {
sendListeners.remove(packetListener);
}
}
/**
* Process all stanza(/packet) listeners for sending packets.
* <p>
* Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread.
* </p>
*
* @param packet the stanza(/packet) to process.
*/
@SuppressWarnings("javadoc")
protected void firePacketSendingListeners(final Stanza packet) {
final List<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
synchronized (sendListeners) {
for (ListenerWrapper listenerWrapper : sendListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
if (listenersToNotify.isEmpty()) {
return;
}
// Notify in a new thread, because we can
asyncGo(new Runnable() {
@Override
public void run() {
for (StanzaListener listener : listenersToNotify) {
try {
listener.processPacket(packet);
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Sending listener threw exception", e);
continue;
}
}
}});
}
@Override
public void addPacketInterceptor(StanzaListener packetInterceptor,
StanzaFilter packetFilter) {
if (packetInterceptor == null) {
throw new NullPointerException("Packet interceptor is null.");
}
InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
synchronized (interceptors) {
interceptors.put(packetInterceptor, interceptorWrapper);
}
}
@Override
public void removePacketInterceptor(StanzaListener packetInterceptor) {
synchronized (interceptors) {
interceptors.remove(packetInterceptor);
}
}
/**
* Process interceptors. Interceptors may modify the stanza(/packet) that is about to be sent.
* Since the thread that requested to send the stanza(/packet) will invoke all interceptors, it
* is important that interceptors perform their work as soon as possible so that the
* thread does not remain blocked for a long period.
*
* @param packet the stanza(/packet) that is going to be sent to the server
*/
private void firePacketInterceptors(Stanza packet) {
List<StanzaListener> interceptorsToInvoke = new LinkedList<StanzaListener>();
synchronized (interceptors) {
for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
if (interceptorWrapper.filterMatches(packet)) {
interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
}
}
}
for (StanzaListener interceptor : interceptorsToInvoke) {
try {
interceptor.processPacket(packet);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
}
}
}
/**
* Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger}
* by setup the system property <code>smack.debuggerClass</code> to the implementation.
*
* @throws IllegalStateException if the reader or writer isn't yet initialized.
* @throws IllegalArgumentException if the SmackDebugger can't be loaded.
*/
protected void initDebugger() {
if (reader == null || writer == null) {
throw new NullPointerException("Reader or writer isn't initialized.");
}
// If debugging is enabled, we open a window and write out all network traffic.
if (config.isDebuggerEnabled()) {
if (debugger == null) {
debugger = SmackConfiguration.createDebugger(this, writer, reader);
}
if (debugger == null) {
LOGGER.severe("Debugging enabled but could not find debugger class");
} else {
// Obtain new reader and writer from the existing debugger
reader = debugger.newConnectionReader(reader);
writer = debugger.newConnectionWriter(writer);
}
}
}
@Override
public long getPacketReplyTimeout() {
return packetReplyTimeout;
}
@Override
public void setPacketReplyTimeout(long timeout) {
packetReplyTimeout = timeout;
}
private static boolean replyToUnknownIqDefault = true;
/**
* Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured
* default is 'true'.
*
* @param replyToUnkownIqDefault
* @see #setReplyToUnknownIq(boolean)
*/
public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) {
AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault;
}
private boolean replyToUnkownIq = replyToUnknownIqDefault;
/**
* Set if Smack will automatically send
* {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a
* registered {@link IQRequestHandler} is received.
*
* @param replyToUnknownIq
*/
public void setReplyToUnknownIq(boolean replyToUnknownIq) {
this.replyToUnkownIq = replyToUnknownIq;
}
protected void parseAndProcessStanza(XmlPullParser parser) throws Exception {
ParserUtils.assertAtStartTag(parser);
int parserDepth = parser.getDepth();
Stanza stanza = null;
try {
stanza = PacketParserUtils.parseStanza(parser);
}
catch (Exception e) {
CharSequence content = PacketParserUtils.parseContentDepth(parser,
parserDepth);
UnparseableStanza message = new UnparseableStanza(content, e);
ParsingExceptionCallback callback = getParsingExceptionCallback();
if (callback != null) {
callback.handleUnparsableStanza(message);
}
}
ParserUtils.assertAtEndTag(parser);
if (stanza != null) {
processStanza(stanza);
}
}
/**
* Processes a stanza(/packet) after it's been fully parsed by looping through the installed
* stanza(/packet) collectors and listeners and letting them examine the stanza(/packet) to see if
* they are a match with the filter.
*
* @param stanza the stanza to process.
* @throws InterruptedException
*/
protected void processStanza(final Stanza stanza) throws InterruptedException {
assert(stanza != null);
lastStanzaReceived = System.currentTimeMillis();
// Deliver the incoming packet to listeners.
executorService.executeBlocking(new Runnable() {
@Override
public void run() {
invokePacketCollectorsAndNotifyRecvListeners(stanza);
}
});
}
/**
* Invoke {@link PacketCollector#processPacket(Stanza)} for every
* PacketCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet.
*
* @param packet the stanza(/packet) to notify the PacketCollectors and receive listeners about.
*/
protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) {
if (packet instanceof IQ) {
final IQ iq = (IQ) packet;
final IQ.Type type = iq.getType();
switch (type) {
case set:
case get:
final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace());
IQRequestHandler iqRequestHandler = null;
switch (type) {
case set:
synchronized (setIqRequestHandler) {
iqRequestHandler = setIqRequestHandler.get(key);
}
break;
case get:
synchronized (getIqRequestHandler) {
iqRequestHandler = getIqRequestHandler.get(key);
}
break;
default:
throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
}
if (iqRequestHandler == null) {
if (!replyToUnkownIq) {
return;
}
// If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
// IQ of type 'error' with condition 'service-unavailable'.
ErrorIQ errorIQ = IQ.createErrorResponse(iq, XMPPError.getBuilder((
XMPPError.Condition.service_unavailable)));
try {
sendStanza(errorIQ);
}
catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.WARNING, "Exception while sending error IQ to unkown IQ request", e);
}
} else {
ExecutorService executorService = null;
switch (iqRequestHandler.getMode()) {
case sync:
executorService = singleThreadedExecutorService;
break;
case async:
executorService = cachedExecutorService;
break;
}
final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
executorService.execute(new Runnable() {
@Override
public void run() {
IQ response = finalIqRequestHandler.handleIQRequest(iq);
if (response == null) {
// It is not ideal if the IQ request handler does not return an IQ response, because RFC
// 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the
// file transfer one, does not always return a result, so we need to handle this case.
// Also sometimes a request handler may decide that it's better to not send a response,
// e.g. to avoid presence leaks.
return;
}
try {
sendStanza(response);
}
catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.WARNING, "Exception while sending response to IQ request", e);
}
}
});
// The following returns makes it impossible for packet listeners and collectors to
// filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the
// desired behavior.
return;
}
break;
default:
break;
}
}
// First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
// the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
// their own thread.
final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
synchronized (asyncRecvListeners) {
for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
for (final StanzaListener listener : listenersToNotify) {
asyncGo(new Runnable() {
@Override
public void run() {
try {
listener.processPacket(packet);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
}
}
});
}
// Loop through all collectors and notify the appropriate ones.
for (PacketCollector collector: collectors) {
collector.processPacket(packet);
}
// Notify the receive listeners interested in the packet
listenersToNotify.clear();
synchronized (syncRecvListeners) {
for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
// Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
// threaded executor service and therefore keeps the order.
singleThreadedExecutorService.execute(new Runnable() {
@Override
public void run() {
for (StanzaListener listener : listenersToNotify) {
try {
listener.processPacket(packet);
} catch(NotConnectedException e) {
LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
break;
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
}
}
}
});
}
/**
* Sets whether the connection has already logged in the server. This method assures that the
* {@link #wasAuthenticated} flag is never reset once it has ever been set.
*
*/
protected void setWasAuthenticated() {
// Never reset the flag if the connection has ever been authenticated
if (!wasAuthenticated) {
wasAuthenticated = authenticated;
}
}
protected void callConnectionConnectedListener() {
for (ConnectionListener listener : connectionListeners) {
listener.connected(this);
}
}
protected void callConnectionAuthenticatedListener(boolean resumed) {
for (ConnectionListener listener : connectionListeners) {
try {
listener.authenticated(this, resumed);
} catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e);
}
}
}
void callConnectionClosedListener() {
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionClosed();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
}
}
}
protected void callConnectionClosedOnErrorListener(Exception e) {
boolean logWarning = true;
if (e instanceof StreamErrorException) {
StreamErrorException see = (StreamErrorException) e;
if (see.getStreamError().getCondition() == StreamError.Condition.not_authorized
&& wasAuthenticated) {
logWarning = false;
LOGGER.log(Level.FINE,
"Connection closed with not-authorized stream error after it was already authenticated. The account was likely deleted/unregistered on the server");
}
}
if (logWarning) {
LOGGER.log(Level.WARNING, "Connection " + this + " closed with error", e);
}
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionClosedOnError(e);
}
catch (Exception e2) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
}
}
}
/**
* Sends a notification indicating that the connection was reconnected successfully.
*/
protected void notifyReconnection() {
// Notify connection listeners of the reconnection.
for (ConnectionListener listener : connectionListeners) {
try {
listener.reconnectionSuccessful();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.WARNING, "notifyReconnection()", e);
}
}
}
/**
* A wrapper class to associate a stanza(/packet) filter with a listener.
*/
protected static class ListenerWrapper {
private final StanzaListener packetListener;
private final StanzaFilter packetFilter;
/**
* Create a class which associates a stanza(/packet) filter with a listener.
*
* @param packetListener the stanza(/packet) listener.
* @param packetFilter the associated filter or null if it listen for all packets.
*/
public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) {
this.packetListener = packetListener;
this.packetFilter = packetFilter;
}
public boolean filterMatches(Stanza packet) {
return packetFilter == null || packetFilter.accept(packet);
}
public StanzaListener getListener() {
return packetListener;
}
}
/**
* A wrapper class to associate a stanza(/packet) filter with an interceptor.
*/
protected static class InterceptorWrapper {
private final StanzaListener packetInterceptor;
private final StanzaFilter packetFilter;
/**
* Create a class which associates a stanza(/packet) filter with an interceptor.
*
* @param packetInterceptor the interceptor.
* @param packetFilter the associated filter or null if it intercepts all packets.
*/
public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) {
this.packetInterceptor = packetInterceptor;
this.packetFilter = packetFilter;
}
public boolean filterMatches(Stanza packet) {
return packetFilter == null || packetFilter.accept(packet);
}
public StanzaListener getInterceptor() {
return packetInterceptor;
}
}
@Override
public int getConnectionCounter() {
return connectionCounterValue;
}
@Override
public void setFromMode(FromMode fromMode) {
this.fromMode = fromMode;
}
@Override
public FromMode getFromMode() {
return this.fromMode;
}
@Override
protected void finalize() throws Throwable {
LOGGER.fine("finalizing " + this + ": Shutting down executor services");
try {
// It's usually not a good idea to rely on finalize. But this is the easiest way to
// avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a
// reference to their ExecutorService which prevents the ExecutorService from being
// gc'ed. It is possible that the XMPPConnection instance is gc'ed while the
// listenerExecutor ExecutorService call not be gc'ed until it got shut down.
executorService.shutdownNow();
cachedExecutorService.shutdown();
removeCallbacksService.shutdownNow();
singleThreadedExecutorService.shutdownNow();
} catch (Throwable t) {
LOGGER.log(Level.WARNING, "finalize() threw trhowable", t);
}
finally {
super.finalize();
}
}
protected final void parseFeatures(XmlPullParser parser) throws Exception {
streamFeatures.clear();
final int initialDepth = parser.getDepth();
while (true) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) {
ExtensionElement streamFeature = null;
String name = parser.getName();
String namespace = parser.getNamespace();
switch (name) {
case StartTls.ELEMENT:
streamFeature = PacketParserUtils.parseStartTlsFeature(parser);
break;
case Mechanisms.ELEMENT:
streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser));
break;
case Bind.ELEMENT:
streamFeature = Bind.Feature.INSTANCE;
break;
case Session.ELEMENT:
streamFeature = PacketParserUtils.parseSessionFeature(parser);
break;
case Compress.Feature.ELEMENT:
streamFeature = PacketParserUtils.parseCompressionFeature(parser);
break;
default:
ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace);
if (provider != null) {
streamFeature = provider.parse(parser);
}
break;
}
if (streamFeature != null) {
addStreamFeature(streamFeature);
}
}
else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) {
break;
}
}
if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
// Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
|| config.getSecurityMode() == SecurityMode.disabled) {
saslFeatureReceived.reportSuccess();
}
}
// If the server reported the bind feature then we are that that we did SASL and maybe
// STARTTLS. We can then report that the last 'stream:features' have been parsed
if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
|| !config.isCompressionEnabled()) {
// This was was last features from the server is either it did not contain
// compression or if we disabled it
lastFeaturesReceived.reportSuccess();
}
}
afterFeaturesReceived();
}
@SuppressWarnings("unused")
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {
// Default implementation does nothing
}
@SuppressWarnings("unchecked")
@Override
public <F extends ExtensionElement> F getFeature(String element, String namespace) {
return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace));
}
@Override
public boolean hasFeature(String element, String namespace) {
return getFeature(element, namespace) != null;
}
protected void addStreamFeature(ExtensionElement feature) {
String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace());
streamFeatures.put(key, feature);
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
StanzaListener callback) throws NotConnectedException, InterruptedException {
sendStanzaWithResponseCallback(stanza, replyFilter, callback, null);
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
StanzaListener callback, ExceptionCallback exceptionCallback)
throws NotConnectedException, InterruptedException {
sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback,
getPacketReplyTimeout());
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter,
final StanzaListener callback, final ExceptionCallback exceptionCallback,
long timeout) throws NotConnectedException, InterruptedException {
Objects.requireNonNull(stanza, "stanza must not be null");
// While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
// disallow it here in the async API as it makes no sense
Objects.requireNonNull(replyFilter, "replyFilter must not be null");
Objects.requireNonNull(callback, "callback must not be null");
final StanzaListener packetListener = new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws NotConnectedException, InterruptedException {
try {
XMPPErrorException.ifHasErrorThenThrow(packet);
callback.processPacket(packet);
}
catch (XMPPErrorException e) {
if (exceptionCallback != null) {
exceptionCallback.processException(e);
}
}
finally {
removeAsyncStanzaListener(this);
}
}
};
removeCallbacksService.schedule(new Runnable() {
@Override
public void run() {
boolean removed = removeAsyncStanzaListener(packetListener);
// If the packetListener got removed, then it was never run and
// we never received a response, inform the exception callback
if (removed && exceptionCallback != null) {
Exception exception;
if (!isConnected()) {
// If the connection is no longer connected, throw a not connected exception.
exception = new NotConnectedException(AbstractXMPPConnection.this, replyFilter);
} else {
exception = NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter);
}
exceptionCallback.processException(exception);
}
}
}, timeout, TimeUnit.MILLISECONDS);
addAsyncStanzaListener(packetListener, replyFilter);
sendStanza(stanza);
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback)
throws NotConnectedException, InterruptedException {
sendIqWithResponseCallback(iqRequest, callback, null);
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback,
ExceptionCallback exceptionCallback) throws NotConnectedException, InterruptedException {
sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout());
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback,
final ExceptionCallback exceptionCallback, long timeout)
throws NotConnectedException, InterruptedException {
StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this);
sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout);
}
@Override
public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
final StanzaListener packetListener = new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws NotConnectedException, InterruptedException {
try {
callback.processPacket(packet);
} finally {
removeSyncStanzaListener(this);
}
}
};
addSyncStanzaListener(packetListener, packetFilter);
removeCallbacksService.schedule(new Runnable() {
@Override
public void run() {
removeSyncStanzaListener(packetListener);
}
}, getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
}
@Override
public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) {
final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace());
switch (iqRequestHandler.getType()) {
case set:
synchronized (setIqRequestHandler) {
return setIqRequestHandler.put(key, iqRequestHandler);
}
case get:
synchronized (getIqRequestHandler) {
return getIqRequestHandler.put(key, iqRequestHandler);
}
default:
throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
}
}
@Override
public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) {
return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(),
iqRequestHandler.getType());
}
@Override
public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
final String key = XmppStringUtils.generateKey(element, namespace);
switch (type) {
case set:
synchronized (setIqRequestHandler) {
return setIqRequestHandler.remove(key);
}
case get:
synchronized (getIqRequestHandler) {
return getIqRequestHandler.remove(key);
}
default:
throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
}
}
private long lastStanzaReceived;
public long getLastStanzaReceived() {
return lastStanzaReceived;
}
/**
* Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a
* stanza.
*
* @param callback the callback to install
*/
public void setParsingExceptionCallback(ParsingExceptionCallback callback) {
parsingExceptionCallback = callback;
}
/**
* Get the current active parsing exception callback.
*
* @return the active exception callback or null if there is none
*/
public ParsingExceptionCallback getParsingExceptionCallback() {
return parsingExceptionCallback;
}
@Override
public final String toString() {
EntityFullJid localEndpoint = getUser();
String localEndpointString = (localEndpoint == null ? "not-authenticated" : localEndpoint.toString());
return getClass().getSimpleName() + '[' + localEndpointString + "] (" + getConnectionCounter() + ')';
}
protected final void asyncGo(Runnable runnable) {
cachedExecutorService.execute(runnable);
}
protected final ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) {
return removeCallbacksService.schedule(runnable, delay, unit);
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_4769_0
|
crossvul-java_data_bad_4768_0
|
/**
*
* Copyright 2009 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.ConnectionException;
import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;
import org.jivesoftware.smack.SmackException.SecurityRequiredException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.compress.packet.Compress;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.debugger.SmackDebugger;
import org.jivesoftware.smack.filter.IQReplyFilter;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.filter.StanzaIdFilter;
import org.jivesoftware.smack.iqrequest.IQRequestHandler;
import org.jivesoftware.smack.packet.Bind;
import org.jivesoftware.smack.packet.ErrorIQ;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Mechanisms;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Session;
import org.jivesoftware.smack.packet.StartTls;
import org.jivesoftware.smack.packet.PlainStreamElement;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
import org.jivesoftware.smack.parsing.UnparsablePacket;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.BoundedThreadPoolExecutor;
import org.jivesoftware.smack.util.DNSUtil;
import org.jivesoftware.smack.util.Objects;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.util.ParserUtils;
import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jxmpp.util.XmppStringUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
public abstract class AbstractXMPPConnection implements XMPPConnection {
private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName());
/**
* Counter to uniquely identify connections that are created.
*/
private final static AtomicInteger connectionCounter = new AtomicInteger(0);
static {
// Ensure the SmackConfiguration class is loaded by calling a method in it.
SmackConfiguration.getVersion();
}
/**
* Get the collection of listeners that are interested in connection creation events.
*
* @return a collection of listeners interested on new connections.
*/
protected static Collection<ConnectionCreationListener> getConnectionCreationListeners() {
return XMPPConnectionRegistry.getConnectionCreationListeners();
}
/**
* A collection of ConnectionListeners which listen for connection closing
* and reconnection events.
*/
protected final Set<ConnectionListener> connectionListeners =
new CopyOnWriteArraySet<ConnectionListener>();
/**
* A collection of PacketCollectors which collects packets for a specified filter
* and perform blocking and polling operations on the result queue.
* <p>
* We use a ConcurrentLinkedQueue here, because its Iterator is weakly
* consistent and we want {@link #invokePacketCollectors(Stanza)} for-each
* loop to be lock free. As drawback, removing a PacketCollector is O(n).
* The alternative would be a synchronized HashSet, but this would mean a
* synchronized block around every usage of <code>collectors</code>.
* </p>
*/
private final Collection<PacketCollector> collectors = new ConcurrentLinkedQueue<PacketCollector>();
/**
* List of PacketListeners that will be notified synchronously when a new stanza(/packet) was received.
*/
private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>();
/**
* List of PacketListeners that will be notified asynchronously when a new stanza(/packet) was received.
*/
private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>();
/**
* List of PacketListeners that will be notified when a new stanza(/packet) was sent.
*/
private final Map<StanzaListener, ListenerWrapper> sendListeners =
new HashMap<StanzaListener, ListenerWrapper>();
/**
* List of PacketListeners that will be notified when a new stanza(/packet) is about to be
* sent to the server. These interceptors may modify the stanza(/packet) before it is being
* actually sent to the server.
*/
private final Map<StanzaListener, InterceptorWrapper> interceptors =
new HashMap<StanzaListener, InterceptorWrapper>();
protected final Lock connectionLock = new ReentrantLock();
protected final Map<String, ExtensionElement> streamFeatures = new HashMap<String, ExtensionElement>();
/**
* The full JID of the authenticated user, as returned by the resource binding response of the server.
* <p>
* It is important that we don't infer the user from the login() arguments and the configurations service name, as,
* for example, when SASL External is used, the username is not given to login but taken from the 'external'
* certificate.
* </p>
*/
protected String user;
protected boolean connected = false;
/**
* The stream ID, see RFC 6120 § 4.7.3
*/
protected String streamId;
/**
*
*/
private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout();
/**
* The SmackDebugger allows to log and debug XML traffic.
*/
protected SmackDebugger debugger = null;
/**
* The Reader which is used for the debugger.
*/
protected Reader reader;
/**
* The Writer which is used for the debugger.
*/
protected Writer writer;
/**
* Set to success if the last features stanza from the server has been parsed. A XMPP connection
* handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature
* stanza is send by the server. This is set to true once the last feature stanza has been
* parsed.
*/
protected final SynchronizationPoint<Exception> lastFeaturesReceived = new SynchronizationPoint<Exception>(
AbstractXMPPConnection.this);
/**
* Set to success if the sasl feature has been received.
*/
protected final SynchronizationPoint<SmackException> saslFeatureReceived = new SynchronizationPoint<SmackException>(
AbstractXMPPConnection.this);
/**
* The SASLAuthentication manager that is responsible for authenticating with the server.
*/
protected SASLAuthentication saslAuthentication = new SASLAuthentication(this);
/**
* A number to uniquely identify connections that are created. This is distinct from the
* connection ID, which is a value sent by the server once a connection is made.
*/
protected final int connectionCounterValue = connectionCounter.getAndIncrement();
/**
* Holds the initial configuration used while creating the connection.
*/
protected final ConnectionConfiguration config;
/**
* Defines how the from attribute of outgoing stanzas should be handled.
*/
private FromMode fromMode = FromMode.OMITTED;
protected XMPPInputOutputStream compressionHandler;
private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback();
/**
* ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is
* important that we use a <b>single threaded ExecutorService</b> in order to guarantee that the
* PacketListeners are invoked in the same order the stanzas arrived.
*/
private final BoundedThreadPoolExecutor executorService = new BoundedThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
100, new SmackExecutorThreadFactory(connectionCounterValue, "Incoming Processor"));
/**
* This scheduled thread pool executor is used to remove pending callbacks.
*/
private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor(
new SmackExecutorThreadFactory(connectionCounterValue, "Remove Callbacks"));
/**
* A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set
* them 'daemon'.
*/
private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool(
// @formatter:off
new SmackExecutorThreadFactory( // threadFactory
connectionCounterValue,
"Cached Executor"
)
// @formatter:on
);
/**
* A executor service used to invoke the callbacks of synchronous stanza(/packet) listeners. We use a executor service to
* decouple incoming stanza processing from callback invocation. It is important that order of callback invocation
* is the same as the order of the incoming stanzas. Therefore we use a <i>single</i> threaded executor service.
*/
private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory(
getConnectionCounter(), "Single Threaded Executor"));
/**
* The used host to establish the connection to
*/
protected String host;
/**
* The used port to establish the connection to
*/
protected int port;
/**
* Flag that indicates if the user is currently authenticated with the server.
*/
protected boolean authenticated = false;
/**
* Flag that indicates if the user was authenticated with the server when the connection
* to the server was closed (abruptly or not).
*/
protected boolean wasAuthenticated = false;
private final Map<String, IQRequestHandler> setIqRequestHandler = new HashMap<>();
private final Map<String, IQRequestHandler> getIqRequestHandler = new HashMap<>();
/**
* Create a new XMPPConnection to an XMPP server.
*
* @param configuration The configuration which is used to establish the connection.
*/
protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
config = configuration;
}
/**
* Get the connection configuration used by this connection.
*
* @return the connection configuration.
*/
public ConnectionConfiguration getConfiguration() {
return config;
}
@Override
public String getServiceName() {
if (serviceName != null) {
return serviceName;
}
return config.getServiceName();
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public abstract boolean isSecureConnection();
protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException;
@Override
public abstract void send(PlainStreamElement element) throws NotConnectedException;
@Override
public abstract boolean isUsingCompression();
/**
* Establishes a connection to the XMPP server and performs an automatic login
* only if the previous connection state was logged (authenticated). It basically
* creates and maintains a connection to the server.
* <p>
* Listeners will be preserved from a previous connection.
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException
* @throws ConnectionException with detailed information about the failed connection.
* @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
*/
public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException {
// Check if not already connected
throwAlreadyConnectedExceptionIfAppropriate();
// Reset the connection state
saslAuthentication.init();
saslFeatureReceived.init();
lastFeaturesReceived.init();
streamId = null;
// Perform the actual connection to the XMPP service
connectInternal();
return this;
}
/**
* Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
* way of XMPP connection establishment. Implementations are required to perform an automatic
* login if the previous connection state was logged (authenticated).
*
* @throws SmackException
* @throws IOException
* @throws XMPPException
*/
protected abstract void connectInternal() throws SmackException, IOException, XMPPException;
private String usedUsername, usedPassword, usedResource;
/**
* Logs in to the server using the strongest SASL mechanism supported by
* the server. If more than the connection's default stanza(/packet) timeout elapses in each step of the
* authentication process without a response from the server, a
* {@link SmackException.NoResponseException} will be thrown.
* <p>
* Before logging in (i.e. authenticate) to the server the connection must be connected
* by calling {@link #connect}.
* </p>
* <p>
* It is possible to log in without sending an initial available presence by using
* {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}.
* Finally, if you want to not pass a password and instead use a more advanced mechanism
* while using SASL then you may be interested in using
* {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}.
* For more advanced login settings see {@link ConnectionConfiguration}.
* </p>
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException if an I/O error occurs during login.
*/
public synchronized void login() throws XMPPException, SmackException, IOException {
if (isAnonymous()) {
throwNotConnectedExceptionIfAppropriate("Did you call connect() before login()?");
throwAlreadyLoggedInExceptionIfAppropriate();
loginAnonymously();
} else {
// The previously used username, password and resource take over precedence over the
// ones from the connection configuration
CharSequence username = usedUsername != null ? usedUsername : config.getUsername();
String password = usedPassword != null ? usedPassword : config.getPassword();
String resource = usedResource != null ? usedResource : config.getResource();
login(username, password, resource);
}
}
/**
* Same as {@link #login(CharSequence, String, String)}, but takes the resource from the connection
* configuration.
*
* @param username
* @param password
* @throws XMPPException
* @throws SmackException
* @throws IOException
* @see #login
*/
public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException,
IOException {
login(username, password, config.getResource());
}
/**
* Login with the given username (authorization identity). You may omit the password if a callback handler is used.
* If resource is null, then the server will generate one.
*
* @param username
* @param password
* @param resource
* @throws XMPPException
* @throws SmackException
* @throws IOException
* @see #login
*/
public synchronized void login(CharSequence username, String password, String resource) throws XMPPException,
SmackException, IOException {
if (!config.allowNullOrEmptyUsername) {
StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty");
}
throwNotConnectedExceptionIfAppropriate();
throwAlreadyLoggedInExceptionIfAppropriate();
usedUsername = username != null ? username.toString() : null;
usedPassword = password;
usedResource = resource;
loginNonAnonymously(usedUsername, usedPassword, usedResource);
}
protected abstract void loginNonAnonymously(String username, String password, String resource)
throws XMPPException, SmackException, IOException;
protected abstract void loginAnonymously() throws XMPPException, SmackException, IOException;
@Override
public final boolean isConnected() {
return connected;
}
@Override
public final boolean isAuthenticated() {
return authenticated;
}
@Override
public final String getUser() {
return user;
}
@Override
public String getStreamId() {
if (!isConnected()) {
return null;
}
return streamId;
}
// TODO remove this suppression once "disable legacy session" code has been removed from Smack
@SuppressWarnings("deprecation")
protected void bindResourceAndEstablishSession(String resource) throws XMPPErrorException,
IOException, SmackException {
// Wait until either:
// - the servers last features stanza has been parsed
// - the timeout occurs
LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
lastFeaturesReceived.checkIfSuccessOrWait();
if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
// Server never offered resource binding, which is REQURIED in XMPP client and
// server implementations as per RFC6120 7.2
throw new ResourceBindingNotOfferedException();
}
// Resource binding, see RFC6120 7.
// Note that we can not use IQReplyFilter here, since the users full JID is not yet
// available. It will become available right after the resource has been successfully bound.
Bind bindResource = Bind.newSet(resource);
PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
Bind response = packetCollector.nextResultOrThrow();
// Set the connections user to the result of resource binding. It is important that we don't infer the user
// from the login() arguments and the configurations service name, as, for example, when SASL External is used,
// the username is not given to login but taken from the 'external' certificate.
user = response.getJid();
serviceName = XmppStringUtils.parseDomain(user);
Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE);
// Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
// For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
if (sessionFeature != null && !sessionFeature.isOptional() && !getConfiguration().isLegacySessionDisabled()) {
Session session = new Session();
packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session);
packetCollector.nextResultOrThrow();
}
}
protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException {
// Indicate that we're now authenticated.
this.authenticated = true;
// If debugging is enabled, change the the debug window title to include the
// name we are now logged-in as.
// If DEBUG was set to true AFTER the connection was created the debugger
// will be null
if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user);
}
callConnectionAuthenticatedListener(resumed);
// Set presence to online. It is important that this is done after
// callConnectionAuthenticatedListener(), as this call will also
// eventually load the roster. And we should load the roster before we
// send the initial presence.
if (config.isSendPresence() && !resumed) {
sendStanza(new Presence(Presence.Type.available));
}
}
@Override
public final boolean isAnonymous() {
return config.getUsername() == null && usedUsername == null
&& !config.allowNullOrEmptyUsername;
}
private String serviceName;
protected List<HostAddress> hostAddresses;
/**
* Populates {@link #hostAddresses} with at least one host address.
*
* @return a list of host addresses where DNS (SRV) RR resolution failed.
*/
protected List<HostAddress> populateHostAddresses() {
List<HostAddress> failedAddresses = new LinkedList<>();
// N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName
if (config.host != null) {
hostAddresses = new ArrayList<HostAddress>(1);
HostAddress hostAddress;
hostAddress = new HostAddress(config.host, config.port);
hostAddresses.add(hostAddress);
} else {
hostAddresses = DNSUtil.resolveXMPPDomain(config.serviceName, failedAddresses);
}
// If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the
// config.host one or the host representing the service name by DNSUtil
assert(!hostAddresses.isEmpty());
return failedAddresses;
}
protected Lock getConnectionLock() {
return connectionLock;
}
protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
throwNotConnectedExceptionIfAppropriate(null);
}
protected void throwNotConnectedExceptionIfAppropriate(String optionalHint) throws NotConnectedException {
if (!isConnected()) {
throw new NotConnectedException(optionalHint);
}
}
protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
if (isConnected()) {
throw new AlreadyConnectedException();
}
}
protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
if (isAuthenticated()) {
throw new AlreadyLoggedInException();
}
}
@Deprecated
@Override
public void sendPacket(Stanza packet) throws NotConnectedException {
sendStanza(packet);
}
@Override
public void sendStanza(Stanza packet) throws NotConnectedException {
Objects.requireNonNull(packet, "Packet must not be null");
throwNotConnectedExceptionIfAppropriate();
switch (fromMode) {
case OMITTED:
packet.setFrom(null);
break;
case USER:
packet.setFrom(getUser());
break;
case UNCHANGED:
default:
break;
}
// Invoke interceptors for the new packet that is about to be sent. Interceptors may modify
// the content of the packet.
firePacketInterceptors(packet);
sendStanzaInternal(packet);
}
/**
* Returns the SASLAuthentication manager that is responsible for authenticating with
* the server.
*
* @return the SASLAuthentication manager that is responsible for authenticating with
* the server.
*/
protected SASLAuthentication getSASLAuthentication() {
return saslAuthentication;
}
/**
* Closes the connection by setting presence to unavailable then closing the connection to
* the XMPP server. The XMPPConnection can still be used for connecting to the server
* again.
*
*/
public void disconnect() {
try {
disconnect(new Presence(Presence.Type.unavailable));
}
catch (NotConnectedException e) {
LOGGER.log(Level.FINEST, "Connection is already disconnected", e);
}
}
/**
* Closes the connection. A custom unavailable presence is sent to the server, followed
* by closing the stream. The XMPPConnection can still be used for connecting to the server
* again. A custom unavailable presence is useful for communicating offline presence
* information such as "On vacation". Typically, just the status text of the presence
* stanza(/packet) is set with online information, but most XMPP servers will deliver the full
* presence stanza(/packet) with whatever data is set.
*
* @param unavailablePresence the presence stanza(/packet) to send during shutdown.
* @throws NotConnectedException
*/
public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException {
sendStanza(unavailablePresence);
shutdown();
callConnectionClosedListener();
}
/**
* Shuts the current connection down.
*/
protected abstract void shutdown();
@Override
public void addConnectionListener(ConnectionListener connectionListener) {
if (connectionListener == null) {
return;
}
connectionListeners.add(connectionListener);
}
@Override
public void removeConnectionListener(ConnectionListener connectionListener) {
connectionListeners.remove(connectionListener);
}
@Override
public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException {
StanzaFilter packetFilter = new IQReplyFilter(packet, this);
// Create the packet collector before sending the packet
PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet);
return packetCollector;
}
@Override
public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
throws NotConnectedException {
// Create the packet collector before sending the packet
PacketCollector packetCollector = createPacketCollector(packetFilter);
try {
// Now we can send the packet as the collector has been created
sendStanza(packet);
}
catch (NotConnectedException | RuntimeException e) {
packetCollector.cancel();
throw e;
}
return packetCollector;
}
@Override
public PacketCollector createPacketCollector(StanzaFilter packetFilter) {
PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter);
return createPacketCollector(configuration);
}
@Override
public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) {
PacketCollector collector = new PacketCollector(this, configuration);
// Add the collector to the list of active collectors.
collectors.add(collector);
return collector;
}
@Override
public void removePacketCollector(PacketCollector collector) {
collectors.remove(collector);
}
@Override
@Deprecated
public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) {
addAsyncStanzaListener(packetListener, packetFilter);
}
@Override
@Deprecated
public boolean removePacketListener(StanzaListener packetListener) {
return removeAsyncStanzaListener(packetListener);
}
@Override
public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (syncRecvListeners) {
syncRecvListeners.put(packetListener, wrapper);
}
}
@Override
public boolean removeSyncStanzaListener(StanzaListener packetListener) {
synchronized (syncRecvListeners) {
return syncRecvListeners.remove(packetListener) != null;
}
}
@Override
public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (asyncRecvListeners) {
asyncRecvListeners.put(packetListener, wrapper);
}
}
@Override
public boolean removeAsyncStanzaListener(StanzaListener packetListener) {
synchronized (asyncRecvListeners) {
return asyncRecvListeners.remove(packetListener) != null;
}
}
@Override
public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (sendListeners) {
sendListeners.put(packetListener, wrapper);
}
}
@Override
public void removePacketSendingListener(StanzaListener packetListener) {
synchronized (sendListeners) {
sendListeners.remove(packetListener);
}
}
/**
* Process all stanza(/packet) listeners for sending packets.
* <p>
* Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread.
* </p>
*
* @param packet the stanza(/packet) to process.
*/
@SuppressWarnings("javadoc")
protected void firePacketSendingListeners(final Stanza packet) {
final List<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
synchronized (sendListeners) {
for (ListenerWrapper listenerWrapper : sendListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
if (listenersToNotify.isEmpty()) {
return;
}
// Notify in a new thread, because we can
asyncGo(new Runnable() {
@Override
public void run() {
for (StanzaListener listener : listenersToNotify) {
try {
listener.processPacket(packet);
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Sending listener threw exception", e);
continue;
}
}
}});
}
@Override
public void addPacketInterceptor(StanzaListener packetInterceptor,
StanzaFilter packetFilter) {
if (packetInterceptor == null) {
throw new NullPointerException("Packet interceptor is null.");
}
InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
synchronized (interceptors) {
interceptors.put(packetInterceptor, interceptorWrapper);
}
}
@Override
public void removePacketInterceptor(StanzaListener packetInterceptor) {
synchronized (interceptors) {
interceptors.remove(packetInterceptor);
}
}
/**
* Process interceptors. Interceptors may modify the stanza(/packet) that is about to be sent.
* Since the thread that requested to send the stanza(/packet) will invoke all interceptors, it
* is important that interceptors perform their work as soon as possible so that the
* thread does not remain blocked for a long period.
*
* @param packet the stanza(/packet) that is going to be sent to the server
*/
private void firePacketInterceptors(Stanza packet) {
List<StanzaListener> interceptorsToInvoke = new LinkedList<StanzaListener>();
synchronized (interceptors) {
for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
if (interceptorWrapper.filterMatches(packet)) {
interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
}
}
}
for (StanzaListener interceptor : interceptorsToInvoke) {
try {
interceptor.processPacket(packet);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
}
}
}
/**
* Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger}
* by setup the system property <code>smack.debuggerClass</code> to the implementation.
*
* @throws IllegalStateException if the reader or writer isn't yet initialized.
* @throws IllegalArgumentException if the SmackDebugger can't be loaded.
*/
protected void initDebugger() {
if (reader == null || writer == null) {
throw new NullPointerException("Reader or writer isn't initialized.");
}
// If debugging is enabled, we open a window and write out all network traffic.
if (config.isDebuggerEnabled()) {
if (debugger == null) {
debugger = SmackConfiguration.createDebugger(this, writer, reader);
}
if (debugger == null) {
LOGGER.severe("Debugging enabled but could not find debugger class");
} else {
// Obtain new reader and writer from the existing debugger
reader = debugger.newConnectionReader(reader);
writer = debugger.newConnectionWriter(writer);
}
}
}
@Override
public long getPacketReplyTimeout() {
return packetReplyTimeout;
}
@Override
public void setPacketReplyTimeout(long timeout) {
packetReplyTimeout = timeout;
}
private static boolean replyToUnknownIqDefault = true;
/**
* Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured
* default is 'true'.
*
* @param replyToUnkownIqDefault
* @see #setReplyToUnknownIq(boolean)
*/
public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) {
AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault;
}
private boolean replyToUnkownIq = replyToUnknownIqDefault;
/**
* Set if Smack will automatically send
* {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a
* registered {@link IQRequestHandler} is received.
*
* @param replyToUnknownIq
*/
public void setReplyToUnknownIq(boolean replyToUnknownIq) {
this.replyToUnkownIq = replyToUnknownIq;
}
protected void parseAndProcessStanza(XmlPullParser parser) throws Exception {
ParserUtils.assertAtStartTag(parser);
int parserDepth = parser.getDepth();
Stanza stanza = null;
try {
stanza = PacketParserUtils.parseStanza(parser);
}
catch (Exception e) {
CharSequence content = PacketParserUtils.parseContentDepth(parser,
parserDepth);
UnparsablePacket message = new UnparsablePacket(content, e);
ParsingExceptionCallback callback = getParsingExceptionCallback();
if (callback != null) {
callback.handleUnparsablePacket(message);
}
}
ParserUtils.assertAtEndTag(parser);
if (stanza != null) {
processPacket(stanza);
}
}
/**
* Processes a stanza(/packet) after it's been fully parsed by looping through the installed
* stanza(/packet) collectors and listeners and letting them examine the stanza(/packet) to see if
* they are a match with the filter.
*
* @param packet the stanza(/packet) to process.
* @throws InterruptedException
*/
protected void processPacket(Stanza packet) throws InterruptedException {
assert(packet != null);
lastStanzaReceived = System.currentTimeMillis();
// Deliver the incoming packet to listeners.
executorService.executeBlocking(new ListenerNotification(packet));
}
/**
* A runnable to notify all listeners and stanza(/packet) collectors of a packet.
*/
private class ListenerNotification implements Runnable {
private final Stanza packet;
public ListenerNotification(Stanza packet) {
this.packet = packet;
}
public void run() {
invokePacketCollectorsAndNotifyRecvListeners(packet);
}
}
/**
* Invoke {@link PacketCollector#processPacket(Stanza)} for every
* PacketCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet.
*
* @param packet the stanza(/packet) to notify the PacketCollectors and receive listeners about.
*/
protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) {
if (packet instanceof IQ) {
final IQ iq = (IQ) packet;
final IQ.Type type = iq.getType();
switch (type) {
case set:
case get:
final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace());
IQRequestHandler iqRequestHandler = null;
switch (type) {
case set:
synchronized (setIqRequestHandler) {
iqRequestHandler = setIqRequestHandler.get(key);
}
break;
case get:
synchronized (getIqRequestHandler) {
iqRequestHandler = getIqRequestHandler.get(key);
}
break;
default:
throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
}
if (iqRequestHandler == null) {
if (!replyToUnkownIq) {
return;
}
// If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
// IQ of type "error" with code 501 ("feature-not-implemented")
ErrorIQ errorIQ = IQ.createErrorResponse(iq, new XMPPError(
XMPPError.Condition.feature_not_implemented));
try {
sendStanza(errorIQ);
}
catch (NotConnectedException e) {
LOGGER.log(Level.WARNING, "NotConnectedException while sending error IQ to unkown IQ request", e);
}
} else {
ExecutorService executorService = null;
switch (iqRequestHandler.getMode()) {
case sync:
executorService = singleThreadedExecutorService;
break;
case async:
executorService = cachedExecutorService;
break;
}
final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
executorService.execute(new Runnable() {
@Override
public void run() {
IQ response = finalIqRequestHandler.handleIQRequest(iq);
if (response == null) {
// It is not ideal if the IQ request handler does not return an IQ response, because RFC
// 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the
// file transfer one, does not always return a result, so we need to handle this case.
// Also sometimes a request handler may decide that it's better to not send a response,
// e.g. to avoid presence leaks.
return;
}
try {
sendStanza(response);
}
catch (NotConnectedException e) {
LOGGER.log(Level.WARNING, "NotConnectedException while sending response to IQ request", e);
}
}
});
// The following returns makes it impossible for packet listeners and collectors to
// filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the
// desired behavior.
return;
}
break;
default:
break;
}
}
// First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
// the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
// their own thread.
final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
synchronized (asyncRecvListeners) {
for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
for (final StanzaListener listener : listenersToNotify) {
asyncGo(new Runnable() {
@Override
public void run() {
try {
listener.processPacket(packet);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
}
}
});
}
// Loop through all collectors and notify the appropriate ones.
for (PacketCollector collector: collectors) {
collector.processPacket(packet);
}
// Notify the receive listeners interested in the packet
listenersToNotify.clear();
synchronized (syncRecvListeners) {
for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
// Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
// threaded executor service and therefore keeps the order.
singleThreadedExecutorService.execute(new Runnable() {
@Override
public void run() {
for (StanzaListener listener : listenersToNotify) {
try {
listener.processPacket(packet);
} catch(NotConnectedException e) {
LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
break;
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
}
}
}
});
}
/**
* Sets whether the connection has already logged in the server. This method assures that the
* {@link #wasAuthenticated} flag is never reset once it has ever been set.
*
*/
protected void setWasAuthenticated() {
// Never reset the flag if the connection has ever been authenticated
if (!wasAuthenticated) {
wasAuthenticated = authenticated;
}
}
protected void callConnectionConnectedListener() {
for (ConnectionListener listener : connectionListeners) {
listener.connected(this);
}
}
protected void callConnectionAuthenticatedListener(boolean resumed) {
for (ConnectionListener listener : connectionListeners) {
try {
listener.authenticated(this, resumed);
} catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e);
}
}
}
void callConnectionClosedListener() {
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionClosed();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
}
}
}
protected void callConnectionClosedOnErrorListener(Exception e) {
LOGGER.log(Level.WARNING, "Connection closed with error", e);
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionClosedOnError(e);
}
catch (Exception e2) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
}
}
}
/**
* Sends a notification indicating that the connection was reconnected successfully.
*/
protected void notifyReconnection() {
// Notify connection listeners of the reconnection.
for (ConnectionListener listener : connectionListeners) {
try {
listener.reconnectionSuccessful();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.WARNING, "notifyReconnection()", e);
}
}
}
/**
* A wrapper class to associate a stanza(/packet) filter with a listener.
*/
protected static class ListenerWrapper {
private final StanzaListener packetListener;
private final StanzaFilter packetFilter;
/**
* Create a class which associates a stanza(/packet) filter with a listener.
*
* @param packetListener the stanza(/packet) listener.
* @param packetFilter the associated filter or null if it listen for all packets.
*/
public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) {
this.packetListener = packetListener;
this.packetFilter = packetFilter;
}
public boolean filterMatches(Stanza packet) {
return packetFilter == null || packetFilter.accept(packet);
}
public StanzaListener getListener() {
return packetListener;
}
}
/**
* A wrapper class to associate a stanza(/packet) filter with an interceptor.
*/
protected static class InterceptorWrapper {
private final StanzaListener packetInterceptor;
private final StanzaFilter packetFilter;
/**
* Create a class which associates a stanza(/packet) filter with an interceptor.
*
* @param packetInterceptor the interceptor.
* @param packetFilter the associated filter or null if it intercepts all packets.
*/
public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) {
this.packetInterceptor = packetInterceptor;
this.packetFilter = packetFilter;
}
public boolean filterMatches(Stanza packet) {
return packetFilter == null || packetFilter.accept(packet);
}
public StanzaListener getInterceptor() {
return packetInterceptor;
}
}
@Override
public int getConnectionCounter() {
return connectionCounterValue;
}
@Override
public void setFromMode(FromMode fromMode) {
this.fromMode = fromMode;
}
@Override
public FromMode getFromMode() {
return this.fromMode;
}
@Override
protected void finalize() throws Throwable {
LOGGER.fine("finalizing XMPPConnection ( " + getConnectionCounter()
+ "): Shutting down executor services");
try {
// It's usually not a good idea to rely on finalize. But this is the easiest way to
// avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a
// reference to their ExecutorService which prevents the ExecutorService from being
// gc'ed. It is possible that the XMPPConnection instance is gc'ed while the
// listenerExecutor ExecutorService call not be gc'ed until it got shut down.
executorService.shutdownNow();
cachedExecutorService.shutdown();
removeCallbacksService.shutdownNow();
singleThreadedExecutorService.shutdownNow();
} catch (Throwable t) {
LOGGER.log(Level.WARNING, "finalize() threw trhowable", t);
}
finally {
super.finalize();
}
}
protected final void parseFeatures(XmlPullParser parser) throws XmlPullParserException,
IOException, SmackException {
streamFeatures.clear();
final int initialDepth = parser.getDepth();
while (true) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) {
ExtensionElement streamFeature = null;
String name = parser.getName();
String namespace = parser.getNamespace();
switch (name) {
case StartTls.ELEMENT:
streamFeature = PacketParserUtils.parseStartTlsFeature(parser);
break;
case Mechanisms.ELEMENT:
streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser));
break;
case Bind.ELEMENT:
streamFeature = Bind.Feature.INSTANCE;
break;
case Session.ELEMENT:
streamFeature = PacketParserUtils.parseSessionFeature(parser);
break;
case Compress.Feature.ELEMENT:
streamFeature = PacketParserUtils.parseCompressionFeature(parser);
break;
default:
ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace);
if (provider != null) {
streamFeature = provider.parse(parser);
}
break;
}
if (streamFeature != null) {
addStreamFeature(streamFeature);
}
}
else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) {
break;
}
}
if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
// Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
|| config.getSecurityMode() == SecurityMode.disabled) {
saslFeatureReceived.reportSuccess();
}
}
// If the server reported the bind feature then we are that that we did SASL and maybe
// STARTTLS. We can then report that the last 'stream:features' have been parsed
if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
|| !config.isCompressionEnabled()) {
// This was was last features from the server is either it did not contain
// compression or if we disabled it
lastFeaturesReceived.reportSuccess();
}
}
afterFeaturesReceived();
}
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException {
// Default implementation does nothing
}
@SuppressWarnings("unchecked")
@Override
public <F extends ExtensionElement> F getFeature(String element, String namespace) {
return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace));
}
@Override
public boolean hasFeature(String element, String namespace) {
return getFeature(element, namespace) != null;
}
private void addStreamFeature(ExtensionElement feature) {
String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace());
streamFeatures.put(key, feature);
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
StanzaListener callback) throws NotConnectedException {
sendStanzaWithResponseCallback(stanza, replyFilter, callback, null);
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
StanzaListener callback, ExceptionCallback exceptionCallback)
throws NotConnectedException {
sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback,
getPacketReplyTimeout());
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter,
final StanzaListener callback, final ExceptionCallback exceptionCallback,
long timeout) throws NotConnectedException {
Objects.requireNonNull(stanza, "stanza must not be null");
// While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
// disallow it here in the async API as it makes no sense
Objects.requireNonNull(replyFilter, "replyFilter must not be null");
Objects.requireNonNull(callback, "callback must not be null");
final StanzaListener packetListener = new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws NotConnectedException {
try {
XMPPErrorException.ifHasErrorThenThrow(packet);
callback.processPacket(packet);
}
catch (XMPPErrorException e) {
if (exceptionCallback != null) {
exceptionCallback.processException(e);
}
}
finally {
removeAsyncStanzaListener(this);
}
}
};
removeCallbacksService.schedule(new Runnable() {
@Override
public void run() {
boolean removed = removeAsyncStanzaListener(packetListener);
// If the packetListener got removed, then it was never run and
// we never received a response, inform the exception callback
if (removed && exceptionCallback != null) {
exceptionCallback.processException(NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter));
}
}
}, timeout, TimeUnit.MILLISECONDS);
addAsyncStanzaListener(packetListener, replyFilter);
sendStanza(stanza);
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback)
throws NotConnectedException {
sendIqWithResponseCallback(iqRequest, callback, null);
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback,
ExceptionCallback exceptionCallback) throws NotConnectedException {
sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout());
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback,
final ExceptionCallback exceptionCallback, long timeout)
throws NotConnectedException {
StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this);
sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout);
}
@Override
public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
final StanzaListener packetListener = new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws NotConnectedException {
try {
callback.processPacket(packet);
} finally {
removeSyncStanzaListener(this);
}
}
};
addSyncStanzaListener(packetListener, packetFilter);
removeCallbacksService.schedule(new Runnable() {
@Override
public void run() {
removeSyncStanzaListener(packetListener);
}
}, getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
}
@Override
public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) {
final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace());
switch (iqRequestHandler.getType()) {
case set:
synchronized (setIqRequestHandler) {
return setIqRequestHandler.put(key, iqRequestHandler);
}
case get:
synchronized (getIqRequestHandler) {
return getIqRequestHandler.put(key, iqRequestHandler);
}
default:
throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
}
}
@Override
public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) {
return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(),
iqRequestHandler.getType());
}
@Override
public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
final String key = XmppStringUtils.generateKey(element, namespace);
switch (type) {
case set:
synchronized (setIqRequestHandler) {
return setIqRequestHandler.remove(key);
}
case get:
synchronized (getIqRequestHandler) {
return getIqRequestHandler.remove(key);
}
default:
throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
}
}
private long lastStanzaReceived;
public long getLastStanzaReceived() {
return lastStanzaReceived;
}
/**
* Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a
* stanza
*
* @param callback the callback to install
*/
public void setParsingExceptionCallback(ParsingExceptionCallback callback) {
parsingExceptionCallback = callback;
}
/**
* Get the current active parsing exception callback.
*
* @return the active exception callback or null if there is none
*/
public ParsingExceptionCallback getParsingExceptionCallback() {
return parsingExceptionCallback;
}
protected final void asyncGo(Runnable runnable) {
cachedExecutorService.execute(runnable);
}
protected final ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) {
return removeCallbacksService.schedule(runnable, delay, unit);
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_4768_0
|
crossvul-java_data_bad_2298_0
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_2298_0
|
crossvul-java_data_bad_2299_0
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.context.cache;
import java.util.LinkedList;
import java.util.List;
/**
* Caches beans over the life of a request, to allow for efficient bean lookups from proxies.
* Besides, can hold any ThreadLocals to be removed at the end of the request.
*
* @author Stuart Douglas
*/
public class RequestScopedCache {
private static final ThreadLocal<List<RequestScopedItem>> CACHE = new ThreadLocal<List<RequestScopedItem>>();
private RequestScopedCache() {
}
public static boolean isActive() {
return CACHE.get() != null;
}
private static void checkCacheForAdding(final List<RequestScopedItem> cache) {
if (cache == null) {
throw new IllegalStateException("Unable to add request scoped cache item when request cache is not active");
}
}
public static void addItem(final RequestScopedItem item) {
final List<RequestScopedItem> cache = CACHE.get();
checkCacheForAdding(cache);
cache.add(item);
}
public static boolean addItemIfActive(final RequestScopedItem item) {
final List<RequestScopedItem> cache = CACHE.get();
if (cache != null) {
cache.add(item);
return true;
}
return false;
}
public static boolean addItemIfActive(final ThreadLocal<?> item) {
final List<RequestScopedItem> cache = CACHE.get();
if (cache != null) {
cache.add(new RequestScopedItem() {
public void invalidate() {
item.remove();
}
});
return true;
}
return false;
}
public static void beginRequest() {
CACHE.set(new LinkedList<RequestScopedItem>());
}
/**
* ends the request and clears the cache. This can be called before the request is over,
* in which case the cache will be unavailable for the rest of the request.
*/
public static void endRequest() {
final List<RequestScopedItem> result = CACHE.get();
CACHE.remove();
if (result != null) {
for (final RequestScopedItem item : result) {
item.invalidate();
}
}
}
/**
* Flushes the bean cache. The cache remains available for the rest of the request.
*/
public static void invalidate() {
if (isActive()) {
endRequest();
beginRequest();
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_2299_0
|
crossvul-java_data_good_2298_2
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.contexts.cache;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jboss.weld.context.beanstore.ConversationNamingScheme;
@WebServlet(value = "/servlet", asyncSupported = true)
public class SimpleServlet extends HttpServlet {
@Inject
private ConversationScopedBean bean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
String sequence = req.getParameter("sequence");
String poison = req.getParameter("poison");
if ("getAndSet".equals(action)) {
// the value should always be foo
String value = bean.getAndSet("bar" + sequence);
resp.getWriter().println(value);
if (poison != null) {
// this is a poisoning request
// normal applications should never do something like this
// we just do this to cause an exception to be thrown out of ConversationContext.deactivate
req.removeAttribute(ConversationNamingScheme.PARAMETER_NAME);
}
} else {
throw new IllegalArgumentException(action);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_2298_2
|
crossvul-java_data_bad_2298_2
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_2298_2
|
crossvul-java_data_bad_2298_1
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_2298_1
|
crossvul-java_data_good_2300_2
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jboss.weld.Container;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.context.BoundContext;
import org.jboss.weld.context.ManagedContext;
import org.jboss.weld.context.cache.RequestScopedCache;
import org.jboss.weld.context.http.HttpRequestContext;
import org.jboss.weld.context.http.HttpRequestContextImpl;
import org.jboss.weld.context.http.HttpSessionContext;
import org.jboss.weld.context.http.HttpSessionDestructionContext;
import org.jboss.weld.event.FastEvent;
import org.jboss.weld.literal.DestroyedLiteral;
import org.jboss.weld.literal.InitializedLiteral;
import org.jboss.weld.logging.ServletLogger;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.servlet.spi.HttpContextActivationFilter;
import org.jboss.weld.util.reflection.Reflections;
/**
* Takes care of setting up and tearing down CDI contexts around an HTTP request and dispatching context lifecycle events.
*
* @author Jozef Hartinger
* @author Marko Luksa
*
*/
public class HttpContextLifecycle implements Service {
private static final String HTTP_SESSION = "org.jboss.weld." + HttpSession.class.getName();
private static final String INCLUDE_HEADER = "javax.servlet.include.request_uri";
private static final String FORWARD_HEADER = "javax.servlet.forward.request_uri";
private static final String REQUEST_DESTROYED = HttpContextLifecycle.class.getName() + ".request.destroyed";
private static final String GUARD_PARAMETER_NAME = "org.jboss.weld.context.ignore.guard.marker";
private static final Object GUARD_PARAMETER_VALUE = new Object();
private HttpSessionDestructionContext sessionDestructionContextCache;
private HttpSessionContext sessionContextCache;
private HttpRequestContext requestContextCache;
private volatile Boolean conversationActivationEnabled;
private final boolean ignoreForwards;
private final boolean ignoreIncludes;
private final BeanManagerImpl beanManager;
private final ConversationContextActivator conversationContextActivator;
private final HttpContextActivationFilter contextActivationFilter;
private final FastEvent<ServletContext> applicationInitializedEvent;
private final FastEvent<ServletContext> applicationDestroyedEvent;
private final FastEvent<HttpServletRequest> requestInitializedEvent;
private final FastEvent<HttpServletRequest> requestDestroyedEvent;
private final FastEvent<HttpSession> sessionInitializedEvent;
private final FastEvent<HttpSession> sessionDestroyedEvent;
private final ServletApiAbstraction servletApi;
private final ServletContextService servletContextService;
private final Container container;
private static final ThreadLocal<Counter> nestedInvocationGuard = new ThreadLocal<HttpContextLifecycle.Counter>();
private final boolean nestedInvocationGuardEnabled;
private static class Counter {
private int value = 1;
}
public HttpContextLifecycle(BeanManagerImpl beanManager, HttpContextActivationFilter contextActivationFilter, boolean ignoreForwards, boolean ignoreIncludes, boolean lazyConversationContext, boolean nestedInvocationGuardEnabled) {
this.beanManager = beanManager;
this.conversationContextActivator = new ConversationContextActivator(beanManager, lazyConversationContext);
this.conversationActivationEnabled = null;
this.ignoreForwards = ignoreForwards;
this.ignoreIncludes = ignoreIncludes;
this.contextActivationFilter = contextActivationFilter;
this.applicationInitializedEvent = FastEvent.of(ServletContext.class, beanManager, InitializedLiteral.APPLICATION);
this.applicationDestroyedEvent = FastEvent.of(ServletContext.class, beanManager, DestroyedLiteral.APPLICATION);
this.requestInitializedEvent = FastEvent.of(HttpServletRequest.class, beanManager, InitializedLiteral.REQUEST);
this.requestDestroyedEvent = FastEvent.of(HttpServletRequest.class, beanManager, DestroyedLiteral.REQUEST);
this.sessionInitializedEvent = FastEvent.of(HttpSession.class, beanManager, InitializedLiteral.SESSION);
this.sessionDestroyedEvent = FastEvent.of(HttpSession.class, beanManager, DestroyedLiteral.SESSION);
this.servletApi = beanManager.getServices().get(ServletApiAbstraction.class);
this.servletContextService = beanManager.getServices().get(ServletContextService.class);
this.nestedInvocationGuardEnabled = nestedInvocationGuardEnabled;
this.container = Container.instance(beanManager);
}
private HttpSessionDestructionContext getSessionDestructionContext() {
if (sessionDestructionContextCache == null) {
this.sessionDestructionContextCache = beanManager.instance().select(HttpSessionDestructionContext.class).get();
}
return sessionDestructionContextCache;
}
private HttpSessionContext getSessionContext() {
if (sessionContextCache == null) {
this.sessionContextCache = beanManager.instance().select(HttpSessionContext.class).get();
}
return sessionContextCache;
}
public HttpRequestContext getRequestContext() {
if (requestContextCache == null) {
this.requestContextCache = beanManager.instance().select(HttpRequestContext.class).get();
}
return requestContextCache;
}
public void contextInitialized(ServletContext ctx) {
servletContextService.contextInitialized(ctx);
synchronized (container) {
applicationInitializedEvent.fire(ctx);
}
}
public void contextDestroyed(ServletContext ctx) {
synchronized (container) {
applicationDestroyedEvent.fire(ctx);
}
}
public void sessionCreated(HttpSession session) {
SessionHolder.sessionCreated(session);
conversationContextActivator.sessionCreated(session);
sessionInitializedEvent.fire(session);
}
public void sessionDestroyed(HttpSession session) {
// Mark the session context and conversation contexts to destroy
// instances when appropriate
deactivateSessionDestructionContext(session);
boolean destroyed = getSessionContext().destroy(session);
SessionHolder.clear();
RequestScopedCache.endRequest();
if (destroyed) {
// we are outside of a request (the session timed out) and therefore the session was destroyed immediately
// we can fire the @Destroyed(SessionScoped.class) event immediately
sessionDestroyedEvent.fire(session);
} else {
// the old session won't be available at the time we destroy this request
// let's store its reference until then
if (getRequestContext() instanceof HttpRequestContextImpl) {
HttpServletRequest request = Reflections.<HttpRequestContextImpl> cast(getRequestContext()).getHttpServletRequest();
request.setAttribute(HTTP_SESSION, session);
}
}
}
private void deactivateSessionDestructionContext(HttpSession session) {
HttpSessionDestructionContext context = getSessionDestructionContext();
if (context.isActive()) {
context.deactivate();
context.dissociate(session);
}
}
public void requestInitialized(HttpServletRequest request, ServletContext ctx) {
if (nestedInvocationGuardEnabled) {
Counter counter = nestedInvocationGuard.get();
Object marker = request.getAttribute(GUARD_PARAMETER_NAME);
if (counter != null && marker != null) {
// this is a nested invocation, increment the counter and ignore this invocation
counter.value++;
return;
} else {
if (counter != null && marker == null) {
/*
* This request has not been processed yet but the guard is set already.
* That indicates, that the guard leaked from a previous request processing - most likely
* the Servlet container did not invoke listener methods symmetrically.
* Log a warning and recover by re-initializing the guard
*/
ServletLogger.LOG.guardLeak(counter.value);
}
// this is the initial (outer) invocation
nestedInvocationGuard.set(new Counter());
request.setAttribute(GUARD_PARAMETER_NAME, GUARD_PARAMETER_VALUE);
}
}
if (ignoreForwards && isForwardedRequest(request)) {
return;
}
if (ignoreIncludes && isIncludedRequest(request)) {
return;
}
if (!contextActivationFilter.accepts(request)) {
return;
}
ServletLogger.LOG.requestInitialized(request);
SessionHolder.requestInitialized(request);
getRequestContext().associate(request);
getSessionContext().associate(request);
if (conversationActivationEnabled) {
conversationContextActivator.associateConversationContext(request);
}
getRequestContext().activate();
getSessionContext().activate();
try {
if (conversationActivationEnabled) {
conversationContextActivator.activateConversationContext(request);
}
requestInitializedEvent.fire(request);
} catch (RuntimeException e) {
try {
requestDestroyed(request);
} catch (Exception ignored) {
// ignored in order to let the original exception be thrown
}
/*
* If the servlet container happens to call the destroyed callback again, ignore it.
*/
request.setAttribute(REQUEST_DESTROYED, Boolean.TRUE);
throw e;
}
}
public void requestDestroyed(HttpServletRequest request) {
if (isRequestDestroyed(request)) {
return;
}
if (nestedInvocationGuardEnabled) {
Counter counter = nestedInvocationGuard.get();
if (counter != null) {
counter.value--;
if (counter.value > 0) {
return; // this is a nested invocation, ignore it
} else {
nestedInvocationGuard.remove(); // this is the outer invocation
request.removeAttribute(GUARD_PARAMETER_NAME);
}
} else {
ServletLogger.LOG.guardNotSet();
return;
}
}
if (ignoreForwards && isForwardedRequest(request)) {
return;
}
if (ignoreIncludes && isIncludedRequest(request)) {
return;
}
if (!contextActivationFilter.accepts(request)) {
return;
}
ServletLogger.LOG.requestDestroyed(request);
try {
conversationContextActivator.deactivateConversationContext(request);
/*
* if this request has been switched to async then do not invalidate the context now
* as it will be invalidated at the end of the async operation.
*/
if (!servletApi.isAsyncSupported() || !servletApi.isAsyncStarted(request)) {
getRequestContext().invalidate();
}
safelyDeactivate(getRequestContext(), request);
// fire @Destroyed(RequestScoped.class)
requestDestroyedEvent.fire(request);
safelyDeactivate(getSessionContext(), request);
// fire @Destroyed(SessionScoped.class)
if (!getSessionContext().isValid()) {
sessionDestroyedEvent.fire((HttpSession) request.getAttribute(HTTP_SESSION));
}
} finally {
safelyDissociate(getRequestContext(), request);
// WFLY-1533 Underlying HTTP session may be invalid
safelyDissociate(getSessionContext(), request);
// Catch block is inside the activator method so that we're able to log the context
conversationContextActivator.disassociateConversationContext(request);
SessionHolder.clear();
}
}
public boolean isConversationActivationSet() {
return conversationActivationEnabled != null;
}
public void setConversationActivationEnabled(boolean conversationActivationEnabled) {
this.conversationActivationEnabled = conversationActivationEnabled;
}
@Override
public void cleanup() {
}
/**
* Some Servlet containers fire HttpServletListeners for include requests (inner requests caused by calling the include method of RequestDispatcher). This
* causes problems with context shut down as context manipulation is not reentrant. This method detects if this request is an included request or not.
*/
private boolean isIncludedRequest(HttpServletRequest request) {
return request.getAttribute(INCLUDE_HEADER) != null;
}
/**
* Some Servlet containers fire HttpServletListeners for forward requests (inner requests caused by calling the forward method of RequestDispatcher). This
* causes problems with context shut down as context manipulation is not reentrant. This method detects if this request is an forwarded request or not.
*/
private boolean isForwardedRequest(HttpServletRequest request) {
return request.getAttribute(FORWARD_HEADER) != null;
}
/**
* The way servlet containers react to an exception that occurs in a {@link ServletRequestListener} differs among servlet listeners. In certain containers
* the destroyed callback may be invoked multiple times, causing the latter invocations to fail as thread locals have already been unset. We use the
* {@link #REQUEST_DESTROYED} flag to indicate that all further invocations of the
* {@link ServletRequestListener#requestDestroyed(javax.servlet.ServletRequestEvent)} should be ignored by Weld.
*/
private boolean isRequestDestroyed(HttpServletRequest request) {
return request.getAttribute(REQUEST_DESTROYED) != null;
}
private <T> void safelyDissociate(BoundContext<T> context, T storage) {
try {
context.dissociate(storage);
} catch(Exception e) {
ServletLogger.LOG.unableToDissociateContext(context, storage);
ServletLogger.LOG.catchingDebug(e);
}
}
private void safelyDeactivate(ManagedContext context, HttpServletRequest request) {
try {
context.deactivate();
} catch(Exception e) {
ServletLogger.LOG.unableToDeactivateContext(context, request);
ServletLogger.LOG.catchingDebug(e);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_2300_2
|
crossvul-java_data_good_2298_0
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.contexts.cache;
import java.io.Serializable;
import javax.enterprise.context.ConversationScoped;
@ConversationScoped
public class ConversationScopedBean implements Serializable {
private String value = "foo";
public String getAndSet(String newValue) {
String old = value;
value = newValue;
return old;
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_2298_0
|
crossvul-java_data_bad_2300_1
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.servlet;
import java.util.function.Consumer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jboss.weld.context.AbstractConversationContext;
import org.jboss.weld.context.ConversationContext;
import org.jboss.weld.context.http.HttpConversationContext;
import org.jboss.weld.context.http.LazyHttpConversationContextImpl;
import org.jboss.weld.event.FastEvent;
import org.jboss.weld.literal.DestroyedLiteral;
import org.jboss.weld.literal.InitializedLiteral;
import org.jboss.weld.logging.ConversationLogger;
import org.jboss.weld.logging.ServletLogger;
import org.jboss.weld.manager.BeanManagerImpl;
/**
* This component takes care of activation/deactivation of the conversation context for a servlet request.
*
* @see ConversationFilter
* @see org.jboss.weld.servlet.WeldInitialListener
*
* @author Jozef Hartinger
* @author Marko Luksa
*
*/
public class ConversationContextActivator {
private static final String NO_CID = "nocid";
private static final String CONVERSATION_PROPAGATION = "conversationPropagation";
private static final String CONVERSATION_PROPAGATION_NONE = "none";
private static final String CONTEXT_ACTIVATED_IN_REQUEST = ConversationContextActivator.class.getName() + "CONTEXT_ACTIVATED_IN_REQUEST";
private final BeanManagerImpl beanManager;
private HttpConversationContext httpConversationContextCache;
private final FastEvent<HttpServletRequest> conversationInitializedEvent;
private final FastEvent<HttpServletRequest> conversationDestroyedEvent;
private final Consumer<HttpServletRequest> lazyInitializationCallback;
private final boolean lazy;
protected ConversationContextActivator(BeanManagerImpl beanManager, boolean lazy) {
this.beanManager = beanManager;
conversationInitializedEvent = FastEvent.of(HttpServletRequest.class, beanManager, InitializedLiteral.CONVERSATION);
conversationDestroyedEvent = FastEvent.of(HttpServletRequest.class, beanManager, DestroyedLiteral.CONVERSATION);
lazyInitializationCallback = lazy ? conversationInitializedEvent::fire : null;
this.lazy = lazy;
}
private HttpConversationContext httpConversationContext() {
if (httpConversationContextCache == null) {
this.httpConversationContextCache = beanManager.instance().select(HttpConversationContext.class).get();
}
return httpConversationContextCache;
}
public void startConversationContext(HttpServletRequest request) {
associateConversationContext(request);
activateConversationContext(request);
}
public void stopConversationContext(HttpServletRequest request) {
deactivateConversationContext(request);
}
// Conversation handling
protected void activateConversationContext(HttpServletRequest request) {
HttpConversationContext conversationContext = httpConversationContext();
/*
* Don't try to reactivate the ConversationContext if we have already activated it for this request WELD-877
*/
if (!isContextActivatedInRequest(request)) {
setContextActivatedInRequest(request);
activate(conversationContext, request);
} else {
/*
* We may have previously been associated with a ConversationContext, but the reference to that context may have been lost during a Servlet forward
* WELD-877
*/
conversationContext.dissociate(request);
conversationContext.associate(request);
activate(conversationContext, request);
}
}
private void activate(HttpConversationContext conversationContext, final HttpServletRequest request) {
if (lazy && conversationContext instanceof LazyHttpConversationContextImpl) {
LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext;
// Activation API should be improved so that it's possible to pass a callback for later execution
lazyConversationContext.activate(lazyInitializationCallback);
} else {
String cid = determineConversationId(request, conversationContext.getParameterName());
conversationContext.activate(cid);
if (cid == null) { // transient conversation
conversationInitializedEvent.fire(request);
}
}
}
protected void associateConversationContext(HttpServletRequest request) {
httpConversationContext().associate(request);
}
private void setContextActivatedInRequest(HttpServletRequest request) {
request.setAttribute(CONTEXT_ACTIVATED_IN_REQUEST, true);
}
private boolean isContextActivatedInRequest(HttpServletRequest request) {
Object result = request.getAttribute(CONTEXT_ACTIVATED_IN_REQUEST);
if (result == null) {
return false;
}
return (Boolean) result;
}
protected void deactivateConversationContext(HttpServletRequest request) {
ConversationContext conversationContext = httpConversationContext();
if (conversationContext.isActive()) {
// Only deactivate the context if one is already active, otherwise we get Exceptions
if (conversationContext instanceof LazyHttpConversationContextImpl) {
LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext;
if (!lazyConversationContext.isInitialized()) {
// if this lazy conversation has not been touched yet, just deactivate it
lazyConversationContext.deactivate();
return;
}
}
boolean isTransient = conversationContext.getCurrentConversation().isTransient();
if (ConversationLogger.LOG.isTraceEnabled()) {
if (isTransient) {
ConversationLogger.LOG.cleaningUpTransientConversation();
} else {
ConversationLogger.LOG.cleaningUpConversation(conversationContext.getCurrentConversation().getId());
}
}
conversationContext.invalidate();
conversationContext.deactivate();
if (isTransient) {
conversationDestroyedEvent.fire(request);
}
}
}
protected void disassociateConversationContext(HttpServletRequest request) {
try {
httpConversationContext().dissociate(request);
} catch (Exception e) {
ServletLogger.LOG.unableToDissociateContext(httpConversationContext(), request);
ServletLogger.LOG.catchingDebug(e);
}
}
public void sessionCreated(HttpSession session) {
HttpConversationContext httpConversationContext = httpConversationContext();
if (httpConversationContext instanceof AbstractConversationContext) {
AbstractConversationContext<?, ?> abstractConversationContext = (AbstractConversationContext<?, ?>) httpConversationContext;
abstractConversationContext.sessionCreated();
}
}
public static String determineConversationId(HttpServletRequest request, String parameterName) {
if (request == null) {
throw ConversationLogger.LOG.mustCallAssociateBeforeActivate();
}
if (request.getParameter(NO_CID) != null) {
return null; // ignore cid; WELD-919
}
if (CONVERSATION_PROPAGATION_NONE.equals(request.getParameter(CONVERSATION_PROPAGATION))) {
return null; // conversationPropagation=none (CDI-135)
}
String cidName = parameterName;
String cid = request.getParameter(cidName);
ConversationLogger.LOG.foundConversationFromRequest(cid);
return cid;
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_2300_1
|
crossvul-java_data_good_4768_1
|
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.tcp;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByClientException;
import org.jivesoftware.smack.SmackException.ConnectionException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByServerException;
import org.jivesoftware.smack.SynchronizationPoint;
import org.jivesoftware.smack.XMPPException.StreamErrorException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.compress.packet.Compressed;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.compress.packet.Compress;
import org.jivesoftware.smack.packet.Element;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.StreamOpen;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.StartTls;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Challenge;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.SASLFailure;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Success;
import org.jivesoftware.smack.sm.SMUtils;
import org.jivesoftware.smack.sm.StreamManagementException;
import org.jivesoftware.smack.sm.StreamManagementException.StreamIdDoesNotMatchException;
import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementCounterError;
import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementNotEnabledException;
import org.jivesoftware.smack.sm.packet.StreamManagement;
import org.jivesoftware.smack.sm.packet.StreamManagement.AckAnswer;
import org.jivesoftware.smack.sm.packet.StreamManagement.AckRequest;
import org.jivesoftware.smack.sm.packet.StreamManagement.Enable;
import org.jivesoftware.smack.sm.packet.StreamManagement.Enabled;
import org.jivesoftware.smack.sm.packet.StreamManagement.Failed;
import org.jivesoftware.smack.sm.packet.StreamManagement.Resume;
import org.jivesoftware.smack.sm.packet.StreamManagement.Resumed;
import org.jivesoftware.smack.sm.packet.StreamManagement.StreamManagementFeature;
import org.jivesoftware.smack.sm.predicates.Predicate;
import org.jivesoftware.smack.sm.provider.ParseStreamManagement;
import org.jivesoftware.smack.packet.PlainStreamElement;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.util.ArrayBlockingQueueWithShutdown;
import org.jivesoftware.smack.util.Async;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.TLSUtils;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jxmpp.util.XmppStringUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.PasswordCallback;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Creates a socket connection to an XMPP server. This is the default connection
* to an XMPP server and is specified in the XMPP Core (RFC 6120).
*
* @see XMPPConnection
* @author Matt Tucker
*/
public class XMPPTCPConnection extends AbstractXMPPConnection {
private static final int QUEUE_SIZE = 500;
private static final Logger LOGGER = Logger.getLogger(XMPPTCPConnection.class.getName());
/**
* The socket which is used for this connection.
*/
private Socket socket;
/**
*
*/
private boolean disconnectedButResumeable = false;
/**
* Flag to indicate if the socket was closed intentionally by Smack.
* <p>
* This boolean flag is used concurrently, therefore it is marked volatile.
* </p>
*/
private volatile boolean socketClosed = false;
private boolean usingTLS = false;
/**
* Protected access level because of unit test purposes
*/
protected PacketWriter packetWriter;
/**
* Protected access level because of unit test purposes
*/
protected PacketReader packetReader;
private final SynchronizationPoint<Exception> initalOpenStreamSend = new SynchronizationPoint<Exception>(this);
/**
*
*/
private final SynchronizationPoint<XMPPException> maybeCompressFeaturesReceived = new SynchronizationPoint<XMPPException>(
this);
/**
*
*/
private final SynchronizationPoint<XMPPException> compressSyncPoint = new SynchronizationPoint<XMPPException>(
this);
/**
* The default bundle and defer callback, used for new connections.
* @see bundleAndDeferCallback
*/
private static BundleAndDeferCallback defaultBundleAndDeferCallback;
/**
* The used bundle and defer callback.
* <p>
* Although this field may be set concurrently, the 'volatile' keyword was deliberately not added, in order to avoid
* having a 'volatile' read within the writer threads loop.
* </p>
*/
private BundleAndDeferCallback bundleAndDeferCallback = defaultBundleAndDeferCallback;
private static boolean useSmDefault = false;
private static boolean useSmResumptionDefault = true;
/**
* The stream ID of the stream that is currently resumable, ie. the stream we hold the state
* for in {@link #clientHandledStanzasCount}, {@link #serverHandledStanzasCount} and
* {@link #unacknowledgedStanzas}.
*/
private String smSessionId;
private final SynchronizationPoint<XMPPException> smResumedSyncPoint = new SynchronizationPoint<XMPPException>(
this);
private final SynchronizationPoint<XMPPException> smEnabledSyncPoint = new SynchronizationPoint<XMPPException>(
this);
/**
* The client's preferred maximum resumption time in seconds.
*/
private int smClientMaxResumptionTime = -1;
/**
* The server's preferred maximum resumption time in seconds.
*/
private int smServerMaxResumptimTime = -1;
/**
* Indicates whether Stream Management (XEP-198) should be used if it's supported by the server.
*/
private boolean useSm = useSmDefault;
private boolean useSmResumption = useSmResumptionDefault;
/**
* The counter that the server sends the client about it's current height. For example, if the server sends
* {@code <a h='42'/>}, then this will be set to 42 (while also handling the {@link #unacknowledgedStanzas} queue).
*/
private long serverHandledStanzasCount = 0;
/**
* The counter for stanzas handled ("received") by the client.
* <p>
* Note that we don't need to synchronize this counter. Although JLS 17.7 states that reads and writes to longs are
* not atomic, it guarantees that there are at most 2 separate writes, one to each 32-bit half. And since
* {@link SMUtils#incrementHeight(long)} masks the lower 32 bit, we only operate on one half of the long and
* therefore have no concurrency problem because the read/write operations on one half are guaranteed to be atomic.
* </p>
*/
private long clientHandledStanzasCount = 0;
private BlockingQueue<Stanza> unacknowledgedStanzas;
/**
* Set to true if Stream Management was at least once enabled for this connection.
*/
private boolean smWasEnabledAtLeastOnce = false;
/**
* This listeners are invoked for every stanza that got acknowledged.
* <p>
* We use a {@link ConccurrentLinkedQueue} here in order to allow the listeners to remove
* themselves after they have been invoked.
* </p>
*/
private final Collection<StanzaListener> stanzaAcknowledgedListeners = new ConcurrentLinkedQueue<StanzaListener>();
/**
* This listeners are invoked for a acknowledged stanza that has the given stanza ID. They will
* only be invoked once and automatically removed after that.
*/
private final Map<String, StanzaListener> stanzaIdAcknowledgedListeners = new ConcurrentHashMap<String, StanzaListener>();
/**
* Predicates that determine if an stream management ack should be requested from the server.
* <p>
* We use a linked hash set here, so that the order how the predicates are added matches the
* order in which they are invoked in order to determine if an ack request should be send or not.
* </p>
*/
private final Set<StanzaFilter> requestAckPredicates = new LinkedHashSet<StanzaFilter>();
private final XMPPTCPConnectionConfiguration config;
/**
* Creates a new XMPP connection over TCP (optionally using proxies).
* <p>
* Note that XMPPTCPConnection constructors do not establish a connection to the server
* and you must call {@link #connect()}.
* </p>
*
* @param config the connection configuration.
*/
public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) {
super(config);
this.config = config;
addConnectionListener(new AbstractConnectionListener() {
@Override
public void connectionClosedOnError(Exception e) {
if (e instanceof XMPPException.StreamErrorException) {
dropSmState();
}
}
});
}
/**
* Creates a new XMPP connection over TCP.
* <p>
* Note that {@code jid} must be the bare JID, e.g. "user@example.org". More fine-grained control over the
* connection settings is available using the {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)}
* constructor.
* </p>
*
* @param jid the bare JID used by the client.
* @param password the password or authentication token.
*/
public XMPPTCPConnection(CharSequence jid, String password) {
this(XmppStringUtils.parseLocalpart(jid.toString()), password, XmppStringUtils.parseDomain(jid.toString()));
}
/**
* Creates a new XMPP connection over TCP.
* <p>
* This is the simplest constructor for connecting to an XMPP server. Alternatively,
* you can get fine-grained control over connection settings using the
* {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)} constructor.
* </p>
* @param username
* @param password
* @param serviceName
*/
public XMPPTCPConnection(CharSequence username, String password, String serviceName) {
this(XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(username, password).setServiceName(
serviceName).build());
}
@Override
protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
if (packetWriter == null) {
throw new NotConnectedException();
}
packetWriter.throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
}
@Override
protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
if (isConnected() && !disconnectedButResumeable) {
throw new AlreadyConnectedException();
}
}
@Override
protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
if (isAuthenticated() && !disconnectedButResumeable) {
throw new AlreadyLoggedInException();
}
}
@Override
protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException {
// Reset the flag in case it was set
disconnectedButResumeable = false;
super.afterSuccessfulLogin(resumed);
}
@Override
protected synchronized void loginNonAnonymously(String username, String password, String resource) throws XMPPException, SmackException, IOException {
if (saslAuthentication.hasNonAnonymousAuthentication()) {
// Authenticate using SASL
if (password != null) {
saslAuthentication.authenticate(username, password, resource);
}
else {
saslAuthentication.authenticate(resource, config.getCallbackHandler());
}
} else {
throw new SmackException("No non-anonymous SASL authentication mechanism available");
}
// If compression is enabled then request the server to use stream compression. XEP-170
// recommends to perform stream compression before resource binding.
if (config.isCompressionEnabled()) {
useCompression();
}
if (isSmResumptionPossible()) {
smResumedSyncPoint.sendAndWaitForResponse(new Resume(clientHandledStanzasCount, smSessionId));
if (smResumedSyncPoint.wasSuccessful()) {
// We successfully resumed the stream, be done here
afterSuccessfulLogin(true);
return;
}
// SM resumption failed, what Smack does here is to report success of
// lastFeaturesReceived in case of sm resumption was answered with 'failed' so that
// normal resource binding can be tried.
LOGGER.fine("Stream resumption failed, continuing with normal stream establishment process");
}
List<Stanza> previouslyUnackedStanzas = new LinkedList<Stanza>();
if (unacknowledgedStanzas != null) {
// There was a previous connection with SM enabled but that was either not resumable or
// failed to resume. Make sure that we (re-)send the unacknowledged stanzas.
unacknowledgedStanzas.drainTo(previouslyUnackedStanzas);
// Reset unacknowledged stanzas to 'null' to signal that we never send 'enable' in this
// XMPP session (There maybe was an enabled in a previous XMPP session of this
// connection instance though). This is used in writePackets to decide if stanzas should
// be added to the unacknowledged stanzas queue, because they have to be added right
// after the 'enable' stream element has been sent.
dropSmState();
}
// Now bind the resource. It is important to do this *after* we dropped an eventually
// existing Stream Management state. As otherwise <bind/> and <session/> may end up in
// unacknowledgedStanzas and become duplicated on reconnect. See SMACK-706.
bindResourceAndEstablishSession(resource);
if (isSmAvailable() && useSm) {
// Remove what is maybe left from previously stream managed sessions
serverHandledStanzasCount = 0;
// XEP-198 3. Enabling Stream Management. If the server response to 'Enable' is 'Failed'
// then this is a non recoverable error and we therefore throw an exception.
smEnabledSyncPoint.sendAndWaitForResponseOrThrow(new Enable(useSmResumption, smClientMaxResumptionTime));
synchronized (requestAckPredicates) {
if (requestAckPredicates.isEmpty()) {
// Assure that we have at lest one predicate set up that so that we request acks
// for the server and eventually flush some stanzas from the unacknowledged
// stanza queue
requestAckPredicates.add(Predicate.forMessagesOrAfter5Stanzas());
}
}
}
// (Re-)send the stanzas *after* we tried to enable SM
for (Stanza stanza : previouslyUnackedStanzas) {
sendStanzaInternal(stanza);
}
afterSuccessfulLogin(false);
}
@Override
public synchronized void loginAnonymously() throws XMPPException, SmackException, IOException {
// Wait with SASL auth until the SASL mechanisms have been received
saslFeatureReceived.checkIfSuccessOrWaitOrThrow();
if (saslAuthentication.hasAnonymousAuthentication()) {
saslAuthentication.authenticateAnonymously();
}
else {
throw new SmackException("No anonymous SASL authentication mechanism available");
}
// If compression is enabled then request the server to use stream compression
if (config.isCompressionEnabled()) {
useCompression();
}
bindResourceAndEstablishSession(null);
afterSuccessfulLogin(false);
}
@Override
public boolean isSecureConnection() {
return usingTLS;
}
public boolean isSocketClosed() {
return socketClosed;
}
/**
* Shuts the current connection down. After this method returns, the connection must be ready
* for re-use by connect.
*/
@Override
protected void shutdown() {
if (isSmEnabled()) {
try {
// Try to send a last SM Acknowledgement. Most servers won't find this information helpful, as the SM
// state is dropped after a clean disconnect anyways. OTOH it doesn't hurt much either.
sendSmAcknowledgementInternal();
} catch (NotConnectedException e) {
LOGGER.log(Level.FINE, "Can not send final SM ack as connection is not connected", e);
}
}
shutdown(false);
}
/**
* Performs an unclean disconnect and shutdown of the connection. Does not send a closing stream stanza.
*/
public synchronized void instantShutdown() {
shutdown(true);
}
private void shutdown(boolean instant) {
if (disconnectedButResumeable) {
return;
}
if (packetReader != null) {
packetReader.shutdown();
}
if (packetWriter != null) {
packetWriter.shutdown(instant);
}
// Set socketClosed to true. This will cause the PacketReader
// and PacketWriter to ignore any Exceptions that are thrown
// because of a read/write from/to a closed stream.
// It is *important* that this is done before socket.close()!
socketClosed = true;
try {
socket.close();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "shutdown", e);
}
setWasAuthenticated();
// If we are able to resume the stream, then don't set
// connected/authenticated/usingTLS to false since we like behave like we are still
// connected (e.g. sendStanza should not throw a NotConnectedException).
if (isSmResumptionPossible() && instant) {
disconnectedButResumeable = true;
} else {
disconnectedButResumeable = false;
// Reset the stream management session id to null, since if the stream is cleanly closed, i.e. sending a closing
// stream tag, there is no longer a stream to resume.
smSessionId = null;
}
authenticated = false;
connected = false;
usingTLS = false;
reader = null;
writer = null;
maybeCompressFeaturesReceived.init();
compressSyncPoint.init();
smResumedSyncPoint.init();
smEnabledSyncPoint.init();
initalOpenStreamSend.init();
}
@Override
public void send(PlainStreamElement element) throws NotConnectedException {
packetWriter.sendStreamElement(element);
}
@Override
protected void sendStanzaInternal(Stanza packet) throws NotConnectedException {
packetWriter.sendStreamElement(packet);
if (isSmEnabled()) {
for (StanzaFilter requestAckPredicate : requestAckPredicates) {
if (requestAckPredicate.accept(packet)) {
requestSmAcknowledgementInternal();
break;
}
}
}
}
private void connectUsingConfiguration() throws IOException, ConnectionException {
List<HostAddress> failedAddresses = populateHostAddresses();
SocketFactory socketFactory = config.getSocketFactory();
if (socketFactory == null) {
socketFactory = SocketFactory.getDefault();
}
for (HostAddress hostAddress : hostAddresses) {
String host = hostAddress.getFQDN();
int port = hostAddress.getPort();
socket = socketFactory.createSocket();
try {
Iterator<InetAddress> inetAddresses = Arrays.asList(InetAddress.getAllByName(host)).iterator();
if (!inetAddresses.hasNext()) {
// This should not happen
LOGGER.warning("InetAddress.getAllByName() returned empty result array.");
throw new UnknownHostException(host);
}
innerloop: while (inetAddresses.hasNext()) {
// Create a *new* Socket before every connection attempt, i.e. connect() call, since Sockets are not
// re-usable after a failed connection attempt. See also SMACK-724.
socket = socketFactory.createSocket();
final InetAddress inetAddress = inetAddresses.next();
final String inetAddressAndPort = inetAddress + " at port " + port;
LOGGER.finer("Trying to establish TCP connection to " + inetAddressAndPort);
try {
socket.connect(new InetSocketAddress(inetAddress, port), config.getConnectTimeout());
} catch (Exception e) {
if (inetAddresses.hasNext()) {
continue innerloop;
} else {
throw e;
}
}
LOGGER.finer("Established TCP connection to " + inetAddressAndPort);
// We found a host to connect to, return here
this.host = host;
this.port = port;
return;
}
}
catch (Exception e) {
hostAddress.setException(e);
failedAddresses.add(hostAddress);
}
}
// There are no more host addresses to try
// throw an exception and report all tried
// HostAddresses in the exception
throw ConnectionException.from(failedAddresses);
}
/**
* Initializes the connection by creating a stanza(/packet) reader and writer and opening a
* XMPP stream to the server.
*
* @throws XMPPException if establishing a connection to the server fails.
* @throws SmackException if the server failes to respond back or if there is anther error.
* @throws IOException
*/
private void initConnection() throws IOException {
boolean isFirstInitialization = packetReader == null || packetWriter == null;
compressionHandler = null;
// Set the reader and writer instance variables
initReaderAndWriter();
if (isFirstInitialization) {
packetWriter = new PacketWriter();
packetReader = new PacketReader();
// If debugging is enabled, we should start the thread that will listen for
// all packets and then log them.
if (config.isDebuggerEnabled()) {
addAsyncStanzaListener(debugger.getReaderListener(), null);
if (debugger.getWriterListener() != null) {
addPacketSendingListener(debugger.getWriterListener(), null);
}
}
}
// Start the packet writer. This will open an XMPP stream to the server
packetWriter.init();
// Start the packet reader. The startup() method will block until we
// get an opening stream packet back from server
packetReader.init();
if (isFirstInitialization) {
// Notify listeners that a new connection has been established
for (ConnectionCreationListener listener : getConnectionCreationListeners()) {
listener.connectionCreated(this);
}
}
}
private void initReaderAndWriter() throws IOException {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
if (compressionHandler != null) {
is = compressionHandler.getInputStream(is);
os = compressionHandler.getOutputStream(os);
}
// OutputStreamWriter is already buffered, no need to wrap it into a BufferedWriter
writer = new OutputStreamWriter(os, "UTF-8");
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// If debugging is enabled, we open a window and write out all network traffic.
initDebugger();
}
/**
* The server has indicated that TLS negotiation can start. We now need to secure the
* existing plain connection and perform a handshake. This method won't return until the
* connection has finished the handshake or an error occurred while securing the connection.
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
* @throws SmackException
* @throws Exception if an exception occurs.
*/
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
SSLContext context = this.config.getCustomSSLContext();
KeyStore ks = null;
KeyManager[] kms = null;
PasswordCallback pcb = null;
if(config.getCallbackHandler() == null) {
ks = null;
} else if (context == null) {
if(config.getKeystoreType().equals("NONE")) {
ks = null;
pcb = null;
}
else if(config.getKeystoreType().equals("PKCS11")) {
try {
Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library();
ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
Provider p = (Provider)c.newInstance(config);
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11",p);
pcb = new PasswordCallback("PKCS11 Password: ",false);
this.config.getCallbackHandler().handle(new Callback[]{pcb});
ks.load(null,pcb.getPassword());
}
catch (Exception e) {
ks = null;
pcb = null;
}
}
else if(config.getKeystoreType().equals("Apple")) {
ks = KeyStore.getInstance("KeychainStore","Apple");
ks.load(null,null);
//pcb = new PasswordCallback("Apple Keychain",false);
//pcb.setPassword(null);
}
else {
ks = KeyStore.getInstance(config.getKeystoreType());
try {
pcb = new PasswordCallback("Keystore Password: ",false);
config.getCallbackHandler().handle(new Callback[]{pcb});
ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
}
catch(Exception e) {
ks = null;
pcb = null;
}
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
try {
if(pcb == null) {
kmf.init(ks,null);
} else {
kmf.init(ks,pcb.getPassword());
pcb.clearPassword();
}
kms = kmf.getKeyManagers();
} catch (NullPointerException npe) {
kms = null;
}
}
// If the user didn't specify a SSLContext, use the default one
if (context == null) {
context = SSLContext.getInstance("TLS");
context.init(kms, null, new java.security.SecureRandom());
}
Socket plain = socket;
// Secure the plain connection
socket = context.getSocketFactory().createSocket(plain,
host, plain.getPort(), true);
final SSLSocket sslSocket = (SSLSocket) socket;
// Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
// important (at least on certain platforms) and it seems to be a good idea anyways to
// prevent an accidental implicit handshake.
TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
// Initialize the reader and writer with the new secured version
initReaderAndWriter();
// Proceed to do the handshake
sslSocket.startHandshake();
final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
if (verifier == null) {
throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
} else if (!verifier.verify(getServiceName(), sslSocket.getSession())) {
throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getServiceName());
}
// Set that TLS was successful
usingTLS = true;
}
/**
* Returns the compression handler that can be used for one compression methods offered by the server.
*
* @return a instance of XMPPInputOutputStream or null if no suitable instance was found
*
*/
private XMPPInputOutputStream maybeGetCompressionHandler() {
Compress.Feature compression = getFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE);
if (compression == null) {
// Server does not support compression
return null;
}
for (XMPPInputOutputStream handler : SmackConfiguration.getCompresionHandlers()) {
String method = handler.getCompressionMethod();
if (compression.getMethods().contains(method))
return handler;
}
return null;
}
@Override
public boolean isUsingCompression() {
return compressionHandler != null && compressSyncPoint.wasSuccessful();
}
/**
* <p>
* Starts using stream compression that will compress network traffic. Traffic can be
* reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
* connection. However, the server and the client will need to use more CPU time in order to
* un/compress network data so under high load the server performance might be affected.
* </p>
* <p>
* Stream compression has to have been previously offered by the server. Currently only the
* zlib method is supported by the client. Stream compression negotiation has to be done
* before authentication took place.
* </p>
*
* @throws NotConnectedException
* @throws XMPPException
* @throws NoResponseException
*/
private void useCompression() throws NotConnectedException, NoResponseException, XMPPException {
maybeCompressFeaturesReceived.checkIfSuccessOrWait();
// If stream compression was offered by the server and we want to use
// compression then send compression request to the server
if ((compressionHandler = maybeGetCompressionHandler()) != null) {
compressSyncPoint.sendAndWaitForResponseOrThrow(new Compress(compressionHandler.getCompressionMethod()));
} else {
LOGGER.warning("Could not enable compression because no matching handler/method pair was found");
}
}
/**
* Establishes a connection to the XMPP server and performs an automatic login
* only if the previous connection state was logged (authenticated). It basically
* creates and maintains a socket connection to the server.<p>
* <p/>
* Listeners will be preserved from a previous connection if the reconnection
* occurs after an abrupt termination.
*
* @throws XMPPException if an error occurs while trying to establish the connection.
* @throws SmackException
* @throws IOException
*/
@Override
protected void connectInternal() throws SmackException, IOException, XMPPException {
// Establishes the TCP connection to the server and does setup the reader and writer. Throws an exception if
// there is an error establishing the connection
connectUsingConfiguration();
// We connected successfully to the servers TCP port
socketClosed = false;
initConnection();
// Wait with SASL auth until the SASL mechanisms have been received
saslFeatureReceived.checkIfSuccessOrWaitOrThrow();
// If TLS is required but the server doesn't offer it, disconnect
// from the server and throw an error. First check if we've already negotiated TLS
// and are secure, however (features get parsed a second time after TLS is established).
if (!isSecureConnection() && getConfiguration().getSecurityMode() == SecurityMode.required) {
shutdown();
throw new SecurityRequiredByClientException();
}
// Make note of the fact that we're now connected.
connected = true;
callConnectionConnectedListener();
// Automatically makes the login if the user was previously connected successfully
// to the server and the connection was terminated abruptly
if (wasAuthenticated) {
login();
notifyReconnection();
}
}
/**
* Sends out a notification that there was an error with the connection
* and closes the connection. Also prints the stack trace of the given exception
*
* @param e the exception that causes the connection close event.
*/
private synchronized void notifyConnectionError(Exception e) {
// Listeners were already notified of the exception, return right here.
if ((packetReader == null || packetReader.done) &&
(packetWriter == null || packetWriter.done())) return;
// Closes the connection temporary. A reconnection is possible
instantShutdown();
// Notify connection listeners of the error.
callConnectionClosedOnErrorListener(e);
}
/**
* For unit testing purposes
*
* @param writer
*/
protected void setWriter(Writer writer) {
this.writer = writer;
}
@Override
protected void afterFeaturesReceived() throws NotConnectedException {
StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
if (startTlsFeature != null) {
if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
notifyConnectionError(new SecurityRequiredByServerException());
return;
}
if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
send(new StartTls());
}
}
if (getSASLAuthentication().authenticationSuccessful()) {
// If we have received features after the SASL has been successfully completed, then we
// have also *maybe* received, as it is an optional feature, the compression feature
// from the server.
maybeCompressFeaturesReceived.reportSuccess();
}
}
/**
* Resets the parser using the latest connection's reader. Reseting the parser is necessary
* when the plain connection has been secured or when a new opening stream element is going
* to be sent by the server.
*
* @throws SmackException if the parser could not be reset.
*/
void openStream() throws SmackException {
// If possible, provide the receiving entity of the stream open tag, i.e. the server, as much information as
// possible. The 'to' attribute is *always* available. The 'from' attribute if set by the user and no external
// mechanism is used to determine the local entity (user). And the 'id' attribute is available after the first
// response from the server (see e.g. RFC 6120 § 9.1.1 Step 2.)
CharSequence to = getServiceName();
CharSequence from = null;
CharSequence localpart = config.getUsername();
if (localpart != null) {
from = XmppStringUtils.completeJidFrom(localpart, to);
}
String id = getStreamId();
send(new StreamOpen(to, from, id));
try {
packetReader.parser = PacketParserUtils.newXmppParser(reader);
}
catch (XmlPullParserException e) {
throw new SmackException(e);
}
}
protected class PacketReader {
XmlPullParser parser;
private volatile boolean done;
/**
* Initializes the reader in order to be used. The reader is initialized during the
* first connection and when reconnecting due to an abruptly disconnection.
*/
void init() {
done = false;
Async.go(new Runnable() {
public void run() {
parsePackets();
}
}, "Smack Packet Reader (" + getConnectionCounter() + ")");
}
/**
* Shuts the stanza(/packet) reader down. This method simply sets the 'done' flag to true.
*/
void shutdown() {
done = true;
}
/**
* Parse top-level packets in order to process them further.
*
* @param thread the thread that is being used by the reader to parse incoming packets.
*/
private void parsePackets() {
try {
initalOpenStreamSend.checkIfSuccessOrWait();
int eventType = parser.getEventType();
while (!done) {
switch (eventType) {
case XmlPullParser.START_TAG:
final String name = parser.getName();
switch (name) {
case Message.ELEMENT:
case IQ.IQ_ELEMENT:
case Presence.ELEMENT:
try {
parseAndProcessStanza(parser);
} finally {
clientHandledStanzasCount = SMUtils.incrementHeight(clientHandledStanzasCount);
}
break;
case "stream":
// We found an opening stream.
if ("jabber:client".equals(parser.getNamespace(null))) {
streamId = parser.getAttributeValue("", "id");
String reportedServiceName = parser.getAttributeValue("", "from");
assert(reportedServiceName.equals(config.getServiceName()));
}
break;
case "error":
throw new StreamErrorException(PacketParserUtils.parseStreamError(parser));
case "features":
parseFeatures(parser);
break;
case "proceed":
try {
// Secure the connection by negotiating TLS
proceedTLSReceived();
// Send a new opening stream to the server
openStream();
}
catch (Exception e) {
// We report any failure regarding TLS in the second stage of XMPP
// connection establishment, namely the SASL authentication
saslFeatureReceived.reportFailure(new SmackException(e));
throw e;
}
break;
case "failure":
String namespace = parser.getNamespace(null);
switch (namespace) {
case "urn:ietf:params:xml:ns:xmpp-tls":
// TLS negotiation has failed. The server will close the connection
// TODO Parse failure stanza
throw new XMPPErrorException("TLS negotiation has failed", null);
case "http://jabber.org/protocol/compress":
// Stream compression has been denied. This is a recoverable
// situation. It is still possible to authenticate and
// use the connection but using an uncompressed connection
// TODO Parse failure stanza
compressSyncPoint.reportFailure(new XMPPErrorException(
"Could not establish compression", null));
break;
case SaslStreamElements.NAMESPACE:
// SASL authentication has failed. The server may close the connection
// depending on the number of retries
final SASLFailure failure = PacketParserUtils.parseSASLFailure(parser);
getSASLAuthentication().authenticationFailed(failure);
break;
}
break;
case Challenge.ELEMENT:
// The server is challenging the SASL authentication made by the client
String challengeData = parser.nextText();
getSASLAuthentication().challengeReceived(challengeData);
break;
case Success.ELEMENT:
Success success = new Success(parser.nextText());
// We now need to bind a resource for the connection
// Open a new stream and wait for the response
openStream();
// The SASL authentication with the server was successful. The next step
// will be to bind the resource
getSASLAuthentication().authenticated(success);
break;
case Compressed.ELEMENT:
// Server confirmed that it's possible to use stream compression. Start
// stream compression
// Initialize the reader and writer with the new compressed version
initReaderAndWriter();
// Send a new opening stream to the server
openStream();
// Notify that compression is being used
compressSyncPoint.reportSuccess();
break;
case Enabled.ELEMENT:
Enabled enabled = ParseStreamManagement.enabled(parser);
if (enabled.isResumeSet()) {
smSessionId = enabled.getId();
if (StringUtils.isNullOrEmpty(smSessionId)) {
XMPPErrorException xmppException = new XMPPErrorException(
"Stream Management 'enabled' element with resume attribute but without session id received",
new XMPPError(
XMPPError.Condition.bad_request));
smEnabledSyncPoint.reportFailure(xmppException);
throw xmppException;
}
smServerMaxResumptimTime = enabled.getMaxResumptionTime();
} else {
// Mark this a non-resumable stream by setting smSessionId to null
smSessionId = null;
}
clientHandledStanzasCount = 0;
smWasEnabledAtLeastOnce = true;
smEnabledSyncPoint.reportSuccess();
LOGGER.fine("Stream Management (XEP-198): succesfully enabled");
break;
case Failed.ELEMENT:
Failed failed = ParseStreamManagement.failed(parser);
XMPPError xmppError = new XMPPError(failed.getXMPPErrorCondition());
XMPPException xmppException = new XMPPErrorException("Stream Management failed", xmppError);
// If only XEP-198 would specify different failure elements for the SM
// enable and SM resume failure case. But this is not the case, so we
// need to determine if this is a 'Failed' response for either 'Enable'
// or 'Resume'.
if (smResumedSyncPoint.requestSent()) {
smResumedSyncPoint.reportFailure(xmppException);
}
else {
if (!smEnabledSyncPoint.requestSent()) {
throw new IllegalStateException("Failed element received but SM was not previously enabled");
}
smEnabledSyncPoint.reportFailure(xmppException);
// Report success for last lastFeaturesReceived so that in case a
// failed resumption, we can continue with normal resource binding.
// See text of XEP-198 5. below Example 11.
lastFeaturesReceived.reportSuccess();
}
break;
case Resumed.ELEMENT:
Resumed resumed = ParseStreamManagement.resumed(parser);
if (!smSessionId.equals(resumed.getPrevId())) {
throw new StreamIdDoesNotMatchException(smSessionId, resumed.getPrevId());
}
// Mark SM as enabled and resumption as successful.
smResumedSyncPoint.reportSuccess();
smEnabledSyncPoint.reportSuccess();
// First, drop the stanzas already handled by the server
processHandledCount(resumed.getHandledCount());
// Then re-send what is left in the unacknowledged queue
List<Stanza> stanzasToResend = new ArrayList<>(unacknowledgedStanzas.size());
unacknowledgedStanzas.drainTo(stanzasToResend);
for (Stanza stanza : stanzasToResend) {
sendStanzaInternal(stanza);
}
// If there where stanzas resent, then request a SM ack for them.
// Writer's sendStreamElement() won't do it automatically based on
// predicates.
if (!stanzasToResend.isEmpty()) {
requestSmAcknowledgementInternal();
}
LOGGER.fine("Stream Management (XEP-198): Stream resumed");
break;
case AckAnswer.ELEMENT:
AckAnswer ackAnswer = ParseStreamManagement.ackAnswer(parser);
processHandledCount(ackAnswer.getHandledCount());
break;
case AckRequest.ELEMENT:
ParseStreamManagement.ackRequest(parser);
if (smEnabledSyncPoint.wasSuccessful()) {
sendSmAcknowledgementInternal();
} else {
LOGGER.warning("SM Ack Request received while SM is not enabled");
}
break;
default:
LOGGER.warning("Unknown top level stream element: " + name);
break;
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("stream")) {
// Disconnect the connection
disconnect();
}
break;
case XmlPullParser.END_DOCUMENT:
// END_DOCUMENT only happens in an error case, as otherwise we would see a
// closing stream element before.
throw new SmackException(
"Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element");
}
eventType = parser.next();
}
}
catch (Exception e) {
// The exception can be ignored if the the connection is 'done'
// or if the it was caused because the socket got closed
if (!(done || isSocketClosed())) {
// Close the connection and notify connection listeners of the
// error.
notifyConnectionError(e);
}
}
}
}
protected class PacketWriter {
public static final int QUEUE_SIZE = XMPPTCPConnection.QUEUE_SIZE;
private final ArrayBlockingQueueWithShutdown<Element> queue = new ArrayBlockingQueueWithShutdown<Element>(
QUEUE_SIZE, true);
/**
* Needs to be protected for unit testing purposes.
*/
protected SynchronizationPoint<NoResponseException> shutdownDone = new SynchronizationPoint<NoResponseException>(
XMPPTCPConnection.this);
/**
* If set, the stanza(/packet) writer is shut down
*/
protected volatile Long shutdownTimestamp = null;
private volatile boolean instantShutdown;
/**
* True if some preconditions are given to start the bundle and defer mechanism.
* <p>
* This will likely get set to true right after the start of the writer thread, because
* {@link #nextStreamElement()} will check if {@link queue} is empty, which is probably the case, and then set
* this field to true.
* </p>
*/
private boolean shouldBundleAndDefer;
/**
* Initializes the writer in order to be used. It is called at the first connection and also
* is invoked if the connection is disconnected by an error.
*/
void init() {
shutdownDone.init();
shutdownTimestamp = null;
if (unacknowledgedStanzas != null) {
// It's possible that there are new stanzas in the writer queue that
// came in while we were disconnected but resumable, drain those into
// the unacknowledged queue so that they get resent now
drainWriterQueueToUnacknowledgedStanzas();
}
queue.start();
Async.go(new Runnable() {
@Override
public void run() {
writePackets();
}
}, "Smack Packet Writer (" + getConnectionCounter() + ")");
}
private boolean done() {
return shutdownTimestamp != null;
}
protected void throwNotConnectedExceptionIfDoneAndResumptionNotPossible() throws NotConnectedException {
if (done() && !isSmResumptionPossible()) {
// Don't throw a NotConnectedException is there is an resumable stream available
throw new NotConnectedException();
}
}
/**
* Sends the specified element to the server.
*
* @param element the element to send.
* @throws NotConnectedException
*/
protected void sendStreamElement(Element element) throws NotConnectedException {
throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
boolean enqueued = false;
while (!enqueued) {
try {
queue.put(element);
enqueued = true;
}
catch (InterruptedException e) {
throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
// If the method above did not throw, then the sending thread was interrupted
// TODO in a later version of Smack the InterruptedException should be thrown to
// allow users to interrupt a sending thread that is currently blocking because
// the queue is full.
LOGGER.log(Level.WARNING, "Sending thread was interrupted", e);
}
}
}
/**
* Shuts down the stanza(/packet) writer. Once this method has been called, no further
* packets will be written to the server.
*/
void shutdown(boolean instant) {
instantShutdown = instant;
shutdownTimestamp = System.currentTimeMillis();
queue.shutdown();
try {
shutdownDone.checkIfSuccessOrWait();
}
catch (NoResponseException e) {
LOGGER.log(Level.WARNING, "shutdownDone was not marked as successful by the writer thread", e);
}
}
/**
* Maybe return the next available element from the queue for writing. If the queue is shut down <b>or</b> a
* spurious interrupt occurs, <code>null</code> is returned. So it is important to check the 'done' condition in
* that case.
*
* @return the next element for writing or null.
*/
private Element nextStreamElement() {
// It is important the we check if the queue is empty before removing an element from it
if (queue.isEmpty()) {
shouldBundleAndDefer = true;
}
Element packet = null;
try {
packet = queue.take();
}
catch (InterruptedException e) {
if (!queue.isShutdown()) {
// Users shouldn't try to interrupt the packet writer thread
LOGGER.log(Level.WARNING, "Packet writer thread was interrupted. Don't do that. Use disconnect() instead.", e);
}
}
return packet;
}
private void writePackets() {
try {
openStream();
initalOpenStreamSend.reportSuccess();
// Write out packets from the queue.
while (!done()) {
Element element = nextStreamElement();
if (element == null) {
continue;
}
// Get a local version of the bundle and defer callback, in case it's unset
// between the null check and the method invocation
final BundleAndDeferCallback localBundleAndDeferCallback = bundleAndDeferCallback;
// If the preconditions are given (e.g. bundleAndDefer callback is set, queue is
// empty), then we could wait a bit for further stanzas attempting to decrease
// our energy consumption
if (localBundleAndDeferCallback != null && isAuthenticated() && shouldBundleAndDefer) {
// Reset shouldBundleAndDefer to false, nextStreamElement() will set it to true once the
// queue is empty again.
shouldBundleAndDefer = false;
final AtomicBoolean bundlingAndDeferringStopped = new AtomicBoolean();
final int bundleAndDeferMillis = localBundleAndDeferCallback.getBundleAndDeferMillis(new BundleAndDefer(
bundlingAndDeferringStopped));
if (bundleAndDeferMillis > 0) {
long remainingWait = bundleAndDeferMillis;
final long waitStart = System.currentTimeMillis();
synchronized (bundlingAndDeferringStopped) {
while (!bundlingAndDeferringStopped.get() && remainingWait > 0) {
bundlingAndDeferringStopped.wait(remainingWait);
remainingWait = bundleAndDeferMillis
- (System.currentTimeMillis() - waitStart);
}
}
}
}
Stanza packet = null;
if (element instanceof Stanza) {
packet = (Stanza) element;
}
else if (element instanceof Enable) {
// The client needs to add messages to the unacknowledged stanzas queue
// right after it sent 'enabled'. Stanza will be added once
// unacknowledgedStanzas is not null.
unacknowledgedStanzas = new ArrayBlockingQueue<>(QUEUE_SIZE);
}
// Check if the stream element should be put to the unacknowledgedStanza
// queue. Note that we can not do the put() in sendStanzaInternal() and the
// packet order is not stable at this point (sendStanzaInternal() can be
// called concurrently).
if (unacknowledgedStanzas != null && packet != null) {
// If the unacknowledgedStanza queue is nearly full, request an new ack
// from the server in order to drain it
if (unacknowledgedStanzas.size() == 0.8 * XMPPTCPConnection.QUEUE_SIZE) {
writer.write(AckRequest.INSTANCE.toXML().toString());
writer.flush();
}
try {
// It is important the we put the stanza in the unacknowledged stanza
// queue before we put it on the wire
unacknowledgedStanzas.put(packet);
}
catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
writer.write(element.toXML().toString());
if (queue.isEmpty()) {
writer.flush();
}
if (packet != null) {
firePacketSendingListeners(packet);
}
}
if (!instantShutdown) {
// Flush out the rest of the queue.
try {
while (!queue.isEmpty()) {
Element packet = queue.remove();
writer.write(packet.toXML().toString());
}
writer.flush();
}
catch (Exception e) {
LOGGER.log(Level.WARNING,
"Exception flushing queue during shutdown, ignore and continue",
e);
}
// Close the stream.
try {
writer.write("</stream:stream>");
writer.flush();
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception writing closing stream element", e);
}
// Delete the queue contents (hopefully nothing is left).
queue.clear();
} else if (instantShutdown && isSmEnabled()) {
// This was an instantShutdown and SM is enabled, drain all remaining stanzas
// into the unacknowledgedStanzas queue
drainWriterQueueToUnacknowledgedStanzas();
}
try {
writer.close();
}
catch (Exception e) {
// Do nothing
}
}
catch (Exception e) {
// The exception can be ignored if the the connection is 'done'
// or if the it was caused because the socket got closed
if (!(done() || isSocketClosed())) {
notifyConnectionError(e);
} else {
LOGGER.log(Level.FINE, "Ignoring Exception in writePackets()", e);
}
} finally {
LOGGER.fine("Reporting shutdownDone success in writer thread");
shutdownDone.reportSuccess();
}
}
private void drainWriterQueueToUnacknowledgedStanzas() {
List<Element> elements = new ArrayList<Element>(queue.size());
queue.drainTo(elements);
for (Element element : elements) {
if (element instanceof Stanza) {
unacknowledgedStanzas.add((Stanza) element);
}
}
}
}
/**
* Set if Stream Management should be used by default for new connections.
*
* @param useSmDefault true to use Stream Management for new connections.
*/
public static void setUseStreamManagementDefault(boolean useSmDefault) {
XMPPTCPConnection.useSmDefault = useSmDefault;
}
/**
* Set if Stream Management resumption should be used by default for new connections.
*
* @param useSmResumptionDefault true to use Stream Management resumption for new connections.
* @deprecated use {@link #setUseStreamManagementResumptionDefault(boolean)} instead.
*/
@Deprecated
public static void setUseStreamManagementResumptiodDefault(boolean useSmResumptionDefault) {
setUseStreamManagementResumptionDefault(useSmResumptionDefault);
}
/**
* Set if Stream Management resumption should be used by default for new connections.
*
* @param useSmResumptionDefault true to use Stream Management resumption for new connections.
*/
public static void setUseStreamManagementResumptionDefault(boolean useSmResumptionDefault) {
if (useSmResumptionDefault) {
// Also enable SM is resumption is enabled
setUseStreamManagementDefault(useSmResumptionDefault);
}
XMPPTCPConnection.useSmResumptionDefault = useSmResumptionDefault;
}
/**
* Set if Stream Management should be used if supported by the server.
*
* @param useSm true to use Stream Management.
*/
public void setUseStreamManagement(boolean useSm) {
this.useSm = useSm;
}
/**
* Set if Stream Management resumption should be used if supported by the server.
*
* @param useSmResumption true to use Stream Management resumption.
*/
public void setUseStreamManagementResumption(boolean useSmResumption) {
if (useSmResumption) {
// Also enable SM is resumption is enabled
setUseStreamManagement(useSmResumption);
}
this.useSmResumption = useSmResumption;
}
/**
* Set the preferred resumption time in seconds.
* @param resumptionTime the preferred resumption time in seconds
*/
public void setPreferredResumptionTime(int resumptionTime) {
smClientMaxResumptionTime = resumptionTime;
}
/**
* Add a predicate for Stream Management acknowledgment requests.
* <p>
* Those predicates are used to determine when a Stream Management acknowledgement request is send to the server.
* Some pre-defined predicates are found in the <code>org.jivesoftware.smack.sm.predicates</code> package.
* </p>
* <p>
* If not predicate is configured, the {@link Predicate#forMessagesOrAfter5Stanzas()} will be used.
* </p>
*
* @param predicate the predicate to add.
* @return if the predicate was not already active.
*/
public boolean addRequestAckPredicate(StanzaFilter predicate) {
synchronized (requestAckPredicates) {
return requestAckPredicates.add(predicate);
}
}
/**
* Remove the given predicate for Stream Management acknowledgment request.
* @param predicate the predicate to remove.
* @return true if the predicate was removed.
*/
public boolean removeRequestAckPredicate(StanzaFilter predicate) {
synchronized (requestAckPredicates) {
return requestAckPredicates.remove(predicate);
}
}
/**
* Remove all predicates for Stream Management acknowledgment requests.
*/
public void removeAllRequestAckPredicates() {
synchronized (requestAckPredicates) {
requestAckPredicates.clear();
}
}
/**
* Send an unconditional Stream Management acknowledgement request to the server.
*
* @throws StreamManagementNotEnabledException if Stream Mangement is not enabled.
* @throws NotConnectedException if the connection is not connected.
*/
public void requestSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException {
if (!isSmEnabled()) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
requestSmAcknowledgementInternal();
}
private void requestSmAcknowledgementInternal() throws NotConnectedException {
packetWriter.sendStreamElement(AckRequest.INSTANCE);
}
/**
* Send a unconditional Stream Management acknowledgment to the server.
* <p>
* See <a href="http://xmpp.org/extensions/xep-0198.html#acking">XEP-198: Stream Management § 4. Acks</a>:
* "Either party MAY send an <a/> element at any time (e.g., after it has received a certain number of stanzas,
* or after a certain period of time), even if it has not received an <r/> element from the other party."
* </p>
*
* @throws StreamManagementNotEnabledException if Stream Management is not enabled.
* @throws NotConnectedException if the connection is not connected.
*/
public void sendSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException {
if (!isSmEnabled()) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
sendSmAcknowledgementInternal();
}
private void sendSmAcknowledgementInternal() throws NotConnectedException {
packetWriter.sendStreamElement(new AckAnswer(clientHandledStanzasCount));
}
/**
* Add a Stanza acknowledged listener.
* <p>
* Those listeners will be invoked every time a Stanza has been acknowledged by the server. The will not get
* automatically removed. Consider using {@link #addStanzaIdAcknowledgedListener(String, StanzaListener)} when
* possible.
* </p>
*
* @param listener the listener to add.
*/
public void addStanzaAcknowledgedListener(StanzaListener listener) {
stanzaAcknowledgedListeners.add(listener);
}
/**
* Remove the given Stanza acknowledged listener.
*
* @param listener the listener.
* @return true if the listener was removed.
*/
public boolean removeStanzaAcknowledgedListener(StanzaListener listener) {
return stanzaAcknowledgedListeners.remove(listener);
}
/**
* Remove all stanza acknowledged listeners.
*/
public void removeAllStanzaAcknowledgedListeners() {
stanzaAcknowledgedListeners.clear();
}
/**
* Add a new Stanza ID acknowledged listener for the given ID.
* <p>
* The listener will be invoked if the stanza with the given ID was acknowledged by the server. It will
* automatically be removed after the listener was run.
* </p>
*
* @param id the stanza ID.
* @param listener the listener to invoke.
* @return the previous listener for this stanza ID or null.
* @throws StreamManagementNotEnabledException if Stream Management is not enabled.
*/
public StanzaListener addStanzaIdAcknowledgedListener(final String id, StanzaListener listener) throws StreamManagementNotEnabledException {
// Prevent users from adding callbacks that will never get removed
if (!smWasEnabledAtLeastOnce) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
// Remove the listener after max. 12 hours
final int removeAfterSeconds = Math.min(getMaxSmResumptionTime(), 12 * 60 * 60);
schedule(new Runnable() {
@Override
public void run() {
stanzaIdAcknowledgedListeners.remove(id);
}
}, removeAfterSeconds, TimeUnit.SECONDS);
return stanzaIdAcknowledgedListeners.put(id, listener);
}
/**
* Remove the Stanza ID acknowledged listener for the given ID.
*
* @param id the stanza ID.
* @return true if the listener was found and removed, false otherwise.
*/
public StanzaListener removeStanzaIdAcknowledgedListener(String id) {
return stanzaIdAcknowledgedListeners.remove(id);
}
/**
* Removes all Stanza ID acknowledged listeners.
*/
public void removeAllStanzaIdAcknowledgedListeners() {
stanzaIdAcknowledgedListeners.clear();
}
/**
* Returns true if Stream Management is supported by the server.
*
* @return true if Stream Management is supported by the server.
*/
public boolean isSmAvailable() {
return hasFeature(StreamManagementFeature.ELEMENT, StreamManagement.NAMESPACE);
}
/**
* Returns true if Stream Management was successfully negotiated with the server.
*
* @return true if Stream Management was negotiated.
*/
public boolean isSmEnabled() {
return smEnabledSyncPoint.wasSuccessful();
}
/**
* Returns true if the stream was successfully resumed with help of Stream Management.
*
* @return true if the stream was resumed.
*/
public boolean streamWasResumed() {
return smResumedSyncPoint.wasSuccessful();
}
/**
* Returns true if the connection is disconnected by a Stream resumption via Stream Management is possible.
*
* @return true if disconnected but resumption possible.
*/
public boolean isDisconnectedButSmResumptionPossible() {
return disconnectedButResumeable && isSmResumptionPossible();
}
/**
* Returns true if the stream is resumable.
*
* @return true if the stream is resumable.
*/
public boolean isSmResumptionPossible() {
// There is no resumable stream available
if (smSessionId == null)
return false;
final Long shutdownTimestamp = packetWriter.shutdownTimestamp;
// Seems like we are already reconnected, report true
if (shutdownTimestamp == null) {
return true;
}
// See if resumption time is over
long current = System.currentTimeMillis();
long maxResumptionMillies = ((long) getMaxSmResumptionTime()) * 1000;
if (current > shutdownTimestamp + maxResumptionMillies) {
// Stream resumption is *not* possible if the current timestamp is greater then the greatest timestamp where
// resumption is possible
return false;
} else {
return true;
}
}
/**
* Drop the stream management state. Sets {@link #smSessionId} and
* {@link #unacknowledgedStanzas} to <code>null</code>.
*/
private void dropSmState() {
// clientHandledCount and serverHandledCount will be reset on <enable/> and <enabled/>
// respective. No need to reset them here.
smSessionId = null;
unacknowledgedStanzas = null;
}
/**
* Get the maximum resumption time in seconds after which a managed stream can be resumed.
* <p>
* This method will return {@link Integer#MAX_VALUE} if neither the client nor the server specify a maximum
* resumption time. Be aware of integer overflows when using this value, e.g. do not add arbitrary values to it
* without checking for overflows before.
* </p>
*
* @return the maximum resumption time in seconds or {@link Integer#MAX_VALUE} if none set.
*/
public int getMaxSmResumptionTime() {
int clientResumptionTime = smClientMaxResumptionTime > 0 ? smClientMaxResumptionTime : Integer.MAX_VALUE;
int serverResumptionTime = smServerMaxResumptimTime > 0 ? smServerMaxResumptimTime : Integer.MAX_VALUE;
return Math.min(clientResumptionTime, serverResumptionTime);
}
private void processHandledCount(long handledCount) throws StreamManagementCounterError {
long ackedStanzasCount = SMUtils.calculateDelta(handledCount, serverHandledStanzasCount);
final List<Stanza> ackedStanzas = new ArrayList<Stanza>(
ackedStanzasCount <= Integer.MAX_VALUE ? (int) ackedStanzasCount
: Integer.MAX_VALUE);
for (long i = 0; i < ackedStanzasCount; i++) {
Stanza ackedStanza = unacknowledgedStanzas.poll();
// If the server ack'ed a stanza, then it must be in the
// unacknowledged stanza queue. There can be no exception.
if (ackedStanza == null) {
throw new StreamManagementCounterError(handledCount, serverHandledStanzasCount,
ackedStanzasCount, ackedStanzas);
}
ackedStanzas.add(ackedStanza);
}
boolean atLeastOneStanzaAcknowledgedListener = false;
if (!stanzaAcknowledgedListeners.isEmpty()) {
// If stanzaAcknowledgedListeners is not empty, the we have at least one
atLeastOneStanzaAcknowledgedListener = true;
}
else {
// Otherwise we look for a matching id in the stanza *id* acknowledged listeners
for (Stanza ackedStanza : ackedStanzas) {
String id = ackedStanza.getStanzaId();
if (id != null && stanzaIdAcknowledgedListeners.containsKey(id)) {
atLeastOneStanzaAcknowledgedListener = true;
break;
}
}
}
// Only spawn a new thread if there is a chance that some listener is invoked
if (atLeastOneStanzaAcknowledgedListener) {
asyncGo(new Runnable() {
@Override
public void run() {
for (Stanza ackedStanza : ackedStanzas) {
for (StanzaListener listener : stanzaAcknowledgedListeners) {
try {
listener.processPacket(ackedStanza);
}
catch (NotConnectedException e) {
LOGGER.log(Level.FINER, "Received not connected exception", e);
}
}
String id = ackedStanza.getStanzaId();
if (StringUtils.isNullOrEmpty(id)) {
continue;
}
StanzaListener listener = stanzaIdAcknowledgedListeners.remove(id);
if (listener != null) {
try {
listener.processPacket(ackedStanza);
}
catch (NotConnectedException e) {
LOGGER.log(Level.FINER, "Received not connected exception", e);
}
}
}
}
});
}
serverHandledStanzasCount = handledCount;
}
/**
* Set the default bundle and defer callback used for new connections.
*
* @param defaultBundleAndDeferCallback
* @see BundleAndDeferCallback
* @since 4.1
*/
public static void setDefaultBundleAndDeferCallback(BundleAndDeferCallback defaultBundleAndDeferCallback) {
XMPPTCPConnection.defaultBundleAndDeferCallback = defaultBundleAndDeferCallback;
}
/**
* Set the bundle and defer callback used for this connection.
* <p>
* You can use <code>null</code> as argument to reset the callback. Outgoing stanzas will then
* no longer get deferred.
* </p>
*
* @param bundleAndDeferCallback the callback or <code>null</code>.
* @see BundleAndDeferCallback
* @since 4.1
*/
public void setBundleandDeferCallback(BundleAndDeferCallback bundleAndDeferCallback) {
this.bundleAndDeferCallback = bundleAndDeferCallback;
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_4768_1
|
crossvul-java_data_bad_4768_1
|
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.tcp;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.ConnectionException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByClientException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByServerException;
import org.jivesoftware.smack.SmackException.SecurityRequiredException;
import org.jivesoftware.smack.SynchronizationPoint;
import org.jivesoftware.smack.XMPPException.StreamErrorException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.compress.packet.Compressed;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.compress.packet.Compress;
import org.jivesoftware.smack.packet.Element;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.StreamOpen;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.StartTls;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Challenge;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.SASLFailure;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Success;
import org.jivesoftware.smack.sm.SMUtils;
import org.jivesoftware.smack.sm.StreamManagementException;
import org.jivesoftware.smack.sm.StreamManagementException.StreamIdDoesNotMatchException;
import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementCounterError;
import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementNotEnabledException;
import org.jivesoftware.smack.sm.packet.StreamManagement;
import org.jivesoftware.smack.sm.packet.StreamManagement.AckAnswer;
import org.jivesoftware.smack.sm.packet.StreamManagement.AckRequest;
import org.jivesoftware.smack.sm.packet.StreamManagement.Enable;
import org.jivesoftware.smack.sm.packet.StreamManagement.Enabled;
import org.jivesoftware.smack.sm.packet.StreamManagement.Failed;
import org.jivesoftware.smack.sm.packet.StreamManagement.Resume;
import org.jivesoftware.smack.sm.packet.StreamManagement.Resumed;
import org.jivesoftware.smack.sm.packet.StreamManagement.StreamManagementFeature;
import org.jivesoftware.smack.sm.predicates.Predicate;
import org.jivesoftware.smack.sm.provider.ParseStreamManagement;
import org.jivesoftware.smack.packet.PlainStreamElement;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.util.ArrayBlockingQueueWithShutdown;
import org.jivesoftware.smack.util.Async;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.TLSUtils;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jxmpp.util.XmppStringUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.PasswordCallback;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Creates a socket connection to an XMPP server. This is the default connection
* to an XMPP server and is specified in the XMPP Core (RFC 6120).
*
* @see XMPPConnection
* @author Matt Tucker
*/
public class XMPPTCPConnection extends AbstractXMPPConnection {
private static final int QUEUE_SIZE = 500;
private static final Logger LOGGER = Logger.getLogger(XMPPTCPConnection.class.getName());
/**
* The socket which is used for this connection.
*/
private Socket socket;
/**
*
*/
private boolean disconnectedButResumeable = false;
/**
* Flag to indicate if the socket was closed intentionally by Smack.
* <p>
* This boolean flag is used concurrently, therefore it is marked volatile.
* </p>
*/
private volatile boolean socketClosed = false;
private boolean usingTLS = false;
/**
* Protected access level because of unit test purposes
*/
protected PacketWriter packetWriter;
/**
* Protected access level because of unit test purposes
*/
protected PacketReader packetReader;
private final SynchronizationPoint<Exception> initalOpenStreamSend = new SynchronizationPoint<Exception>(this);
/**
*
*/
private final SynchronizationPoint<XMPPException> maybeCompressFeaturesReceived = new SynchronizationPoint<XMPPException>(
this);
/**
*
*/
private final SynchronizationPoint<XMPPException> compressSyncPoint = new SynchronizationPoint<XMPPException>(
this);
/**
* The default bundle and defer callback, used for new connections.
* @see bundleAndDeferCallback
*/
private static BundleAndDeferCallback defaultBundleAndDeferCallback;
/**
* The used bundle and defer callback.
* <p>
* Although this field may be set concurrently, the 'volatile' keyword was deliberately not added, in order to avoid
* having a 'volatile' read within the writer threads loop.
* </p>
*/
private BundleAndDeferCallback bundleAndDeferCallback = defaultBundleAndDeferCallback;
private static boolean useSmDefault = false;
private static boolean useSmResumptionDefault = true;
/**
* The stream ID of the stream that is currently resumable, ie. the stream we hold the state
* for in {@link #clientHandledStanzasCount}, {@link #serverHandledStanzasCount} and
* {@link #unacknowledgedStanzas}.
*/
private String smSessionId;
private final SynchronizationPoint<XMPPException> smResumedSyncPoint = new SynchronizationPoint<XMPPException>(
this);
private final SynchronizationPoint<XMPPException> smEnabledSyncPoint = new SynchronizationPoint<XMPPException>(
this);
/**
* The client's preferred maximum resumption time in seconds.
*/
private int smClientMaxResumptionTime = -1;
/**
* The server's preferred maximum resumption time in seconds.
*/
private int smServerMaxResumptimTime = -1;
/**
* Indicates whether Stream Management (XEP-198) should be used if it's supported by the server.
*/
private boolean useSm = useSmDefault;
private boolean useSmResumption = useSmResumptionDefault;
/**
* The counter that the server sends the client about it's current height. For example, if the server sends
* {@code <a h='42'/>}, then this will be set to 42 (while also handling the {@link #unacknowledgedStanzas} queue).
*/
private long serverHandledStanzasCount = 0;
/**
* The counter for stanzas handled ("received") by the client.
* <p>
* Note that we don't need to synchronize this counter. Although JLS 17.7 states that reads and writes to longs are
* not atomic, it guarantees that there are at most 2 separate writes, one to each 32-bit half. And since
* {@link SMUtils#incrementHeight(long)} masks the lower 32 bit, we only operate on one half of the long and
* therefore have no concurrency problem because the read/write operations on one half are guaranteed to be atomic.
* </p>
*/
private long clientHandledStanzasCount = 0;
private BlockingQueue<Stanza> unacknowledgedStanzas;
/**
* Set to true if Stream Management was at least once enabled for this connection.
*/
private boolean smWasEnabledAtLeastOnce = false;
/**
* This listeners are invoked for every stanza that got acknowledged.
* <p>
* We use a {@link ConccurrentLinkedQueue} here in order to allow the listeners to remove
* themselves after they have been invoked.
* </p>
*/
private final Collection<StanzaListener> stanzaAcknowledgedListeners = new ConcurrentLinkedQueue<StanzaListener>();
/**
* This listeners are invoked for a acknowledged stanza that has the given stanza ID. They will
* only be invoked once and automatically removed after that.
*/
private final Map<String, StanzaListener> stanzaIdAcknowledgedListeners = new ConcurrentHashMap<String, StanzaListener>();
/**
* Predicates that determine if an stream management ack should be requested from the server.
* <p>
* We use a linked hash set here, so that the order how the predicates are added matches the
* order in which they are invoked in order to determine if an ack request should be send or not.
* </p>
*/
private final Set<StanzaFilter> requestAckPredicates = new LinkedHashSet<StanzaFilter>();
private final XMPPTCPConnectionConfiguration config;
/**
* Creates a new XMPP connection over TCP (optionally using proxies).
* <p>
* Note that XMPPTCPConnection constructors do not establish a connection to the server
* and you must call {@link #connect()}.
* </p>
*
* @param config the connection configuration.
*/
public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) {
super(config);
this.config = config;
addConnectionListener(new AbstractConnectionListener() {
@Override
public void connectionClosedOnError(Exception e) {
if (e instanceof XMPPException.StreamErrorException) {
dropSmState();
}
}
});
}
/**
* Creates a new XMPP connection over TCP.
* <p>
* Note that {@code jid} must be the bare JID, e.g. "user@example.org". More fine-grained control over the
* connection settings is available using the {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)}
* constructor.
* </p>
*
* @param jid the bare JID used by the client.
* @param password the password or authentication token.
*/
public XMPPTCPConnection(CharSequence jid, String password) {
this(XmppStringUtils.parseLocalpart(jid.toString()), password, XmppStringUtils.parseDomain(jid.toString()));
}
/**
* Creates a new XMPP connection over TCP.
* <p>
* This is the simplest constructor for connecting to an XMPP server. Alternatively,
* you can get fine-grained control over connection settings using the
* {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)} constructor.
* </p>
* @param username
* @param password
* @param serviceName
*/
public XMPPTCPConnection(CharSequence username, String password, String serviceName) {
this(XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(username, password).setServiceName(
serviceName).build());
}
@Override
protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
if (packetWriter == null) {
throw new NotConnectedException();
}
packetWriter.throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
}
@Override
protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
if (isConnected() && !disconnectedButResumeable) {
throw new AlreadyConnectedException();
}
}
@Override
protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
if (isAuthenticated() && !disconnectedButResumeable) {
throw new AlreadyLoggedInException();
}
}
@Override
protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException {
// Reset the flag in case it was set
disconnectedButResumeable = false;
super.afterSuccessfulLogin(resumed);
}
@Override
protected synchronized void loginNonAnonymously(String username, String password, String resource) throws XMPPException, SmackException, IOException {
if (saslAuthentication.hasNonAnonymousAuthentication()) {
// Authenticate using SASL
if (password != null) {
saslAuthentication.authenticate(username, password, resource);
}
else {
saslAuthentication.authenticate(resource, config.getCallbackHandler());
}
} else {
throw new SmackException("No non-anonymous SASL authentication mechanism available");
}
// If compression is enabled then request the server to use stream compression. XEP-170
// recommends to perform stream compression before resource binding.
if (config.isCompressionEnabled()) {
useCompression();
}
if (isSmResumptionPossible()) {
smResumedSyncPoint.sendAndWaitForResponse(new Resume(clientHandledStanzasCount, smSessionId));
if (smResumedSyncPoint.wasSuccessful()) {
// We successfully resumed the stream, be done here
afterSuccessfulLogin(true);
return;
}
// SM resumption failed, what Smack does here is to report success of
// lastFeaturesReceived in case of sm resumption was answered with 'failed' so that
// normal resource binding can be tried.
LOGGER.fine("Stream resumption failed, continuing with normal stream establishment process");
}
List<Stanza> previouslyUnackedStanzas = new LinkedList<Stanza>();
if (unacknowledgedStanzas != null) {
// There was a previous connection with SM enabled but that was either not resumable or
// failed to resume. Make sure that we (re-)send the unacknowledged stanzas.
unacknowledgedStanzas.drainTo(previouslyUnackedStanzas);
// Reset unacknowledged stanzas to 'null' to signal that we never send 'enable' in this
// XMPP session (There maybe was an enabled in a previous XMPP session of this
// connection instance though). This is used in writePackets to decide if stanzas should
// be added to the unacknowledged stanzas queue, because they have to be added right
// after the 'enable' stream element has been sent.
dropSmState();
}
// Now bind the resource. It is important to do this *after* we dropped an eventually
// existing Stream Management state. As otherwise <bind/> and <session/> may end up in
// unacknowledgedStanzas and become duplicated on reconnect. See SMACK-706.
bindResourceAndEstablishSession(resource);
if (isSmAvailable() && useSm) {
// Remove what is maybe left from previously stream managed sessions
serverHandledStanzasCount = 0;
// XEP-198 3. Enabling Stream Management. If the server response to 'Enable' is 'Failed'
// then this is a non recoverable error and we therefore throw an exception.
smEnabledSyncPoint.sendAndWaitForResponseOrThrow(new Enable(useSmResumption, smClientMaxResumptionTime));
synchronized (requestAckPredicates) {
if (requestAckPredicates.isEmpty()) {
// Assure that we have at lest one predicate set up that so that we request acks
// for the server and eventually flush some stanzas from the unacknowledged
// stanza queue
requestAckPredicates.add(Predicate.forMessagesOrAfter5Stanzas());
}
}
}
// (Re-)send the stanzas *after* we tried to enable SM
for (Stanza stanza : previouslyUnackedStanzas) {
sendStanzaInternal(stanza);
}
afterSuccessfulLogin(false);
}
@Override
public synchronized void loginAnonymously() throws XMPPException, SmackException, IOException {
// Wait with SASL auth until the SASL mechanisms have been received
saslFeatureReceived.checkIfSuccessOrWaitOrThrow();
if (saslAuthentication.hasAnonymousAuthentication()) {
saslAuthentication.authenticateAnonymously();
}
else {
throw new SmackException("No anonymous SASL authentication mechanism available");
}
// If compression is enabled then request the server to use stream compression
if (config.isCompressionEnabled()) {
useCompression();
}
bindResourceAndEstablishSession(null);
afterSuccessfulLogin(false);
}
@Override
public boolean isSecureConnection() {
return usingTLS;
}
public boolean isSocketClosed() {
return socketClosed;
}
/**
* Shuts the current connection down. After this method returns, the connection must be ready
* for re-use by connect.
*/
@Override
protected void shutdown() {
if (isSmEnabled()) {
try {
// Try to send a last SM Acknowledgement. Most servers won't find this information helpful, as the SM
// state is dropped after a clean disconnect anyways. OTOH it doesn't hurt much either.
sendSmAcknowledgementInternal();
} catch (NotConnectedException e) {
LOGGER.log(Level.FINE, "Can not send final SM ack as connection is not connected", e);
}
}
shutdown(false);
}
/**
* Performs an unclean disconnect and shutdown of the connection. Does not send a closing stream stanza.
*/
public synchronized void instantShutdown() {
shutdown(true);
}
private void shutdown(boolean instant) {
if (disconnectedButResumeable) {
return;
}
if (packetReader != null) {
packetReader.shutdown();
}
if (packetWriter != null) {
packetWriter.shutdown(instant);
}
// Set socketClosed to true. This will cause the PacketReader
// and PacketWriter to ignore any Exceptions that are thrown
// because of a read/write from/to a closed stream.
// It is *important* that this is done before socket.close()!
socketClosed = true;
try {
socket.close();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "shutdown", e);
}
setWasAuthenticated();
// If we are able to resume the stream, then don't set
// connected/authenticated/usingTLS to false since we like behave like we are still
// connected (e.g. sendStanza should not throw a NotConnectedException).
if (isSmResumptionPossible() && instant) {
disconnectedButResumeable = true;
} else {
disconnectedButResumeable = false;
// Reset the stream management session id to null, since if the stream is cleanly closed, i.e. sending a closing
// stream tag, there is no longer a stream to resume.
smSessionId = null;
}
authenticated = false;
connected = false;
usingTLS = false;
reader = null;
writer = null;
maybeCompressFeaturesReceived.init();
compressSyncPoint.init();
smResumedSyncPoint.init();
smEnabledSyncPoint.init();
initalOpenStreamSend.init();
}
@Override
public void send(PlainStreamElement element) throws NotConnectedException {
packetWriter.sendStreamElement(element);
}
@Override
protected void sendStanzaInternal(Stanza packet) throws NotConnectedException {
packetWriter.sendStreamElement(packet);
if (isSmEnabled()) {
for (StanzaFilter requestAckPredicate : requestAckPredicates) {
if (requestAckPredicate.accept(packet)) {
requestSmAcknowledgementInternal();
break;
}
}
}
}
private void connectUsingConfiguration() throws IOException, ConnectionException {
List<HostAddress> failedAddresses = populateHostAddresses();
SocketFactory socketFactory = config.getSocketFactory();
if (socketFactory == null) {
socketFactory = SocketFactory.getDefault();
}
for (HostAddress hostAddress : hostAddresses) {
String host = hostAddress.getFQDN();
int port = hostAddress.getPort();
socket = socketFactory.createSocket();
try {
Iterator<InetAddress> inetAddresses = Arrays.asList(InetAddress.getAllByName(host)).iterator();
if (!inetAddresses.hasNext()) {
// This should not happen
LOGGER.warning("InetAddress.getAllByName() returned empty result array.");
throw new UnknownHostException(host);
}
innerloop: while (inetAddresses.hasNext()) {
// Create a *new* Socket before every connection attempt, i.e. connect() call, since Sockets are not
// re-usable after a failed connection attempt. See also SMACK-724.
socket = socketFactory.createSocket();
final InetAddress inetAddress = inetAddresses.next();
final String inetAddressAndPort = inetAddress + " at port " + port;
LOGGER.finer("Trying to establish TCP connection to " + inetAddressAndPort);
try {
socket.connect(new InetSocketAddress(inetAddress, port), config.getConnectTimeout());
} catch (Exception e) {
if (inetAddresses.hasNext()) {
continue innerloop;
} else {
throw e;
}
}
LOGGER.finer("Established TCP connection to " + inetAddressAndPort);
// We found a host to connect to, return here
this.host = host;
this.port = port;
return;
}
}
catch (Exception e) {
hostAddress.setException(e);
failedAddresses.add(hostAddress);
}
}
// There are no more host addresses to try
// throw an exception and report all tried
// HostAddresses in the exception
throw ConnectionException.from(failedAddresses);
}
/**
* Initializes the connection by creating a stanza(/packet) reader and writer and opening a
* XMPP stream to the server.
*
* @throws XMPPException if establishing a connection to the server fails.
* @throws SmackException if the server failes to respond back or if there is anther error.
* @throws IOException
*/
private void initConnection() throws IOException {
boolean isFirstInitialization = packetReader == null || packetWriter == null;
compressionHandler = null;
// Set the reader and writer instance variables
initReaderAndWriter();
if (isFirstInitialization) {
packetWriter = new PacketWriter();
packetReader = new PacketReader();
// If debugging is enabled, we should start the thread that will listen for
// all packets and then log them.
if (config.isDebuggerEnabled()) {
addAsyncStanzaListener(debugger.getReaderListener(), null);
if (debugger.getWriterListener() != null) {
addPacketSendingListener(debugger.getWriterListener(), null);
}
}
}
// Start the packet writer. This will open an XMPP stream to the server
packetWriter.init();
// Start the packet reader. The startup() method will block until we
// get an opening stream packet back from server
packetReader.init();
if (isFirstInitialization) {
// Notify listeners that a new connection has been established
for (ConnectionCreationListener listener : getConnectionCreationListeners()) {
listener.connectionCreated(this);
}
}
}
private void initReaderAndWriter() throws IOException {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
if (compressionHandler != null) {
is = compressionHandler.getInputStream(is);
os = compressionHandler.getOutputStream(os);
}
// OutputStreamWriter is already buffered, no need to wrap it into a BufferedWriter
writer = new OutputStreamWriter(os, "UTF-8");
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// If debugging is enabled, we open a window and write out all network traffic.
initDebugger();
}
/**
* The server has indicated that TLS negotiation can start. We now need to secure the
* existing plain connection and perform a handshake. This method won't return until the
* connection has finished the handshake or an error occurred while securing the connection.
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
* @throws SmackException
* @throws Exception if an exception occurs.
*/
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
SSLContext context = this.config.getCustomSSLContext();
KeyStore ks = null;
KeyManager[] kms = null;
PasswordCallback pcb = null;
if(config.getCallbackHandler() == null) {
ks = null;
} else if (context == null) {
if(config.getKeystoreType().equals("NONE")) {
ks = null;
pcb = null;
}
else if(config.getKeystoreType().equals("PKCS11")) {
try {
Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library();
ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
Provider p = (Provider)c.newInstance(config);
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11",p);
pcb = new PasswordCallback("PKCS11 Password: ",false);
this.config.getCallbackHandler().handle(new Callback[]{pcb});
ks.load(null,pcb.getPassword());
}
catch (Exception e) {
ks = null;
pcb = null;
}
}
else if(config.getKeystoreType().equals("Apple")) {
ks = KeyStore.getInstance("KeychainStore","Apple");
ks.load(null,null);
//pcb = new PasswordCallback("Apple Keychain",false);
//pcb.setPassword(null);
}
else {
ks = KeyStore.getInstance(config.getKeystoreType());
try {
pcb = new PasswordCallback("Keystore Password: ",false);
config.getCallbackHandler().handle(new Callback[]{pcb});
ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
}
catch(Exception e) {
ks = null;
pcb = null;
}
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
try {
if(pcb == null) {
kmf.init(ks,null);
} else {
kmf.init(ks,pcb.getPassword());
pcb.clearPassword();
}
kms = kmf.getKeyManagers();
} catch (NullPointerException npe) {
kms = null;
}
}
// If the user didn't specify a SSLContext, use the default one
if (context == null) {
context = SSLContext.getInstance("TLS");
context.init(kms, null, new java.security.SecureRandom());
}
Socket plain = socket;
// Secure the plain connection
socket = context.getSocketFactory().createSocket(plain,
host, plain.getPort(), true);
final SSLSocket sslSocket = (SSLSocket) socket;
// Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
// important (at least on certain platforms) and it seems to be a good idea anyways to
// prevent an accidental implicit handshake.
TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
// Initialize the reader and writer with the new secured version
initReaderAndWriter();
// Proceed to do the handshake
sslSocket.startHandshake();
final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
if (verifier == null) {
throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
} else if (!verifier.verify(getServiceName(), sslSocket.getSession())) {
throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getServiceName());
}
// Set that TLS was successful
usingTLS = true;
}
/**
* Returns the compression handler that can be used for one compression methods offered by the server.
*
* @return a instance of XMPPInputOutputStream or null if no suitable instance was found
*
*/
private XMPPInputOutputStream maybeGetCompressionHandler() {
Compress.Feature compression = getFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE);
if (compression == null) {
// Server does not support compression
return null;
}
for (XMPPInputOutputStream handler : SmackConfiguration.getCompresionHandlers()) {
String method = handler.getCompressionMethod();
if (compression.getMethods().contains(method))
return handler;
}
return null;
}
@Override
public boolean isUsingCompression() {
return compressionHandler != null && compressSyncPoint.wasSuccessful();
}
/**
* <p>
* Starts using stream compression that will compress network traffic. Traffic can be
* reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
* connection. However, the server and the client will need to use more CPU time in order to
* un/compress network data so under high load the server performance might be affected.
* </p>
* <p>
* Stream compression has to have been previously offered by the server. Currently only the
* zlib method is supported by the client. Stream compression negotiation has to be done
* before authentication took place.
* </p>
*
* @throws NotConnectedException
* @throws XMPPException
* @throws NoResponseException
*/
private void useCompression() throws NotConnectedException, NoResponseException, XMPPException {
maybeCompressFeaturesReceived.checkIfSuccessOrWait();
// If stream compression was offered by the server and we want to use
// compression then send compression request to the server
if ((compressionHandler = maybeGetCompressionHandler()) != null) {
compressSyncPoint.sendAndWaitForResponseOrThrow(new Compress(compressionHandler.getCompressionMethod()));
} else {
LOGGER.warning("Could not enable compression because no matching handler/method pair was found");
}
}
/**
* Establishes a connection to the XMPP server and performs an automatic login
* only if the previous connection state was logged (authenticated). It basically
* creates and maintains a socket connection to the server.<p>
* <p/>
* Listeners will be preserved from a previous connection if the reconnection
* occurs after an abrupt termination.
*
* @throws XMPPException if an error occurs while trying to establish the connection.
* @throws SmackException
* @throws IOException
*/
@Override
protected void connectInternal() throws SmackException, IOException, XMPPException {
// Establishes the TCP connection to the server and does setup the reader and writer. Throws an exception if
// there is an error establishing the connection
connectUsingConfiguration();
// We connected successfully to the servers TCP port
socketClosed = false;
initConnection();
// Wait with SASL auth until the SASL mechanisms have been received
saslFeatureReceived.checkIfSuccessOrWaitOrThrow();
// Make note of the fact that we're now connected.
connected = true;
callConnectionConnectedListener();
// Automatically makes the login if the user was previously connected successfully
// to the server and the connection was terminated abruptly
if (wasAuthenticated) {
login();
notifyReconnection();
}
}
/**
* Sends out a notification that there was an error with the connection
* and closes the connection. Also prints the stack trace of the given exception
*
* @param e the exception that causes the connection close event.
*/
private synchronized void notifyConnectionError(Exception e) {
// Listeners were already notified of the exception, return right here.
if ((packetReader == null || packetReader.done) &&
(packetWriter == null || packetWriter.done())) return;
// Closes the connection temporary. A reconnection is possible
instantShutdown();
// Notify connection listeners of the error.
callConnectionClosedOnErrorListener(e);
}
/**
* For unit testing purposes
*
* @param writer
*/
protected void setWriter(Writer writer) {
this.writer = writer;
}
@Override
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException {
StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
if (startTlsFeature != null) {
if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
notifyConnectionError(new SecurityRequiredByServerException());
return;
}
if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
send(new StartTls());
}
}
// If TLS is required but the server doesn't offer it, disconnect
// from the server and throw an error. First check if we've already negotiated TLS
// and are secure, however (features get parsed a second time after TLS is established).
if (!isSecureConnection() && startTlsFeature == null
&& getConfiguration().getSecurityMode() == SecurityMode.required) {
throw new SecurityRequiredByClientException();
}
if (getSASLAuthentication().authenticationSuccessful()) {
// If we have received features after the SASL has been successfully completed, then we
// have also *maybe* received, as it is an optional feature, the compression feature
// from the server.
maybeCompressFeaturesReceived.reportSuccess();
}
}
/**
* Resets the parser using the latest connection's reader. Reseting the parser is necessary
* when the plain connection has been secured or when a new opening stream element is going
* to be sent by the server.
*
* @throws SmackException if the parser could not be reset.
*/
void openStream() throws SmackException {
// If possible, provide the receiving entity of the stream open tag, i.e. the server, as much information as
// possible. The 'to' attribute is *always* available. The 'from' attribute if set by the user and no external
// mechanism is used to determine the local entity (user). And the 'id' attribute is available after the first
// response from the server (see e.g. RFC 6120 § 9.1.1 Step 2.)
CharSequence to = getServiceName();
CharSequence from = null;
CharSequence localpart = config.getUsername();
if (localpart != null) {
from = XmppStringUtils.completeJidFrom(localpart, to);
}
String id = getStreamId();
send(new StreamOpen(to, from, id));
try {
packetReader.parser = PacketParserUtils.newXmppParser(reader);
}
catch (XmlPullParserException e) {
throw new SmackException(e);
}
}
protected class PacketReader {
XmlPullParser parser;
private volatile boolean done;
/**
* Initializes the reader in order to be used. The reader is initialized during the
* first connection and when reconnecting due to an abruptly disconnection.
*/
void init() {
done = false;
Async.go(new Runnable() {
public void run() {
parsePackets();
}
}, "Smack Packet Reader (" + getConnectionCounter() + ")");
}
/**
* Shuts the stanza(/packet) reader down. This method simply sets the 'done' flag to true.
*/
void shutdown() {
done = true;
}
/**
* Parse top-level packets in order to process them further.
*
* @param thread the thread that is being used by the reader to parse incoming packets.
*/
private void parsePackets() {
try {
initalOpenStreamSend.checkIfSuccessOrWait();
int eventType = parser.getEventType();
while (!done) {
switch (eventType) {
case XmlPullParser.START_TAG:
final String name = parser.getName();
switch (name) {
case Message.ELEMENT:
case IQ.IQ_ELEMENT:
case Presence.ELEMENT:
try {
parseAndProcessStanza(parser);
} finally {
clientHandledStanzasCount = SMUtils.incrementHeight(clientHandledStanzasCount);
}
break;
case "stream":
// We found an opening stream.
if ("jabber:client".equals(parser.getNamespace(null))) {
streamId = parser.getAttributeValue("", "id");
String reportedServiceName = parser.getAttributeValue("", "from");
assert(reportedServiceName.equals(config.getServiceName()));
}
break;
case "error":
throw new StreamErrorException(PacketParserUtils.parseStreamError(parser));
case "features":
parseFeatures(parser);
break;
case "proceed":
try {
// Secure the connection by negotiating TLS
proceedTLSReceived();
// Send a new opening stream to the server
openStream();
}
catch (Exception e) {
// We report any failure regarding TLS in the second stage of XMPP
// connection establishment, namely the SASL authentication
saslFeatureReceived.reportFailure(new SmackException(e));
throw e;
}
break;
case "failure":
String namespace = parser.getNamespace(null);
switch (namespace) {
case "urn:ietf:params:xml:ns:xmpp-tls":
// TLS negotiation has failed. The server will close the connection
// TODO Parse failure stanza
throw new XMPPErrorException("TLS negotiation has failed", null);
case "http://jabber.org/protocol/compress":
// Stream compression has been denied. This is a recoverable
// situation. It is still possible to authenticate and
// use the connection but using an uncompressed connection
// TODO Parse failure stanza
compressSyncPoint.reportFailure(new XMPPErrorException(
"Could not establish compression", null));
break;
case SaslStreamElements.NAMESPACE:
// SASL authentication has failed. The server may close the connection
// depending on the number of retries
final SASLFailure failure = PacketParserUtils.parseSASLFailure(parser);
getSASLAuthentication().authenticationFailed(failure);
break;
}
break;
case Challenge.ELEMENT:
// The server is challenging the SASL authentication made by the client
String challengeData = parser.nextText();
getSASLAuthentication().challengeReceived(challengeData);
break;
case Success.ELEMENT:
Success success = new Success(parser.nextText());
// We now need to bind a resource for the connection
// Open a new stream and wait for the response
openStream();
// The SASL authentication with the server was successful. The next step
// will be to bind the resource
getSASLAuthentication().authenticated(success);
break;
case Compressed.ELEMENT:
// Server confirmed that it's possible to use stream compression. Start
// stream compression
// Initialize the reader and writer with the new compressed version
initReaderAndWriter();
// Send a new opening stream to the server
openStream();
// Notify that compression is being used
compressSyncPoint.reportSuccess();
break;
case Enabled.ELEMENT:
Enabled enabled = ParseStreamManagement.enabled(parser);
if (enabled.isResumeSet()) {
smSessionId = enabled.getId();
if (StringUtils.isNullOrEmpty(smSessionId)) {
XMPPErrorException xmppException = new XMPPErrorException(
"Stream Management 'enabled' element with resume attribute but without session id received",
new XMPPError(
XMPPError.Condition.bad_request));
smEnabledSyncPoint.reportFailure(xmppException);
throw xmppException;
}
smServerMaxResumptimTime = enabled.getMaxResumptionTime();
} else {
// Mark this a non-resumable stream by setting smSessionId to null
smSessionId = null;
}
clientHandledStanzasCount = 0;
smWasEnabledAtLeastOnce = true;
smEnabledSyncPoint.reportSuccess();
LOGGER.fine("Stream Management (XEP-198): succesfully enabled");
break;
case Failed.ELEMENT:
Failed failed = ParseStreamManagement.failed(parser);
XMPPError xmppError = new XMPPError(failed.getXMPPErrorCondition());
XMPPException xmppException = new XMPPErrorException("Stream Management failed", xmppError);
// If only XEP-198 would specify different failure elements for the SM
// enable and SM resume failure case. But this is not the case, so we
// need to determine if this is a 'Failed' response for either 'Enable'
// or 'Resume'.
if (smResumedSyncPoint.requestSent()) {
smResumedSyncPoint.reportFailure(xmppException);
}
else {
if (!smEnabledSyncPoint.requestSent()) {
throw new IllegalStateException("Failed element received but SM was not previously enabled");
}
smEnabledSyncPoint.reportFailure(xmppException);
// Report success for last lastFeaturesReceived so that in case a
// failed resumption, we can continue with normal resource binding.
// See text of XEP-198 5. below Example 11.
lastFeaturesReceived.reportSuccess();
}
break;
case Resumed.ELEMENT:
Resumed resumed = ParseStreamManagement.resumed(parser);
if (!smSessionId.equals(resumed.getPrevId())) {
throw new StreamIdDoesNotMatchException(smSessionId, resumed.getPrevId());
}
// Mark SM as enabled and resumption as successful.
smResumedSyncPoint.reportSuccess();
smEnabledSyncPoint.reportSuccess();
// First, drop the stanzas already handled by the server
processHandledCount(resumed.getHandledCount());
// Then re-send what is left in the unacknowledged queue
List<Stanza> stanzasToResend = new ArrayList<>(unacknowledgedStanzas.size());
unacknowledgedStanzas.drainTo(stanzasToResend);
for (Stanza stanza : stanzasToResend) {
sendStanzaInternal(stanza);
}
// If there where stanzas resent, then request a SM ack for them.
// Writer's sendStreamElement() won't do it automatically based on
// predicates.
if (!stanzasToResend.isEmpty()) {
requestSmAcknowledgementInternal();
}
LOGGER.fine("Stream Management (XEP-198): Stream resumed");
break;
case AckAnswer.ELEMENT:
AckAnswer ackAnswer = ParseStreamManagement.ackAnswer(parser);
processHandledCount(ackAnswer.getHandledCount());
break;
case AckRequest.ELEMENT:
ParseStreamManagement.ackRequest(parser);
if (smEnabledSyncPoint.wasSuccessful()) {
sendSmAcknowledgementInternal();
} else {
LOGGER.warning("SM Ack Request received while SM is not enabled");
}
break;
default:
LOGGER.warning("Unknown top level stream element: " + name);
break;
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("stream")) {
// Disconnect the connection
disconnect();
}
break;
case XmlPullParser.END_DOCUMENT:
// END_DOCUMENT only happens in an error case, as otherwise we would see a
// closing stream element before.
throw new SmackException(
"Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element");
}
eventType = parser.next();
}
}
catch (Exception e) {
// The exception can be ignored if the the connection is 'done'
// or if the it was caused because the socket got closed
if (!(done || isSocketClosed())) {
// Close the connection and notify connection listeners of the
// error.
notifyConnectionError(e);
}
}
}
}
protected class PacketWriter {
public static final int QUEUE_SIZE = XMPPTCPConnection.QUEUE_SIZE;
private final ArrayBlockingQueueWithShutdown<Element> queue = new ArrayBlockingQueueWithShutdown<Element>(
QUEUE_SIZE, true);
/**
* Needs to be protected for unit testing purposes.
*/
protected SynchronizationPoint<NoResponseException> shutdownDone = new SynchronizationPoint<NoResponseException>(
XMPPTCPConnection.this);
/**
* If set, the stanza(/packet) writer is shut down
*/
protected volatile Long shutdownTimestamp = null;
private volatile boolean instantShutdown;
/**
* True if some preconditions are given to start the bundle and defer mechanism.
* <p>
* This will likely get set to true right after the start of the writer thread, because
* {@link #nextStreamElement()} will check if {@link queue} is empty, which is probably the case, and then set
* this field to true.
* </p>
*/
private boolean shouldBundleAndDefer;
/**
* Initializes the writer in order to be used. It is called at the first connection and also
* is invoked if the connection is disconnected by an error.
*/
void init() {
shutdownDone.init();
shutdownTimestamp = null;
if (unacknowledgedStanzas != null) {
// It's possible that there are new stanzas in the writer queue that
// came in while we were disconnected but resumable, drain those into
// the unacknowledged queue so that they get resent now
drainWriterQueueToUnacknowledgedStanzas();
}
queue.start();
Async.go(new Runnable() {
@Override
public void run() {
writePackets();
}
}, "Smack Packet Writer (" + getConnectionCounter() + ")");
}
private boolean done() {
return shutdownTimestamp != null;
}
protected void throwNotConnectedExceptionIfDoneAndResumptionNotPossible() throws NotConnectedException {
if (done() && !isSmResumptionPossible()) {
// Don't throw a NotConnectedException is there is an resumable stream available
throw new NotConnectedException();
}
}
/**
* Sends the specified element to the server.
*
* @param element the element to send.
* @throws NotConnectedException
*/
protected void sendStreamElement(Element element) throws NotConnectedException {
throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
boolean enqueued = false;
while (!enqueued) {
try {
queue.put(element);
enqueued = true;
}
catch (InterruptedException e) {
throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
// If the method above did not throw, then the sending thread was interrupted
// TODO in a later version of Smack the InterruptedException should be thrown to
// allow users to interrupt a sending thread that is currently blocking because
// the queue is full.
LOGGER.log(Level.WARNING, "Sending thread was interrupted", e);
}
}
}
/**
* Shuts down the stanza(/packet) writer. Once this method has been called, no further
* packets will be written to the server.
*/
void shutdown(boolean instant) {
instantShutdown = instant;
shutdownTimestamp = System.currentTimeMillis();
queue.shutdown();
try {
shutdownDone.checkIfSuccessOrWait();
}
catch (NoResponseException e) {
LOGGER.log(Level.WARNING, "shutdownDone was not marked as successful by the writer thread", e);
}
}
/**
* Maybe return the next available element from the queue for writing. If the queue is shut down <b>or</b> a
* spurious interrupt occurs, <code>null</code> is returned. So it is important to check the 'done' condition in
* that case.
*
* @return the next element for writing or null.
*/
private Element nextStreamElement() {
// It is important the we check if the queue is empty before removing an element from it
if (queue.isEmpty()) {
shouldBundleAndDefer = true;
}
Element packet = null;
try {
packet = queue.take();
}
catch (InterruptedException e) {
if (!queue.isShutdown()) {
// Users shouldn't try to interrupt the packet writer thread
LOGGER.log(Level.WARNING, "Packet writer thread was interrupted. Don't do that. Use disconnect() instead.", e);
}
}
return packet;
}
private void writePackets() {
try {
openStream();
initalOpenStreamSend.reportSuccess();
// Write out packets from the queue.
while (!done()) {
Element element = nextStreamElement();
if (element == null) {
continue;
}
// Get a local version of the bundle and defer callback, in case it's unset
// between the null check and the method invocation
final BundleAndDeferCallback localBundleAndDeferCallback = bundleAndDeferCallback;
// If the preconditions are given (e.g. bundleAndDefer callback is set, queue is
// empty), then we could wait a bit for further stanzas attempting to decrease
// our energy consumption
if (localBundleAndDeferCallback != null && isAuthenticated() && shouldBundleAndDefer) {
// Reset shouldBundleAndDefer to false, nextStreamElement() will set it to true once the
// queue is empty again.
shouldBundleAndDefer = false;
final AtomicBoolean bundlingAndDeferringStopped = new AtomicBoolean();
final int bundleAndDeferMillis = localBundleAndDeferCallback.getBundleAndDeferMillis(new BundleAndDefer(
bundlingAndDeferringStopped));
if (bundleAndDeferMillis > 0) {
long remainingWait = bundleAndDeferMillis;
final long waitStart = System.currentTimeMillis();
synchronized (bundlingAndDeferringStopped) {
while (!bundlingAndDeferringStopped.get() && remainingWait > 0) {
bundlingAndDeferringStopped.wait(remainingWait);
remainingWait = bundleAndDeferMillis
- (System.currentTimeMillis() - waitStart);
}
}
}
}
Stanza packet = null;
if (element instanceof Stanza) {
packet = (Stanza) element;
}
else if (element instanceof Enable) {
// The client needs to add messages to the unacknowledged stanzas queue
// right after it sent 'enabled'. Stanza will be added once
// unacknowledgedStanzas is not null.
unacknowledgedStanzas = new ArrayBlockingQueue<>(QUEUE_SIZE);
}
// Check if the stream element should be put to the unacknowledgedStanza
// queue. Note that we can not do the put() in sendStanzaInternal() and the
// packet order is not stable at this point (sendStanzaInternal() can be
// called concurrently).
if (unacknowledgedStanzas != null && packet != null) {
// If the unacknowledgedStanza queue is nearly full, request an new ack
// from the server in order to drain it
if (unacknowledgedStanzas.size() == 0.8 * XMPPTCPConnection.QUEUE_SIZE) {
writer.write(AckRequest.INSTANCE.toXML().toString());
writer.flush();
}
try {
// It is important the we put the stanza in the unacknowledged stanza
// queue before we put it on the wire
unacknowledgedStanzas.put(packet);
}
catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
writer.write(element.toXML().toString());
if (queue.isEmpty()) {
writer.flush();
}
if (packet != null) {
firePacketSendingListeners(packet);
}
}
if (!instantShutdown) {
// Flush out the rest of the queue.
try {
while (!queue.isEmpty()) {
Element packet = queue.remove();
writer.write(packet.toXML().toString());
}
writer.flush();
}
catch (Exception e) {
LOGGER.log(Level.WARNING,
"Exception flushing queue during shutdown, ignore and continue",
e);
}
// Close the stream.
try {
writer.write("</stream:stream>");
writer.flush();
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception writing closing stream element", e);
}
// Delete the queue contents (hopefully nothing is left).
queue.clear();
} else if (instantShutdown && isSmEnabled()) {
// This was an instantShutdown and SM is enabled, drain all remaining stanzas
// into the unacknowledgedStanzas queue
drainWriterQueueToUnacknowledgedStanzas();
}
try {
writer.close();
}
catch (Exception e) {
// Do nothing
}
}
catch (Exception e) {
// The exception can be ignored if the the connection is 'done'
// or if the it was caused because the socket got closed
if (!(done() || isSocketClosed())) {
notifyConnectionError(e);
} else {
LOGGER.log(Level.FINE, "Ignoring Exception in writePackets()", e);
}
} finally {
LOGGER.fine("Reporting shutdownDone success in writer thread");
shutdownDone.reportSuccess();
}
}
private void drainWriterQueueToUnacknowledgedStanzas() {
List<Element> elements = new ArrayList<Element>(queue.size());
queue.drainTo(elements);
for (Element element : elements) {
if (element instanceof Stanza) {
unacknowledgedStanzas.add((Stanza) element);
}
}
}
}
/**
* Set if Stream Management should be used by default for new connections.
*
* @param useSmDefault true to use Stream Management for new connections.
*/
public static void setUseStreamManagementDefault(boolean useSmDefault) {
XMPPTCPConnection.useSmDefault = useSmDefault;
}
/**
* Set if Stream Management resumption should be used by default for new connections.
*
* @param useSmResumptionDefault true to use Stream Management resumption for new connections.
* @deprecated use {@link #setUseStreamManagementResumptionDefault(boolean)} instead.
*/
@Deprecated
public static void setUseStreamManagementResumptiodDefault(boolean useSmResumptionDefault) {
setUseStreamManagementResumptionDefault(useSmResumptionDefault);
}
/**
* Set if Stream Management resumption should be used by default for new connections.
*
* @param useSmResumptionDefault true to use Stream Management resumption for new connections.
*/
public static void setUseStreamManagementResumptionDefault(boolean useSmResumptionDefault) {
if (useSmResumptionDefault) {
// Also enable SM is resumption is enabled
setUseStreamManagementDefault(useSmResumptionDefault);
}
XMPPTCPConnection.useSmResumptionDefault = useSmResumptionDefault;
}
/**
* Set if Stream Management should be used if supported by the server.
*
* @param useSm true to use Stream Management.
*/
public void setUseStreamManagement(boolean useSm) {
this.useSm = useSm;
}
/**
* Set if Stream Management resumption should be used if supported by the server.
*
* @param useSmResumption true to use Stream Management resumption.
*/
public void setUseStreamManagementResumption(boolean useSmResumption) {
if (useSmResumption) {
// Also enable SM is resumption is enabled
setUseStreamManagement(useSmResumption);
}
this.useSmResumption = useSmResumption;
}
/**
* Set the preferred resumption time in seconds.
* @param resumptionTime the preferred resumption time in seconds
*/
public void setPreferredResumptionTime(int resumptionTime) {
smClientMaxResumptionTime = resumptionTime;
}
/**
* Add a predicate for Stream Management acknowledgment requests.
* <p>
* Those predicates are used to determine when a Stream Management acknowledgement request is send to the server.
* Some pre-defined predicates are found in the <code>org.jivesoftware.smack.sm.predicates</code> package.
* </p>
* <p>
* If not predicate is configured, the {@link Predicate#forMessagesOrAfter5Stanzas()} will be used.
* </p>
*
* @param predicate the predicate to add.
* @return if the predicate was not already active.
*/
public boolean addRequestAckPredicate(StanzaFilter predicate) {
synchronized (requestAckPredicates) {
return requestAckPredicates.add(predicate);
}
}
/**
* Remove the given predicate for Stream Management acknowledgment request.
* @param predicate the predicate to remove.
* @return true if the predicate was removed.
*/
public boolean removeRequestAckPredicate(StanzaFilter predicate) {
synchronized (requestAckPredicates) {
return requestAckPredicates.remove(predicate);
}
}
/**
* Remove all predicates for Stream Management acknowledgment requests.
*/
public void removeAllRequestAckPredicates() {
synchronized (requestAckPredicates) {
requestAckPredicates.clear();
}
}
/**
* Send an unconditional Stream Management acknowledgement request to the server.
*
* @throws StreamManagementNotEnabledException if Stream Mangement is not enabled.
* @throws NotConnectedException if the connection is not connected.
*/
public void requestSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException {
if (!isSmEnabled()) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
requestSmAcknowledgementInternal();
}
private void requestSmAcknowledgementInternal() throws NotConnectedException {
packetWriter.sendStreamElement(AckRequest.INSTANCE);
}
/**
* Send a unconditional Stream Management acknowledgment to the server.
* <p>
* See <a href="http://xmpp.org/extensions/xep-0198.html#acking">XEP-198: Stream Management § 4. Acks</a>:
* "Either party MAY send an <a/> element at any time (e.g., after it has received a certain number of stanzas,
* or after a certain period of time), even if it has not received an <r/> element from the other party."
* </p>
*
* @throws StreamManagementNotEnabledException if Stream Management is not enabled.
* @throws NotConnectedException if the connection is not connected.
*/
public void sendSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException {
if (!isSmEnabled()) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
sendSmAcknowledgementInternal();
}
private void sendSmAcknowledgementInternal() throws NotConnectedException {
packetWriter.sendStreamElement(new AckAnswer(clientHandledStanzasCount));
}
/**
* Add a Stanza acknowledged listener.
* <p>
* Those listeners will be invoked every time a Stanza has been acknowledged by the server. The will not get
* automatically removed. Consider using {@link #addStanzaIdAcknowledgedListener(String, StanzaListener)} when
* possible.
* </p>
*
* @param listener the listener to add.
*/
public void addStanzaAcknowledgedListener(StanzaListener listener) {
stanzaAcknowledgedListeners.add(listener);
}
/**
* Remove the given Stanza acknowledged listener.
*
* @param listener the listener.
* @return true if the listener was removed.
*/
public boolean removeStanzaAcknowledgedListener(StanzaListener listener) {
return stanzaAcknowledgedListeners.remove(listener);
}
/**
* Remove all stanza acknowledged listeners.
*/
public void removeAllStanzaAcknowledgedListeners() {
stanzaAcknowledgedListeners.clear();
}
/**
* Add a new Stanza ID acknowledged listener for the given ID.
* <p>
* The listener will be invoked if the stanza with the given ID was acknowledged by the server. It will
* automatically be removed after the listener was run.
* </p>
*
* @param id the stanza ID.
* @param listener the listener to invoke.
* @return the previous listener for this stanza ID or null.
* @throws StreamManagementNotEnabledException if Stream Management is not enabled.
*/
public StanzaListener addStanzaIdAcknowledgedListener(final String id, StanzaListener listener) throws StreamManagementNotEnabledException {
// Prevent users from adding callbacks that will never get removed
if (!smWasEnabledAtLeastOnce) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
// Remove the listener after max. 12 hours
final int removeAfterSeconds = Math.min(getMaxSmResumptionTime(), 12 * 60 * 60);
schedule(new Runnable() {
@Override
public void run() {
stanzaIdAcknowledgedListeners.remove(id);
}
}, removeAfterSeconds, TimeUnit.SECONDS);
return stanzaIdAcknowledgedListeners.put(id, listener);
}
/**
* Remove the Stanza ID acknowledged listener for the given ID.
*
* @param id the stanza ID.
* @return true if the listener was found and removed, false otherwise.
*/
public StanzaListener removeStanzaIdAcknowledgedListener(String id) {
return stanzaIdAcknowledgedListeners.remove(id);
}
/**
* Removes all Stanza ID acknowledged listeners.
*/
public void removeAllStanzaIdAcknowledgedListeners() {
stanzaIdAcknowledgedListeners.clear();
}
/**
* Returns true if Stream Management is supported by the server.
*
* @return true if Stream Management is supported by the server.
*/
public boolean isSmAvailable() {
return hasFeature(StreamManagementFeature.ELEMENT, StreamManagement.NAMESPACE);
}
/**
* Returns true if Stream Management was successfully negotiated with the server.
*
* @return true if Stream Management was negotiated.
*/
public boolean isSmEnabled() {
return smEnabledSyncPoint.wasSuccessful();
}
/**
* Returns true if the stream was successfully resumed with help of Stream Management.
*
* @return true if the stream was resumed.
*/
public boolean streamWasResumed() {
return smResumedSyncPoint.wasSuccessful();
}
/**
* Returns true if the connection is disconnected by a Stream resumption via Stream Management is possible.
*
* @return true if disconnected but resumption possible.
*/
public boolean isDisconnectedButSmResumptionPossible() {
return disconnectedButResumeable && isSmResumptionPossible();
}
/**
* Returns true if the stream is resumable.
*
* @return true if the stream is resumable.
*/
public boolean isSmResumptionPossible() {
// There is no resumable stream available
if (smSessionId == null)
return false;
final Long shutdownTimestamp = packetWriter.shutdownTimestamp;
// Seems like we are already reconnected, report true
if (shutdownTimestamp == null) {
return true;
}
// See if resumption time is over
long current = System.currentTimeMillis();
long maxResumptionMillies = ((long) getMaxSmResumptionTime()) * 1000;
if (current > shutdownTimestamp + maxResumptionMillies) {
// Stream resumption is *not* possible if the current timestamp is greater then the greatest timestamp where
// resumption is possible
return false;
} else {
return true;
}
}
/**
* Drop the stream management state. Sets {@link #smSessionId} and
* {@link #unacknowledgedStanzas} to <code>null</code>.
*/
private void dropSmState() {
// clientHandledCount and serverHandledCount will be reset on <enable/> and <enabled/>
// respective. No need to reset them here.
smSessionId = null;
unacknowledgedStanzas = null;
}
/**
* Get the maximum resumption time in seconds after which a managed stream can be resumed.
* <p>
* This method will return {@link Integer#MAX_VALUE} if neither the client nor the server specify a maximum
* resumption time. Be aware of integer overflows when using this value, e.g. do not add arbitrary values to it
* without checking for overflows before.
* </p>
*
* @return the maximum resumption time in seconds or {@link Integer#MAX_VALUE} if none set.
*/
public int getMaxSmResumptionTime() {
int clientResumptionTime = smClientMaxResumptionTime > 0 ? smClientMaxResumptionTime : Integer.MAX_VALUE;
int serverResumptionTime = smServerMaxResumptimTime > 0 ? smServerMaxResumptimTime : Integer.MAX_VALUE;
return Math.min(clientResumptionTime, serverResumptionTime);
}
private void processHandledCount(long handledCount) throws StreamManagementCounterError {
long ackedStanzasCount = SMUtils.calculateDelta(handledCount, serverHandledStanzasCount);
final List<Stanza> ackedStanzas = new ArrayList<Stanza>(
ackedStanzasCount <= Integer.MAX_VALUE ? (int) ackedStanzasCount
: Integer.MAX_VALUE);
for (long i = 0; i < ackedStanzasCount; i++) {
Stanza ackedStanza = unacknowledgedStanzas.poll();
// If the server ack'ed a stanza, then it must be in the
// unacknowledged stanza queue. There can be no exception.
if (ackedStanza == null) {
throw new StreamManagementCounterError(handledCount, serverHandledStanzasCount,
ackedStanzasCount, ackedStanzas);
}
ackedStanzas.add(ackedStanza);
}
boolean atLeastOneStanzaAcknowledgedListener = false;
if (!stanzaAcknowledgedListeners.isEmpty()) {
// If stanzaAcknowledgedListeners is not empty, the we have at least one
atLeastOneStanzaAcknowledgedListener = true;
}
else {
// Otherwise we look for a matching id in the stanza *id* acknowledged listeners
for (Stanza ackedStanza : ackedStanzas) {
String id = ackedStanza.getStanzaId();
if (id != null && stanzaIdAcknowledgedListeners.containsKey(id)) {
atLeastOneStanzaAcknowledgedListener = true;
break;
}
}
}
// Only spawn a new thread if there is a chance that some listener is invoked
if (atLeastOneStanzaAcknowledgedListener) {
asyncGo(new Runnable() {
@Override
public void run() {
for (Stanza ackedStanza : ackedStanzas) {
for (StanzaListener listener : stanzaAcknowledgedListeners) {
try {
listener.processPacket(ackedStanza);
}
catch (NotConnectedException e) {
LOGGER.log(Level.FINER, "Received not connected exception", e);
}
}
String id = ackedStanza.getStanzaId();
if (StringUtils.isNullOrEmpty(id)) {
continue;
}
StanzaListener listener = stanzaIdAcknowledgedListeners.remove(id);
if (listener != null) {
try {
listener.processPacket(ackedStanza);
}
catch (NotConnectedException e) {
LOGGER.log(Level.FINER, "Received not connected exception", e);
}
}
}
}
});
}
serverHandledStanzasCount = handledCount;
}
/**
* Set the default bundle and defer callback used for new connections.
*
* @param defaultBundleAndDeferCallback
* @see BundleAndDeferCallback
* @since 4.1
*/
public static void setDefaultBundleAndDeferCallback(BundleAndDeferCallback defaultBundleAndDeferCallback) {
XMPPTCPConnection.defaultBundleAndDeferCallback = defaultBundleAndDeferCallback;
}
/**
* Set the bundle and defer callback used for this connection.
* <p>
* You can use <code>null</code> as argument to reset the callback. Outgoing stanzas will then
* no longer get deferred.
* </p>
*
* @param bundleAndDeferCallback the callback or <code>null</code>.
* @see BundleAndDeferCallback
* @since 4.1
*/
public void setBundleandDeferCallback(BundleAndDeferCallback bundleAndDeferCallback) {
this.bundleAndDeferCallback = bundleAndDeferCallback;
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_4768_1
|
crossvul-java_data_bad_2300_0
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.logging;
import static org.jboss.weld.logging.WeldLogger.WELD_PROJECT_CODE;
import javax.enterprise.context.spi.Context;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;
import org.jboss.logging.Logger.Level;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.Message.Format;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.weld.exceptions.IllegalStateException;
import org.jboss.weld.servlet.ServletContextService;
/**
* Error messages relating to Servlet integration
*
* Message ids: 000700 - 000799
*/
@MessageLogger(projectCode = WELD_PROJECT_CODE)
public interface ServletLogger extends WeldLogger {
ServletLogger LOG = Logger.getMessageLogger(ServletLogger.class, Category.SERVLET.getName());
@Message(id = 707, value = "Non Http-Servlet lifecycle not defined")
IllegalStateException onlyHttpServletLifecycleDefined();
@LogMessage(level = Level.TRACE)
@Message(id = 708, value = "Initializing request {0}", format = Format.MESSAGE_FORMAT)
void requestInitialized(Object param1);
@LogMessage(level = Level.TRACE)
@Message(id = 709, value = "Destroying request {0}", format = Format.MESSAGE_FORMAT)
void requestDestroyed(Object param1);
@Message(id = 710, value = "Cannot inject {0} outside of a Servlet request", format = Format.MESSAGE_FORMAT)
IllegalStateException cannotInjectObjectOutsideOfServletRequest(Object param1, @Cause Throwable cause);
@LogMessage(level = Level.WARN)
@Message(id = 711, value = "Context activation pattern {0} ignored as it is overriden by the integrator.", format = Format.MESSAGE_FORMAT)
void webXmlMappingPatternIgnored(String pattern);
@LogMessage(level = Level.WARN)
@Message(id = 712, value = "Unable to dissociate context {0} when destroying request {1}", format = Format.MESSAGE_FORMAT)
void unableToDissociateContext(Context context, HttpServletRequest request);
@Message(id = 713, value = "Unable to inject ServletContext. None is associated with {0}, {1}", format = Format.MESSAGE_FORMAT)
IllegalStateException cannotInjectServletContext(ClassLoader classLoader, ServletContextService service);
@LogMessage(level = Level.WARN)
@Message(id = 714, value = "HttpContextLifecycle guard leak detected. The Servlet container is not fully compliant. The value was {0}", format = Format.MESSAGE_FORMAT)
void guardLeak(int value);
@LogMessage(level = Level.WARN)
@Message(id = 715, value = "HttpContextLifecycle guard not set. The Servlet container is not fully compliant.", format = Format.MESSAGE_FORMAT)
void guardNotSet();
@LogMessage(level = Level.INFO)
@Message(id = 716, value = "Running in Servlet 2.x environment. Asynchronous request support is disabled.")
void servlet2Environment();
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_2300_0
|
crossvul-java_data_good_4769_0
|
/**
*
* Copyright 2009 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByClientException;
import org.jivesoftware.smack.SmackException.SecurityRequiredException;
import org.jivesoftware.smack.XMPPException.StreamErrorException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.compress.packet.Compress;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.debugger.SmackDebugger;
import org.jivesoftware.smack.filter.IQReplyFilter;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.filter.StanzaIdFilter;
import org.jivesoftware.smack.iqrequest.IQRequestHandler;
import org.jivesoftware.smack.packet.Bind;
import org.jivesoftware.smack.packet.ErrorIQ;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Mechanisms;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Session;
import org.jivesoftware.smack.packet.StartTls;
import org.jivesoftware.smack.packet.Nonza;
import org.jivesoftware.smack.packet.StreamError;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.sasl.core.SASLAnonymous;
import org.jivesoftware.smack.util.BoundedThreadPoolExecutor;
import org.jivesoftware.smack.util.DNSUtil;
import org.jivesoftware.smack.util.Objects;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.util.ParserUtils;
import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.EntityFullJid;
import org.jxmpp.jid.Jid;
import org.jxmpp.jid.parts.Resourcepart;
import org.jxmpp.util.XmppStringUtils;
import org.xmlpull.v1.XmlPullParser;
public abstract class AbstractXMPPConnection implements XMPPConnection {
private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName());
/**
* Counter to uniquely identify connections that are created.
*/
private final static AtomicInteger connectionCounter = new AtomicInteger(0);
static {
// Ensure the SmackConfiguration class is loaded by calling a method in it.
SmackConfiguration.getVersion();
}
/**
* A collection of ConnectionListeners which listen for connection closing
* and reconnection events.
*/
protected final Set<ConnectionListener> connectionListeners =
new CopyOnWriteArraySet<ConnectionListener>();
/**
* A collection of PacketCollectors which collects packets for a specified filter
* and perform blocking and polling operations on the result queue.
* <p>
* We use a ConcurrentLinkedQueue here, because its Iterator is weakly
* consistent and we want {@link #invokePacketCollectors(Stanza)} for-each
* loop to be lock free. As drawback, removing a PacketCollector is O(n).
* The alternative would be a synchronized HashSet, but this would mean a
* synchronized block around every usage of <code>collectors</code>.
* </p>
*/
private final Collection<PacketCollector> collectors = new ConcurrentLinkedQueue<PacketCollector>();
/**
* List of PacketListeners that will be notified synchronously when a new stanza(/packet) was received.
*/
private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>();
/**
* List of PacketListeners that will be notified asynchronously when a new stanza(/packet) was received.
*/
private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>();
/**
* List of PacketListeners that will be notified when a new stanza(/packet) was sent.
*/
private final Map<StanzaListener, ListenerWrapper> sendListeners =
new HashMap<StanzaListener, ListenerWrapper>();
/**
* List of PacketListeners that will be notified when a new stanza(/packet) is about to be
* sent to the server. These interceptors may modify the stanza(/packet) before it is being
* actually sent to the server.
*/
private final Map<StanzaListener, InterceptorWrapper> interceptors =
new HashMap<StanzaListener, InterceptorWrapper>();
protected final Lock connectionLock = new ReentrantLock();
protected final Map<String, ExtensionElement> streamFeatures = new HashMap<String, ExtensionElement>();
/**
* The full JID of the authenticated user, as returned by the resource binding response of the server.
* <p>
* It is important that we don't infer the user from the login() arguments and the configurations service name, as,
* for example, when SASL External is used, the username is not given to login but taken from the 'external'
* certificate.
* </p>
*/
protected EntityFullJid user;
protected boolean connected = false;
/**
* The stream ID, see RFC 6120 § 4.7.3
*/
protected String streamId;
/**
*
*/
private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout();
/**
* The SmackDebugger allows to log and debug XML traffic.
*/
protected SmackDebugger debugger = null;
/**
* The Reader which is used for the debugger.
*/
protected Reader reader;
/**
* The Writer which is used for the debugger.
*/
protected Writer writer;
/**
* Set to success if the last features stanza from the server has been parsed. A XMPP connection
* handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature
* stanza is send by the server. This is set to true once the last feature stanza has been
* parsed.
*/
protected final SynchronizationPoint<Exception> lastFeaturesReceived = new SynchronizationPoint<Exception>(
AbstractXMPPConnection.this, "last stream features received from server");
/**
* Set to success if the sasl feature has been received.
*/
protected final SynchronizationPoint<SmackException> saslFeatureReceived = new SynchronizationPoint<SmackException>(
AbstractXMPPConnection.this, "SASL mechanisms stream feature from server");
/**
* The SASLAuthentication manager that is responsible for authenticating with the server.
*/
protected final SASLAuthentication saslAuthentication;
/**
* A number to uniquely identify connections that are created. This is distinct from the
* connection ID, which is a value sent by the server once a connection is made.
*/
protected final int connectionCounterValue = connectionCounter.getAndIncrement();
/**
* Holds the initial configuration used while creating the connection.
*/
protected final ConnectionConfiguration config;
/**
* Defines how the from attribute of outgoing stanzas should be handled.
*/
private FromMode fromMode = FromMode.OMITTED;
protected XMPPInputOutputStream compressionHandler;
private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback();
/**
* ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is
* important that we use a <b>single threaded ExecutorService</b> in order to guarantee that the
* PacketListeners are invoked in the same order the stanzas arrived.
*/
private final BoundedThreadPoolExecutor executorService = new BoundedThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
100, new SmackExecutorThreadFactory(this, "Incoming Processor"));
/**
* This scheduled thread pool executor is used to remove pending callbacks.
*/
private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor(
new SmackExecutorThreadFactory(this, "Remove Callbacks"));
/**
* A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set
* them 'daemon'.
*/
private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool(
// @formatter:off
new SmackExecutorThreadFactory( // threadFactory
this,
"Cached Executor"
)
// @formatter:on
);
/**
* A executor service used to invoke the callbacks of synchronous stanza(/packet) listeners. We use a executor service to
* decouple incoming stanza processing from callback invocation. It is important that order of callback invocation
* is the same as the order of the incoming stanzas. Therefore we use a <i>single</i> threaded executor service.
*/
private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory(
this, "Single Threaded Executor"));
/**
* The used host to establish the connection to
*/
protected String host;
/**
* The used port to establish the connection to
*/
protected int port;
/**
* Flag that indicates if the user is currently authenticated with the server.
*/
protected boolean authenticated = false;
/**
* Flag that indicates if the user was authenticated with the server when the connection
* to the server was closed (abruptly or not).
*/
protected boolean wasAuthenticated = false;
private final Map<String, IQRequestHandler> setIqRequestHandler = new HashMap<>();
private final Map<String, IQRequestHandler> getIqRequestHandler = new HashMap<>();
/**
* Create a new XMPPConnection to an XMPP server.
*
* @param configuration The configuration which is used to establish the connection.
*/
protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
saslAuthentication = new SASLAuthentication(this, configuration);
config = configuration;
// Notify listeners that a new connection has been established
for (ConnectionCreationListener listener : XMPPConnectionRegistry.getConnectionCreationListeners()) {
listener.connectionCreated(this);
}
}
/**
* Get the connection configuration used by this connection.
*
* @return the connection configuration.
*/
public ConnectionConfiguration getConfiguration() {
return config;
}
@SuppressWarnings("deprecation")
@Override
public DomainBareJid getServiceName() {
return getXMPPServiceDomain();
}
@Override
public DomainBareJid getXMPPServiceDomain() {
if (xmppServiceDomain != null) {
return xmppServiceDomain;
}
return config.getXMPPServiceDomain();
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public abstract boolean isSecureConnection();
protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException;
@Override
public abstract void sendNonza(Nonza element) throws NotConnectedException, InterruptedException;
@Override
public abstract boolean isUsingCompression();
/**
* Establishes a connection to the XMPP server. It basically
* creates and maintains a connection to the server.
* <p>
* Listeners will be preserved from a previous connection.
* </p>
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException
* @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
* @throws InterruptedException
*/
public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException, InterruptedException {
// Check if not already connected
throwAlreadyConnectedExceptionIfAppropriate();
// Reset the connection state
saslAuthentication.init();
saslFeatureReceived.init();
lastFeaturesReceived.init();
streamId = null;
// Perform the actual connection to the XMPP service
connectInternal();
// Wait with SASL auth until the SASL mechanisms have been received
saslFeatureReceived.checkIfSuccessOrWaitOrThrow();
// If TLS is required but the server doesn't offer it, disconnect
// from the server and throw an error. First check if we've already negotiated TLS
// and are secure, however (features get parsed a second time after TLS is established).
if (!isSecureConnection() && getConfiguration().getSecurityMode() == SecurityMode.required) {
throw new SecurityRequiredByClientException();
}
// Make note of the fact that we're now connected.
connected = true;
callConnectionConnectedListener();
return this;
}
/**
* Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
* way of XMPP connection establishment. Implementations are required to perform an automatic
* login if the previous connection state was logged (authenticated).
*
* @throws SmackException
* @throws IOException
* @throws XMPPException
* @throws InterruptedException
*/
protected abstract void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException;
private String usedUsername, usedPassword;
/**
* The resourcepart used for this connection. May not be the resulting resourcepart if it's null or overridden by the XMPP service.
*/
private Resourcepart usedResource;
/**
* Logs in to the server using the strongest SASL mechanism supported by
* the server. If more than the connection's default stanza(/packet) timeout elapses in each step of the
* authentication process without a response from the server, a
* {@link SmackException.NoResponseException} will be thrown.
* <p>
* Before logging in (i.e. authenticate) to the server the connection must be connected
* by calling {@link #connect}.
* </p>
* <p>
* It is possible to log in without sending an initial available presence by using
* {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}.
* Finally, if you want to not pass a password and instead use a more advanced mechanism
* while using SASL then you may be interested in using
* {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}.
* For more advanced login settings see {@link ConnectionConfiguration}.
* </p>
*
* @throws XMPPException if an error occurs on the XMPP protocol level.
* @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
* @throws IOException if an I/O error occurs during login.
* @throws InterruptedException
*/
public synchronized void login() throws XMPPException, SmackException, IOException, InterruptedException {
// The previously used username, password and resource take over precedence over the
// ones from the connection configuration
CharSequence username = usedUsername != null ? usedUsername : config.getUsername();
String password = usedPassword != null ? usedPassword : config.getPassword();
Resourcepart resource = usedResource != null ? usedResource : config.getResource();
login(username, password, resource);
}
/**
* Same as {@link #login(CharSequence, String, Resourcepart)}, but takes the resource from the connection
* configuration.
*
* @param username
* @param password
* @throws XMPPException
* @throws SmackException
* @throws IOException
* @throws InterruptedException
* @see #login
*/
public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException,
IOException, InterruptedException {
login(username, password, config.getResource());
}
/**
* Login with the given username (authorization identity). You may omit the password if a callback handler is used.
* If resource is null, then the server will generate one.
*
* @param username
* @param password
* @param resource
* @throws XMPPException
* @throws SmackException
* @throws IOException
* @throws InterruptedException
* @see #login
*/
public synchronized void login(CharSequence username, String password, Resourcepart resource) throws XMPPException,
SmackException, IOException, InterruptedException {
if (!config.allowNullOrEmptyUsername) {
StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty");
}
throwNotConnectedExceptionIfAppropriate("Did you call connect() before login()?");
throwAlreadyLoggedInExceptionIfAppropriate();
usedUsername = username != null ? username.toString() : null;
usedPassword = password;
usedResource = resource;
loginInternal(usedUsername, usedPassword, usedResource);
}
protected abstract void loginInternal(String username, String password, Resourcepart resource)
throws XMPPException, SmackException, IOException, InterruptedException;
@Override
public final boolean isConnected() {
return connected;
}
@Override
public final boolean isAuthenticated() {
return authenticated;
}
@Override
public final EntityFullJid getUser() {
return user;
}
@Override
public String getStreamId() {
if (!isConnected()) {
return null;
}
return streamId;
}
protected void bindResourceAndEstablishSession(Resourcepart resource) throws XMPPErrorException,
SmackException, InterruptedException {
// Wait until either:
// - the servers last features stanza has been parsed
// - the timeout occurs
LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
lastFeaturesReceived.checkIfSuccessOrWait();
if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
// Server never offered resource binding, which is REQURIED in XMPP client and
// server implementations as per RFC6120 7.2
throw new ResourceBindingNotOfferedException();
}
// Resource binding, see RFC6120 7.
// Note that we can not use IQReplyFilter here, since the users full JID is not yet
// available. It will become available right after the resource has been successfully bound.
Bind bindResource = Bind.newSet(resource);
PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
Bind response = packetCollector.nextResultOrThrow();
// Set the connections user to the result of resource binding. It is important that we don't infer the user
// from the login() arguments and the configurations service name, as, for example, when SASL External is used,
// the username is not given to login but taken from the 'external' certificate.
user = response.getJid();
xmppServiceDomain = user.asDomainBareJid();
Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE);
// Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
// For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
// TODO remove this suppression once "disable legacy session" code has been removed from Smack
@SuppressWarnings("deprecation")
boolean legacySessionDisabled = getConfiguration().isLegacySessionDisabled();
if (sessionFeature != null && !sessionFeature.isOptional() && !legacySessionDisabled) {
Session session = new Session();
packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session);
packetCollector.nextResultOrThrow();
}
}
protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException, InterruptedException {
// Indicate that we're now authenticated.
this.authenticated = true;
// If debugging is enabled, change the the debug window title to include the
// name we are now logged-in as.
// If DEBUG was set to true AFTER the connection was created the debugger
// will be null
if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user);
}
callConnectionAuthenticatedListener(resumed);
// Set presence to online. It is important that this is done after
// callConnectionAuthenticatedListener(), as this call will also
// eventually load the roster. And we should load the roster before we
// send the initial presence.
if (config.isSendPresence() && !resumed) {
sendStanza(new Presence(Presence.Type.available));
}
}
@Override
public final boolean isAnonymous() {
return isAuthenticated() && SASLAnonymous.NAME.equals(getUsedSaslMechansism());
}
/**
* Get the name of the SASL mechanism that was used to authenticate this connection. This returns the name of
* mechanism which was used the last time this conneciton was authenticated, and will return <code>null</code> if
* this connection was not authenticated before.
*
* @return the name of the used SASL mechanism.
* @since 4.2
*/
public final String getUsedSaslMechansism() {
return saslAuthentication.getNameOfLastUsedSaslMechansism();
}
private DomainBareJid xmppServiceDomain;
protected List<HostAddress> hostAddresses;
/**
* Populates {@link #hostAddresses} with at least one host address.
*
* @return a list of host addresses where DNS (SRV) RR resolution failed.
*/
protected List<HostAddress> populateHostAddresses() {
List<HostAddress> failedAddresses = new LinkedList<>();
// N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName
if (config.host != null) {
hostAddresses = new ArrayList<HostAddress>(1);
HostAddress hostAddress = DNSUtil.getDNSResolver().lookupHostAddress(config.host, failedAddresses, config.getDnssecMode());
hostAddresses.add(hostAddress);
} else {
hostAddresses = DNSUtil.resolveXMPPServiceDomain(config.getXMPPServiceDomain().toString(), failedAddresses, config.getDnssecMode());
}
// If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the
// config.host one or the host representing the service name by DNSUtil
assert(!hostAddresses.isEmpty());
return failedAddresses;
}
protected Lock getConnectionLock() {
return connectionLock;
}
protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
throwNotConnectedExceptionIfAppropriate(null);
}
protected void throwNotConnectedExceptionIfAppropriate(String optionalHint) throws NotConnectedException {
if (!isConnected()) {
throw new NotConnectedException(optionalHint);
}
}
protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
if (isConnected()) {
throw new AlreadyConnectedException();
}
}
protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
if (isAuthenticated()) {
throw new AlreadyLoggedInException();
}
}
@Deprecated
@Override
public void sendPacket(Stanza packet) throws NotConnectedException, InterruptedException {
sendStanza(packet);
}
@Override
public void sendStanza(Stanza stanza) throws NotConnectedException, InterruptedException {
Objects.requireNonNull(stanza, "Stanza must not be null");
assert(stanza instanceof Message || stanza instanceof Presence || stanza instanceof IQ);
throwNotConnectedExceptionIfAppropriate();
switch (fromMode) {
case OMITTED:
stanza.setFrom((Jid) null);
break;
case USER:
stanza.setFrom(getUser());
break;
case UNCHANGED:
default:
break;
}
// Invoke interceptors for the new stanza that is about to be sent. Interceptors may modify
// the content of the stanza.
firePacketInterceptors(stanza);
sendStanzaInternal(stanza);
}
/**
* Returns the SASLAuthentication manager that is responsible for authenticating with
* the server.
*
* @return the SASLAuthentication manager that is responsible for authenticating with
* the server.
*/
protected SASLAuthentication getSASLAuthentication() {
return saslAuthentication;
}
/**
* Closes the connection by setting presence to unavailable then closing the connection to
* the XMPP server. The XMPPConnection can still be used for connecting to the server
* again.
*
*/
public void disconnect() {
try {
disconnect(new Presence(Presence.Type.unavailable));
}
catch (NotConnectedException e) {
LOGGER.log(Level.FINEST, "Connection is already disconnected", e);
}
}
/**
* Closes the connection. A custom unavailable presence is sent to the server, followed
* by closing the stream. The XMPPConnection can still be used for connecting to the server
* again. A custom unavailable presence is useful for communicating offline presence
* information such as "On vacation". Typically, just the status text of the presence
* stanza(/packet) is set with online information, but most XMPP servers will deliver the full
* presence stanza(/packet) with whatever data is set.
*
* @param unavailablePresence the presence stanza(/packet) to send during shutdown.
* @throws NotConnectedException
*/
public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException {
try {
sendStanza(unavailablePresence);
}
catch (InterruptedException e) {
LOGGER.log(Level.FINE, "Was interrupted while sending unavailable presence. Continuing to disconnect the connection", e);
}
shutdown();
callConnectionClosedListener();
}
/**
* Shuts the current connection down.
*/
protected abstract void shutdown();
@Override
public void addConnectionListener(ConnectionListener connectionListener) {
if (connectionListener == null) {
return;
}
connectionListeners.add(connectionListener);
}
@Override
public void removeConnectionListener(ConnectionListener connectionListener) {
connectionListeners.remove(connectionListener);
}
@Override
public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException, InterruptedException {
StanzaFilter packetFilter = new IQReplyFilter(packet, this);
// Create the packet collector before sending the packet
PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet);
return packetCollector;
}
@Override
public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
throws NotConnectedException, InterruptedException {
// Create the packet collector before sending the packet
PacketCollector packetCollector = createPacketCollector(packetFilter);
try {
// Now we can send the packet as the collector has been created
sendStanza(packet);
}
catch (InterruptedException | NotConnectedException | RuntimeException e) {
packetCollector.cancel();
throw e;
}
return packetCollector;
}
@Override
public PacketCollector createPacketCollector(StanzaFilter packetFilter) {
PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter);
return createPacketCollector(configuration);
}
@Override
public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) {
PacketCollector collector = new PacketCollector(this, configuration);
// Add the collector to the list of active collectors.
collectors.add(collector);
return collector;
}
@Override
public void removePacketCollector(PacketCollector collector) {
collectors.remove(collector);
}
@Override
@Deprecated
public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) {
addAsyncStanzaListener(packetListener, packetFilter);
}
@Override
@Deprecated
public boolean removePacketListener(StanzaListener packetListener) {
return removeAsyncStanzaListener(packetListener);
}
@Override
public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (syncRecvListeners) {
syncRecvListeners.put(packetListener, wrapper);
}
}
@Override
public boolean removeSyncStanzaListener(StanzaListener packetListener) {
synchronized (syncRecvListeners) {
return syncRecvListeners.remove(packetListener) != null;
}
}
@Override
public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (asyncRecvListeners) {
asyncRecvListeners.put(packetListener, wrapper);
}
}
@Override
public boolean removeAsyncStanzaListener(StanzaListener packetListener) {
synchronized (asyncRecvListeners) {
return asyncRecvListeners.remove(packetListener) != null;
}
}
@Override
public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
synchronized (sendListeners) {
sendListeners.put(packetListener, wrapper);
}
}
@Override
public void removePacketSendingListener(StanzaListener packetListener) {
synchronized (sendListeners) {
sendListeners.remove(packetListener);
}
}
/**
* Process all stanza(/packet) listeners for sending packets.
* <p>
* Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread.
* </p>
*
* @param packet the stanza(/packet) to process.
*/
@SuppressWarnings("javadoc")
protected void firePacketSendingListeners(final Stanza packet) {
final List<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
synchronized (sendListeners) {
for (ListenerWrapper listenerWrapper : sendListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
if (listenersToNotify.isEmpty()) {
return;
}
// Notify in a new thread, because we can
asyncGo(new Runnable() {
@Override
public void run() {
for (StanzaListener listener : listenersToNotify) {
try {
listener.processPacket(packet);
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Sending listener threw exception", e);
continue;
}
}
}});
}
@Override
public void addPacketInterceptor(StanzaListener packetInterceptor,
StanzaFilter packetFilter) {
if (packetInterceptor == null) {
throw new NullPointerException("Packet interceptor is null.");
}
InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
synchronized (interceptors) {
interceptors.put(packetInterceptor, interceptorWrapper);
}
}
@Override
public void removePacketInterceptor(StanzaListener packetInterceptor) {
synchronized (interceptors) {
interceptors.remove(packetInterceptor);
}
}
/**
* Process interceptors. Interceptors may modify the stanza(/packet) that is about to be sent.
* Since the thread that requested to send the stanza(/packet) will invoke all interceptors, it
* is important that interceptors perform their work as soon as possible so that the
* thread does not remain blocked for a long period.
*
* @param packet the stanza(/packet) that is going to be sent to the server
*/
private void firePacketInterceptors(Stanza packet) {
List<StanzaListener> interceptorsToInvoke = new LinkedList<StanzaListener>();
synchronized (interceptors) {
for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
if (interceptorWrapper.filterMatches(packet)) {
interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
}
}
}
for (StanzaListener interceptor : interceptorsToInvoke) {
try {
interceptor.processPacket(packet);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
}
}
}
/**
* Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger}
* by setup the system property <code>smack.debuggerClass</code> to the implementation.
*
* @throws IllegalStateException if the reader or writer isn't yet initialized.
* @throws IllegalArgumentException if the SmackDebugger can't be loaded.
*/
protected void initDebugger() {
if (reader == null || writer == null) {
throw new NullPointerException("Reader or writer isn't initialized.");
}
// If debugging is enabled, we open a window and write out all network traffic.
if (config.isDebuggerEnabled()) {
if (debugger == null) {
debugger = SmackConfiguration.createDebugger(this, writer, reader);
}
if (debugger == null) {
LOGGER.severe("Debugging enabled but could not find debugger class");
} else {
// Obtain new reader and writer from the existing debugger
reader = debugger.newConnectionReader(reader);
writer = debugger.newConnectionWriter(writer);
}
}
}
@Override
public long getPacketReplyTimeout() {
return packetReplyTimeout;
}
@Override
public void setPacketReplyTimeout(long timeout) {
packetReplyTimeout = timeout;
}
private static boolean replyToUnknownIqDefault = true;
/**
* Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured
* default is 'true'.
*
* @param replyToUnkownIqDefault
* @see #setReplyToUnknownIq(boolean)
*/
public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) {
AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault;
}
private boolean replyToUnkownIq = replyToUnknownIqDefault;
/**
* Set if Smack will automatically send
* {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a
* registered {@link IQRequestHandler} is received.
*
* @param replyToUnknownIq
*/
public void setReplyToUnknownIq(boolean replyToUnknownIq) {
this.replyToUnkownIq = replyToUnknownIq;
}
protected void parseAndProcessStanza(XmlPullParser parser) throws Exception {
ParserUtils.assertAtStartTag(parser);
int parserDepth = parser.getDepth();
Stanza stanza = null;
try {
stanza = PacketParserUtils.parseStanza(parser);
}
catch (Exception e) {
CharSequence content = PacketParserUtils.parseContentDepth(parser,
parserDepth);
UnparseableStanza message = new UnparseableStanza(content, e);
ParsingExceptionCallback callback = getParsingExceptionCallback();
if (callback != null) {
callback.handleUnparsableStanza(message);
}
}
ParserUtils.assertAtEndTag(parser);
if (stanza != null) {
processStanza(stanza);
}
}
/**
* Processes a stanza(/packet) after it's been fully parsed by looping through the installed
* stanza(/packet) collectors and listeners and letting them examine the stanza(/packet) to see if
* they are a match with the filter.
*
* @param stanza the stanza to process.
* @throws InterruptedException
*/
protected void processStanza(final Stanza stanza) throws InterruptedException {
assert(stanza != null);
lastStanzaReceived = System.currentTimeMillis();
// Deliver the incoming packet to listeners.
executorService.executeBlocking(new Runnable() {
@Override
public void run() {
invokePacketCollectorsAndNotifyRecvListeners(stanza);
}
});
}
/**
* Invoke {@link PacketCollector#processPacket(Stanza)} for every
* PacketCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet.
*
* @param packet the stanza(/packet) to notify the PacketCollectors and receive listeners about.
*/
protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) {
if (packet instanceof IQ) {
final IQ iq = (IQ) packet;
final IQ.Type type = iq.getType();
switch (type) {
case set:
case get:
final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace());
IQRequestHandler iqRequestHandler = null;
switch (type) {
case set:
synchronized (setIqRequestHandler) {
iqRequestHandler = setIqRequestHandler.get(key);
}
break;
case get:
synchronized (getIqRequestHandler) {
iqRequestHandler = getIqRequestHandler.get(key);
}
break;
default:
throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
}
if (iqRequestHandler == null) {
if (!replyToUnkownIq) {
return;
}
// If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
// IQ of type 'error' with condition 'service-unavailable'.
ErrorIQ errorIQ = IQ.createErrorResponse(iq, XMPPError.getBuilder((
XMPPError.Condition.service_unavailable)));
try {
sendStanza(errorIQ);
}
catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.WARNING, "Exception while sending error IQ to unkown IQ request", e);
}
} else {
ExecutorService executorService = null;
switch (iqRequestHandler.getMode()) {
case sync:
executorService = singleThreadedExecutorService;
break;
case async:
executorService = cachedExecutorService;
break;
}
final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
executorService.execute(new Runnable() {
@Override
public void run() {
IQ response = finalIqRequestHandler.handleIQRequest(iq);
if (response == null) {
// It is not ideal if the IQ request handler does not return an IQ response, because RFC
// 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the
// file transfer one, does not always return a result, so we need to handle this case.
// Also sometimes a request handler may decide that it's better to not send a response,
// e.g. to avoid presence leaks.
return;
}
try {
sendStanza(response);
}
catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.WARNING, "Exception while sending response to IQ request", e);
}
}
});
// The following returns makes it impossible for packet listeners and collectors to
// filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the
// desired behavior.
return;
}
break;
default:
break;
}
}
// First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
// the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
// their own thread.
final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
synchronized (asyncRecvListeners) {
for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
for (final StanzaListener listener : listenersToNotify) {
asyncGo(new Runnable() {
@Override
public void run() {
try {
listener.processPacket(packet);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
}
}
});
}
// Loop through all collectors and notify the appropriate ones.
for (PacketCollector collector: collectors) {
collector.processPacket(packet);
}
// Notify the receive listeners interested in the packet
listenersToNotify.clear();
synchronized (syncRecvListeners) {
for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
if (listenerWrapper.filterMatches(packet)) {
listenersToNotify.add(listenerWrapper.getListener());
}
}
}
// Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
// threaded executor service and therefore keeps the order.
singleThreadedExecutorService.execute(new Runnable() {
@Override
public void run() {
for (StanzaListener listener : listenersToNotify) {
try {
listener.processPacket(packet);
} catch(NotConnectedException e) {
LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
break;
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
}
}
}
});
}
/**
* Sets whether the connection has already logged in the server. This method assures that the
* {@link #wasAuthenticated} flag is never reset once it has ever been set.
*
*/
protected void setWasAuthenticated() {
// Never reset the flag if the connection has ever been authenticated
if (!wasAuthenticated) {
wasAuthenticated = authenticated;
}
}
protected void callConnectionConnectedListener() {
for (ConnectionListener listener : connectionListeners) {
listener.connected(this);
}
}
protected void callConnectionAuthenticatedListener(boolean resumed) {
for (ConnectionListener listener : connectionListeners) {
try {
listener.authenticated(this, resumed);
} catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e);
}
}
}
void callConnectionClosedListener() {
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionClosed();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
}
}
}
protected void callConnectionClosedOnErrorListener(Exception e) {
boolean logWarning = true;
if (e instanceof StreamErrorException) {
StreamErrorException see = (StreamErrorException) e;
if (see.getStreamError().getCondition() == StreamError.Condition.not_authorized
&& wasAuthenticated) {
logWarning = false;
LOGGER.log(Level.FINE,
"Connection closed with not-authorized stream error after it was already authenticated. The account was likely deleted/unregistered on the server");
}
}
if (logWarning) {
LOGGER.log(Level.WARNING, "Connection " + this + " closed with error", e);
}
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionClosedOnError(e);
}
catch (Exception e2) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
}
}
}
/**
* Sends a notification indicating that the connection was reconnected successfully.
*/
protected void notifyReconnection() {
// Notify connection listeners of the reconnection.
for (ConnectionListener listener : connectionListeners) {
try {
listener.reconnectionSuccessful();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.WARNING, "notifyReconnection()", e);
}
}
}
/**
* A wrapper class to associate a stanza(/packet) filter with a listener.
*/
protected static class ListenerWrapper {
private final StanzaListener packetListener;
private final StanzaFilter packetFilter;
/**
* Create a class which associates a stanza(/packet) filter with a listener.
*
* @param packetListener the stanza(/packet) listener.
* @param packetFilter the associated filter or null if it listen for all packets.
*/
public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) {
this.packetListener = packetListener;
this.packetFilter = packetFilter;
}
public boolean filterMatches(Stanza packet) {
return packetFilter == null || packetFilter.accept(packet);
}
public StanzaListener getListener() {
return packetListener;
}
}
/**
* A wrapper class to associate a stanza(/packet) filter with an interceptor.
*/
protected static class InterceptorWrapper {
private final StanzaListener packetInterceptor;
private final StanzaFilter packetFilter;
/**
* Create a class which associates a stanza(/packet) filter with an interceptor.
*
* @param packetInterceptor the interceptor.
* @param packetFilter the associated filter or null if it intercepts all packets.
*/
public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) {
this.packetInterceptor = packetInterceptor;
this.packetFilter = packetFilter;
}
public boolean filterMatches(Stanza packet) {
return packetFilter == null || packetFilter.accept(packet);
}
public StanzaListener getInterceptor() {
return packetInterceptor;
}
}
@Override
public int getConnectionCounter() {
return connectionCounterValue;
}
@Override
public void setFromMode(FromMode fromMode) {
this.fromMode = fromMode;
}
@Override
public FromMode getFromMode() {
return this.fromMode;
}
@Override
protected void finalize() throws Throwable {
LOGGER.fine("finalizing " + this + ": Shutting down executor services");
try {
// It's usually not a good idea to rely on finalize. But this is the easiest way to
// avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a
// reference to their ExecutorService which prevents the ExecutorService from being
// gc'ed. It is possible that the XMPPConnection instance is gc'ed while the
// listenerExecutor ExecutorService call not be gc'ed until it got shut down.
executorService.shutdownNow();
cachedExecutorService.shutdown();
removeCallbacksService.shutdownNow();
singleThreadedExecutorService.shutdownNow();
} catch (Throwable t) {
LOGGER.log(Level.WARNING, "finalize() threw trhowable", t);
}
finally {
super.finalize();
}
}
protected final void parseFeatures(XmlPullParser parser) throws Exception {
streamFeatures.clear();
final int initialDepth = parser.getDepth();
while (true) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) {
ExtensionElement streamFeature = null;
String name = parser.getName();
String namespace = parser.getNamespace();
switch (name) {
case StartTls.ELEMENT:
streamFeature = PacketParserUtils.parseStartTlsFeature(parser);
break;
case Mechanisms.ELEMENT:
streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser));
break;
case Bind.ELEMENT:
streamFeature = Bind.Feature.INSTANCE;
break;
case Session.ELEMENT:
streamFeature = PacketParserUtils.parseSessionFeature(parser);
break;
case Compress.Feature.ELEMENT:
streamFeature = PacketParserUtils.parseCompressionFeature(parser);
break;
default:
ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace);
if (provider != null) {
streamFeature = provider.parse(parser);
}
break;
}
if (streamFeature != null) {
addStreamFeature(streamFeature);
}
}
else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) {
break;
}
}
if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
// Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
|| config.getSecurityMode() == SecurityMode.disabled) {
saslFeatureReceived.reportSuccess();
}
}
// If the server reported the bind feature then we are that that we did SASL and maybe
// STARTTLS. We can then report that the last 'stream:features' have been parsed
if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
|| !config.isCompressionEnabled()) {
// This was was last features from the server is either it did not contain
// compression or if we disabled it
lastFeaturesReceived.reportSuccess();
}
}
afterFeaturesReceived();
}
@SuppressWarnings("unused")
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {
// Default implementation does nothing
}
@SuppressWarnings("unchecked")
@Override
public <F extends ExtensionElement> F getFeature(String element, String namespace) {
return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace));
}
@Override
public boolean hasFeature(String element, String namespace) {
return getFeature(element, namespace) != null;
}
protected void addStreamFeature(ExtensionElement feature) {
String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace());
streamFeatures.put(key, feature);
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
StanzaListener callback) throws NotConnectedException, InterruptedException {
sendStanzaWithResponseCallback(stanza, replyFilter, callback, null);
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
StanzaListener callback, ExceptionCallback exceptionCallback)
throws NotConnectedException, InterruptedException {
sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback,
getPacketReplyTimeout());
}
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter,
final StanzaListener callback, final ExceptionCallback exceptionCallback,
long timeout) throws NotConnectedException, InterruptedException {
Objects.requireNonNull(stanza, "stanza must not be null");
// While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
// disallow it here in the async API as it makes no sense
Objects.requireNonNull(replyFilter, "replyFilter must not be null");
Objects.requireNonNull(callback, "callback must not be null");
final StanzaListener packetListener = new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws NotConnectedException, InterruptedException {
try {
XMPPErrorException.ifHasErrorThenThrow(packet);
callback.processPacket(packet);
}
catch (XMPPErrorException e) {
if (exceptionCallback != null) {
exceptionCallback.processException(e);
}
}
finally {
removeAsyncStanzaListener(this);
}
}
};
removeCallbacksService.schedule(new Runnable() {
@Override
public void run() {
boolean removed = removeAsyncStanzaListener(packetListener);
// If the packetListener got removed, then it was never run and
// we never received a response, inform the exception callback
if (removed && exceptionCallback != null) {
Exception exception;
if (!isConnected()) {
// If the connection is no longer connected, throw a not connected exception.
exception = new NotConnectedException(AbstractXMPPConnection.this, replyFilter);
} else {
exception = NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter);
}
exceptionCallback.processException(exception);
}
}
}, timeout, TimeUnit.MILLISECONDS);
addAsyncStanzaListener(packetListener, replyFilter);
sendStanza(stanza);
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback)
throws NotConnectedException, InterruptedException {
sendIqWithResponseCallback(iqRequest, callback, null);
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback,
ExceptionCallback exceptionCallback) throws NotConnectedException, InterruptedException {
sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout());
}
@Override
public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback,
final ExceptionCallback exceptionCallback, long timeout)
throws NotConnectedException, InterruptedException {
StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this);
sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout);
}
@Override
public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
final StanzaListener packetListener = new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws NotConnectedException, InterruptedException {
try {
callback.processPacket(packet);
} finally {
removeSyncStanzaListener(this);
}
}
};
addSyncStanzaListener(packetListener, packetFilter);
removeCallbacksService.schedule(new Runnable() {
@Override
public void run() {
removeSyncStanzaListener(packetListener);
}
}, getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
}
@Override
public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) {
final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace());
switch (iqRequestHandler.getType()) {
case set:
synchronized (setIqRequestHandler) {
return setIqRequestHandler.put(key, iqRequestHandler);
}
case get:
synchronized (getIqRequestHandler) {
return getIqRequestHandler.put(key, iqRequestHandler);
}
default:
throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
}
}
@Override
public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) {
return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(),
iqRequestHandler.getType());
}
@Override
public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
final String key = XmppStringUtils.generateKey(element, namespace);
switch (type) {
case set:
synchronized (setIqRequestHandler) {
return setIqRequestHandler.remove(key);
}
case get:
synchronized (getIqRequestHandler) {
return getIqRequestHandler.remove(key);
}
default:
throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
}
}
private long lastStanzaReceived;
public long getLastStanzaReceived() {
return lastStanzaReceived;
}
/**
* Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a
* stanza.
*
* @param callback the callback to install
*/
public void setParsingExceptionCallback(ParsingExceptionCallback callback) {
parsingExceptionCallback = callback;
}
/**
* Get the current active parsing exception callback.
*
* @return the active exception callback or null if there is none
*/
public ParsingExceptionCallback getParsingExceptionCallback() {
return parsingExceptionCallback;
}
@Override
public final String toString() {
EntityFullJid localEndpoint = getUser();
String localEndpointString = (localEndpoint == null ? "not-authenticated" : localEndpoint.toString());
return getClass().getSimpleName() + '[' + localEndpointString + "] (" + getConnectionCounter() + ')';
}
protected final void asyncGo(Runnable runnable) {
cachedExecutorService.execute(runnable);
}
protected final ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) {
return removeCallbacksService.schedule(runnable, delay, unit);
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_4769_0
|
crossvul-java_data_good_2299_0
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.context.cache;
import java.util.LinkedList;
import java.util.List;
/**
* Caches beans over the life of a request, to allow for efficient bean lookups from proxies.
* Besides, can hold any ThreadLocals to be removed at the end of the request.
*
* @author Stuart Douglas
*/
public class RequestScopedCache {
private static final ThreadLocal<List<RequestScopedItem>> CACHE = new ThreadLocal<List<RequestScopedItem>>();
private RequestScopedCache() {
}
public static boolean isActive() {
return CACHE.get() != null;
}
private static void checkCacheForAdding(final List<RequestScopedItem> cache) {
if (cache == null) {
throw new IllegalStateException("Unable to add request scoped cache item when request cache is not active");
}
}
public static void addItem(final RequestScopedItem item) {
final List<RequestScopedItem> cache = CACHE.get();
checkCacheForAdding(cache);
cache.add(item);
}
public static boolean addItemIfActive(final RequestScopedItem item) {
final List<RequestScopedItem> cache = CACHE.get();
if (cache != null) {
cache.add(item);
return true;
}
return false;
}
public static boolean addItemIfActive(final ThreadLocal<?> item) {
final List<RequestScopedItem> cache = CACHE.get();
if (cache != null) {
cache.add(new RequestScopedItem() {
public void invalidate() {
item.remove();
}
});
return true;
}
return false;
}
public static void beginRequest() {
// if the previous request was not ended properly for some reason, make sure it is ended now
endRequest();
CACHE.set(new LinkedList<RequestScopedItem>());
}
/**
* ends the request and clears the cache. This can be called before the request is over,
* in which case the cache will be unavailable for the rest of the request.
*/
public static void endRequest() {
final List<RequestScopedItem> result = CACHE.get();
if (result != null) {
CACHE.remove();
for (final RequestScopedItem item : result) {
item.invalidate();
}
}
}
/**
* Flushes the bean cache. The cache remains available for the rest of the request.
*/
public static void invalidate() {
if (isActive()) {
endRequest();
beginRequest();
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_2299_0
|
crossvul-java_data_bad_4769_1
|
/**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.tcp;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.DnssecMode;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.ConnectionException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByClientException;
import org.jivesoftware.smack.SmackException.SecurityRequiredByServerException;
import org.jivesoftware.smack.SmackException.SecurityRequiredException;
import org.jivesoftware.smack.SynchronizationPoint;
import org.jivesoftware.smack.XMPPException.StreamErrorException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.compress.packet.Compressed;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.compress.packet.Compress;
import org.jivesoftware.smack.packet.Element;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.StreamOpen;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.StartTls;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Challenge;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.SASLFailure;
import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Success;
import org.jivesoftware.smack.sm.SMUtils;
import org.jivesoftware.smack.sm.StreamManagementException;
import org.jivesoftware.smack.sm.StreamManagementException.StreamIdDoesNotMatchException;
import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementCounterError;
import org.jivesoftware.smack.sm.StreamManagementException.StreamManagementNotEnabledException;
import org.jivesoftware.smack.sm.packet.StreamManagement;
import org.jivesoftware.smack.sm.packet.StreamManagement.AckAnswer;
import org.jivesoftware.smack.sm.packet.StreamManagement.AckRequest;
import org.jivesoftware.smack.sm.packet.StreamManagement.Enable;
import org.jivesoftware.smack.sm.packet.StreamManagement.Enabled;
import org.jivesoftware.smack.sm.packet.StreamManagement.Failed;
import org.jivesoftware.smack.sm.packet.StreamManagement.Resume;
import org.jivesoftware.smack.sm.packet.StreamManagement.Resumed;
import org.jivesoftware.smack.sm.packet.StreamManagement.StreamManagementFeature;
import org.jivesoftware.smack.sm.predicates.Predicate;
import org.jivesoftware.smack.sm.provider.ParseStreamManagement;
import org.jivesoftware.smack.packet.Nonza;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.proxy.ProxyInfo;
import org.jivesoftware.smack.util.ArrayBlockingQueueWithShutdown;
import org.jivesoftware.smack.util.Async;
import org.jivesoftware.smack.util.DNSUtil;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.TLSUtils;
import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jivesoftware.smack.util.dns.HostAddress;
import org.jivesoftware.smack.util.dns.SmackDaneProvider;
import org.jivesoftware.smack.util.dns.SmackDaneVerifier;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.jid.parts.Resourcepart;
import org.jxmpp.stringprep.XmppStringprepException;
import org.jxmpp.util.XmppStringUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Creates a socket connection to an XMPP server. This is the default connection
* to an XMPP server and is specified in the XMPP Core (RFC 6120).
*
* @see XMPPConnection
* @author Matt Tucker
*/
public class XMPPTCPConnection extends AbstractXMPPConnection {
private static final int QUEUE_SIZE = 500;
private static final Logger LOGGER = Logger.getLogger(XMPPTCPConnection.class.getName());
/**
* The socket which is used for this connection.
*/
private Socket socket;
/**
*
*/
private boolean disconnectedButResumeable = false;
private boolean usingTLS = false;
/**
* Protected access level because of unit test purposes
*/
protected PacketWriter packetWriter;
/**
* Protected access level because of unit test purposes
*/
protected PacketReader packetReader;
private final SynchronizationPoint<Exception> initalOpenStreamSend = new SynchronizationPoint<>(
this, "initial open stream element send to server");
/**
*
*/
private final SynchronizationPoint<XMPPException> maybeCompressFeaturesReceived = new SynchronizationPoint<XMPPException>(
this, "stream compression feature");
/**
*
*/
private final SynchronizationPoint<SmackException> compressSyncPoint = new SynchronizationPoint<>(
this, "stream compression");
/**
* A synchronization point which is successful if this connection has received the closing
* stream element from the remote end-point, i.e. the server.
*/
private final SynchronizationPoint<Exception> closingStreamReceived = new SynchronizationPoint<>(
this, "stream closing element received");
/**
* The default bundle and defer callback, used for new connections.
* @see bundleAndDeferCallback
*/
private static BundleAndDeferCallback defaultBundleAndDeferCallback;
/**
* The used bundle and defer callback.
* <p>
* Although this field may be set concurrently, the 'volatile' keyword was deliberately not added, in order to avoid
* having a 'volatile' read within the writer threads loop.
* </p>
*/
private BundleAndDeferCallback bundleAndDeferCallback = defaultBundleAndDeferCallback;
private static boolean useSmDefault = true;
private static boolean useSmResumptionDefault = true;
/**
* The stream ID of the stream that is currently resumable, ie. the stream we hold the state
* for in {@link #clientHandledStanzasCount}, {@link #serverHandledStanzasCount} and
* {@link #unacknowledgedStanzas}.
*/
private String smSessionId;
private final SynchronizationPoint<XMPPException> smResumedSyncPoint = new SynchronizationPoint<XMPPException>(
this, "stream resumed element");
private final SynchronizationPoint<XMPPException> smEnabledSyncPoint = new SynchronizationPoint<XMPPException>(
this, "stream enabled element");
/**
* The client's preferred maximum resumption time in seconds.
*/
private int smClientMaxResumptionTime = -1;
/**
* The server's preferred maximum resumption time in seconds.
*/
private int smServerMaxResumptimTime = -1;
/**
* Indicates whether Stream Management (XEP-198) should be used if it's supported by the server.
*/
private boolean useSm = useSmDefault;
private boolean useSmResumption = useSmResumptionDefault;
/**
* The counter that the server sends the client about it's current height. For example, if the server sends
* {@code <a h='42'/>}, then this will be set to 42 (while also handling the {@link #unacknowledgedStanzas} queue).
*/
private long serverHandledStanzasCount = 0;
/**
* The counter for stanzas handled ("received") by the client.
* <p>
* Note that we don't need to synchronize this counter. Although JLS 17.7 states that reads and writes to longs are
* not atomic, it guarantees that there are at most 2 separate writes, one to each 32-bit half. And since
* {@link SMUtils#incrementHeight(long)} masks the lower 32 bit, we only operate on one half of the long and
* therefore have no concurrency problem because the read/write operations on one half are guaranteed to be atomic.
* </p>
*/
private long clientHandledStanzasCount = 0;
private BlockingQueue<Stanza> unacknowledgedStanzas;
/**
* Set to true if Stream Management was at least once enabled for this connection.
*/
private boolean smWasEnabledAtLeastOnce = false;
/**
* This listeners are invoked for every stanza that got acknowledged.
* <p>
* We use a {@link ConccurrentLinkedQueue} here in order to allow the listeners to remove
* themselves after they have been invoked.
* </p>
*/
private final Collection<StanzaListener> stanzaAcknowledgedListeners = new ConcurrentLinkedQueue<StanzaListener>();
/**
* This listeners are invoked for a acknowledged stanza that has the given stanza ID. They will
* only be invoked once and automatically removed after that.
*/
private final Map<String, StanzaListener> stanzaIdAcknowledgedListeners = new ConcurrentHashMap<String, StanzaListener>();
/**
* Predicates that determine if an stream management ack should be requested from the server.
* <p>
* We use a linked hash set here, so that the order how the predicates are added matches the
* order in which they are invoked in order to determine if an ack request should be send or not.
* </p>
*/
private final Set<StanzaFilter> requestAckPredicates = new LinkedHashSet<StanzaFilter>();
private final XMPPTCPConnectionConfiguration config;
/**
* Creates a new XMPP connection over TCP (optionally using proxies).
* <p>
* Note that XMPPTCPConnection constructors do not establish a connection to the server
* and you must call {@link #connect()}.
* </p>
*
* @param config the connection configuration.
*/
public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) {
super(config);
this.config = config;
addConnectionListener(new AbstractConnectionListener() {
@Override
public void connectionClosedOnError(Exception e) {
if (e instanceof XMPPException.StreamErrorException) {
dropSmState();
}
}
});
}
/**
* Creates a new XMPP connection over TCP.
* <p>
* Note that {@code jid} must be the bare JID, e.g. "user@example.org". More fine-grained control over the
* connection settings is available using the {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)}
* constructor.
* </p>
*
* @param jid the bare JID used by the client.
* @param password the password or authentication token.
* @throws XmppStringprepException
*/
public XMPPTCPConnection(CharSequence jid, String password) throws XmppStringprepException {
this(XmppStringUtils.parseLocalpart(jid.toString()), password, XmppStringUtils.parseDomain(jid.toString()));
}
/**
* Creates a new XMPP connection over TCP.
* <p>
* This is the simplest constructor for connecting to an XMPP server. Alternatively,
* you can get fine-grained control over connection settings using the
* {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)} constructor.
* </p>
* @param username
* @param password
* @param serviceName
* @throws XmppStringprepException
*/
public XMPPTCPConnection(CharSequence username, String password, String serviceName) throws XmppStringprepException {
this(XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(username, password).setXmppDomain(
JidCreate.domainBareFrom(serviceName)).build());
}
@Override
protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
if (packetWriter == null) {
throw new NotConnectedException();
}
packetWriter.throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
}
@Override
protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
if (isConnected() && !disconnectedButResumeable) {
throw new AlreadyConnectedException();
}
}
@Override
protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
if (isAuthenticated() && !disconnectedButResumeable) {
throw new AlreadyLoggedInException();
}
}
@Override
protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException, InterruptedException {
// Reset the flag in case it was set
disconnectedButResumeable = false;
super.afterSuccessfulLogin(resumed);
}
@Override
protected synchronized void loginInternal(String username, String password, Resourcepart resource) throws XMPPException,
SmackException, IOException, InterruptedException {
// Authenticate using SASL
saslAuthentication.authenticate(username, password, config.getAuthzid());
// If compression is enabled then request the server to use stream compression. XEP-170
// recommends to perform stream compression before resource binding.
maybeEnableCompression();
if (isSmResumptionPossible()) {
smResumedSyncPoint.sendAndWaitForResponse(new Resume(clientHandledStanzasCount, smSessionId));
if (smResumedSyncPoint.wasSuccessful()) {
// We successfully resumed the stream, be done here
afterSuccessfulLogin(true);
return;
}
// SM resumption failed, what Smack does here is to report success of
// lastFeaturesReceived in case of sm resumption was answered with 'failed' so that
// normal resource binding can be tried.
LOGGER.fine("Stream resumption failed, continuing with normal stream establishment process");
}
List<Stanza> previouslyUnackedStanzas = new LinkedList<Stanza>();
if (unacknowledgedStanzas != null) {
// There was a previous connection with SM enabled but that was either not resumable or
// failed to resume. Make sure that we (re-)send the unacknowledged stanzas.
unacknowledgedStanzas.drainTo(previouslyUnackedStanzas);
// Reset unacknowledged stanzas to 'null' to signal that we never send 'enable' in this
// XMPP session (There maybe was an enabled in a previous XMPP session of this
// connection instance though). This is used in writePackets to decide if stanzas should
// be added to the unacknowledged stanzas queue, because they have to be added right
// after the 'enable' stream element has been sent.
dropSmState();
}
// Now bind the resource. It is important to do this *after* we dropped an eventually
// existing Stream Management state. As otherwise <bind/> and <session/> may end up in
// unacknowledgedStanzas and become duplicated on reconnect. See SMACK-706.
bindResourceAndEstablishSession(resource);
if (isSmAvailable() && useSm) {
// Remove what is maybe left from previously stream managed sessions
serverHandledStanzasCount = 0;
// XEP-198 3. Enabling Stream Management. If the server response to 'Enable' is 'Failed'
// then this is a non recoverable error and we therefore throw an exception.
smEnabledSyncPoint.sendAndWaitForResponseOrThrow(new Enable(useSmResumption, smClientMaxResumptionTime));
synchronized (requestAckPredicates) {
if (requestAckPredicates.isEmpty()) {
// Assure that we have at lest one predicate set up that so that we request acks
// for the server and eventually flush some stanzas from the unacknowledged
// stanza queue
requestAckPredicates.add(Predicate.forMessagesOrAfter5Stanzas());
}
}
}
// (Re-)send the stanzas *after* we tried to enable SM
for (Stanza stanza : previouslyUnackedStanzas) {
sendStanzaInternal(stanza);
}
afterSuccessfulLogin(false);
}
@Override
public boolean isSecureConnection() {
return usingTLS;
}
/**
* Shuts the current connection down. After this method returns, the connection must be ready
* for re-use by connect.
*/
@Override
protected void shutdown() {
if (isSmEnabled()) {
try {
// Try to send a last SM Acknowledgement. Most servers won't find this information helpful, as the SM
// state is dropped after a clean disconnect anyways. OTOH it doesn't hurt much either.
sendSmAcknowledgementInternal();
} catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.FINE, "Can not send final SM ack as connection is not connected", e);
}
}
shutdown(false);
}
/**
* Performs an unclean disconnect and shutdown of the connection. Does not send a closing stream stanza.
*/
public synchronized void instantShutdown() {
shutdown(true);
}
private void shutdown(boolean instant) {
if (disconnectedButResumeable) {
return;
}
// First shutdown the writer, this will result in a closing stream element getting send to
// the server
if (packetWriter != null) {
LOGGER.finer("PacketWriter shutdown()");
packetWriter.shutdown(instant);
}
LOGGER.finer("PacketWriter has been shut down");
try {
// After we send the closing stream element, check if there was already a
// closing stream element sent by the server or wait with a timeout for a
// closing stream element to be received from the server.
@SuppressWarnings("unused")
Exception res = closingStreamReceived.checkIfSuccessOrWait();
} catch (InterruptedException | NoResponseException e) {
LOGGER.log(Level.INFO, "Exception while waiting for closing stream element from the server " + this, e);
}
if (packetReader != null) {
LOGGER.finer("PacketReader shutdown()");
packetReader.shutdown();
}
LOGGER.finer("PacketReader has been shut down");
try {
socket.close();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "shutdown", e);
}
setWasAuthenticated();
// If we are able to resume the stream, then don't set
// connected/authenticated/usingTLS to false since we like behave like we are still
// connected (e.g. sendStanza should not throw a NotConnectedException).
if (isSmResumptionPossible() && instant) {
disconnectedButResumeable = true;
} else {
disconnectedButResumeable = false;
// Reset the stream management session id to null, since if the stream is cleanly closed, i.e. sending a closing
// stream tag, there is no longer a stream to resume.
smSessionId = null;
}
authenticated = false;
connected = false;
usingTLS = false;
reader = null;
writer = null;
maybeCompressFeaturesReceived.init();
compressSyncPoint.init();
smResumedSyncPoint.init();
smEnabledSyncPoint.init();
initalOpenStreamSend.init();
}
@Override
public void sendNonza(Nonza element) throws NotConnectedException, InterruptedException {
packetWriter.sendStreamElement(element);
}
@Override
protected void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException {
packetWriter.sendStreamElement(packet);
if (isSmEnabled()) {
for (StanzaFilter requestAckPredicate : requestAckPredicates) {
if (requestAckPredicate.accept(packet)) {
requestSmAcknowledgementInternal();
break;
}
}
}
}
private void connectUsingConfiguration() throws ConnectionException, IOException {
List<HostAddress> failedAddresses = populateHostAddresses();
SocketFactory socketFactory = config.getSocketFactory();
ProxyInfo proxyInfo = config.getProxyInfo();
int timeout = config.getConnectTimeout();
if (socketFactory == null) {
socketFactory = SocketFactory.getDefault();
}
for (HostAddress hostAddress : hostAddresses) {
Iterator<InetAddress> inetAddresses = null;
String host = hostAddress.getFQDN();
int port = hostAddress.getPort();
if (proxyInfo == null) {
inetAddresses = hostAddress.getInetAddresses().iterator();
assert(inetAddresses.hasNext());
innerloop: while (inetAddresses.hasNext()) {
// Create a *new* Socket before every connection attempt, i.e. connect() call, since Sockets are not
// re-usable after a failed connection attempt. See also SMACK-724.
socket = socketFactory.createSocket();
final InetAddress inetAddress = inetAddresses.next();
final String inetAddressAndPort = inetAddress + " at port " + port;
LOGGER.finer("Trying to establish TCP connection to " + inetAddressAndPort);
try {
socket.connect(new InetSocketAddress(inetAddress, port), timeout);
} catch (Exception e) {
hostAddress.setException(inetAddress, e);
if (inetAddresses.hasNext()) {
continue innerloop;
} else {
break innerloop;
}
}
LOGGER.finer("Established TCP connection to " + inetAddressAndPort);
// We found a host to connect to, return here
this.host = host;
this.port = port;
return;
}
failedAddresses.add(hostAddress);
} else {
final String hostAndPort = host + " at port " + port;
LOGGER.finer("Trying to establish TCP connection via Proxy to " + hostAndPort);
try {
proxyInfo.getProxySocketConnection().connect(socket, host, port, timeout);
} catch (IOException e) {
hostAddress.setException(e);
continue;
}
LOGGER.finer("Established TCP connection to " + hostAndPort);
// We found a host to connect to, return here
this.host = host;
this.port = port;
return;
}
}
// There are no more host addresses to try
// throw an exception and report all tried
// HostAddresses in the exception
throw ConnectionException.from(failedAddresses);
}
/**
* Initializes the connection by creating a stanza(/packet) reader and writer and opening a
* XMPP stream to the server.
*
* @throws XMPPException if establishing a connection to the server fails.
* @throws SmackException if the server failes to respond back or if there is anther error.
* @throws IOException
*/
private void initConnection() throws IOException {
boolean isFirstInitialization = packetReader == null || packetWriter == null;
compressionHandler = null;
// Set the reader and writer instance variables
initReaderAndWriter();
if (isFirstInitialization) {
packetWriter = new PacketWriter();
packetReader = new PacketReader();
// If debugging is enabled, we should start the thread that will listen for
// all packets and then log them.
if (config.isDebuggerEnabled()) {
addAsyncStanzaListener(debugger.getReaderListener(), null);
if (debugger.getWriterListener() != null) {
addPacketSendingListener(debugger.getWriterListener(), null);
}
}
}
// Start the packet writer. This will open an XMPP stream to the server
packetWriter.init();
// Start the packet reader. The startup() method will block until we
// get an opening stream packet back from server
packetReader.init();
}
private void initReaderAndWriter() throws IOException {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
if (compressionHandler != null) {
is = compressionHandler.getInputStream(is);
os = compressionHandler.getOutputStream(os);
}
// OutputStreamWriter is already buffered, no need to wrap it into a BufferedWriter
writer = new OutputStreamWriter(os, "UTF-8");
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// If debugging is enabled, we open a window and write out all network traffic.
initDebugger();
}
/**
* The server has indicated that TLS negotiation can start. We now need to secure the
* existing plain connection and perform a handshake. This method won't return until the
* connection has finished the handshake or an error occurred while securing the connection.
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
* @throws SmackException
* @throws Exception if an exception occurs.
*/
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
SSLContext context = this.config.getCustomSSLContext();
KeyStore ks = null;
KeyManager[] kms = null;
PasswordCallback pcb = null;
SmackDaneVerifier daneVerifier = null;
if (config.getDnssecMode() == DnssecMode.needsDnssecAndDane) {
SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
if (daneProvider == null) {
throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
}
daneVerifier = daneProvider.newInstance();
if (daneVerifier == null) {
throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
}
}
if (context == null) {
final String keyStoreType = config.getKeystoreType();
final CallbackHandler callbackHandler = config.getCallbackHandler();
final String keystorePath = config.getKeystorePath();
if ("PKCS11".equals(keyStoreType)) {
try {
Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library();
ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
Provider p = (Provider)c.newInstance(config);
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11",p);
pcb = new PasswordCallback("PKCS11 Password: ",false);
callbackHandler.handle(new Callback[]{pcb});
ks.load(null,pcb.getPassword());
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
}
else if ("Apple".equals(keyStoreType)) {
ks = KeyStore.getInstance("KeychainStore","Apple");
ks.load(null,null);
//pcb = new PasswordCallback("Apple Keychain",false);
//pcb.setPassword(null);
}
else if (keyStoreType != null){
ks = KeyStore.getInstance(keyStoreType);
if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
try {
pcb = new PasswordCallback("Keystore Password: ", false);
callbackHandler.handle(new Callback[] { pcb });
ks.load(new FileInputStream(keystorePath), pcb.getPassword());
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
} else {
ks.load(null, null);
}
}
if (ks != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
try {
if (pcb == null) {
kmf.init(ks, null);
}
else {
kmf.init(ks, pcb.getPassword());
pcb.clearPassword();
}
kms = kmf.getKeyManagers();
}
catch (NullPointerException npe) {
LOGGER.log(Level.WARNING, "NullPointerException", npe);
}
}
// If the user didn't specify a SSLContext, use the default one
context = SSLContext.getInstance("TLS");
final SecureRandom secureRandom = new java.security.SecureRandom();
X509TrustManager customTrustManager = config.getCustomX509TrustManager();
if (daneVerifier != null) {
// User requested DANE verification.
daneVerifier.init(context, kms, customTrustManager, secureRandom);
} else {
TrustManager[] customTrustManagers = null;
if (customTrustManager != null) {
customTrustManagers = new TrustManager[] { customTrustManager };
}
context.init(kms, customTrustManagers, secureRandom);
}
}
Socket plain = socket;
// Secure the plain connection
socket = context.getSocketFactory().createSocket(plain,
host, plain.getPort(), true);
final SSLSocket sslSocket = (SSLSocket) socket;
// Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
// important (at least on certain platforms) and it seems to be a good idea anyways to
// prevent an accidental implicit handshake.
TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
// Initialize the reader and writer with the new secured version
initReaderAndWriter();
// Proceed to do the handshake
sslSocket.startHandshake();
if (daneVerifier != null) {
daneVerifier.finish(sslSocket);
}
final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
if (verifier == null) {
throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
} else if (!verifier.verify(getXMPPServiceDomain().toString(), sslSocket.getSession())) {
throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain());
}
// Set that TLS was successful
usingTLS = true;
}
/**
* Returns the compression handler that can be used for one compression methods offered by the server.
*
* @return a instance of XMPPInputOutputStream or null if no suitable instance was found
*
*/
private static XMPPInputOutputStream maybeGetCompressionHandler(Compress.Feature compression) {
for (XMPPInputOutputStream handler : SmackConfiguration.getCompresionHandlers()) {
String method = handler.getCompressionMethod();
if (compression.getMethods().contains(method))
return handler;
}
return null;
}
@Override
public boolean isUsingCompression() {
return compressionHandler != null && compressSyncPoint.wasSuccessful();
}
/**
* <p>
* Starts using stream compression that will compress network traffic. Traffic can be
* reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
* connection. However, the server and the client will need to use more CPU time in order to
* un/compress network data so under high load the server performance might be affected.
* </p>
* <p>
* Stream compression has to have been previously offered by the server. Currently only the
* zlib method is supported by the client. Stream compression negotiation has to be done
* before authentication took place.
* </p>
*
* @throws NotConnectedException
* @throws SmackException
* @throws NoResponseException
* @throws InterruptedException
*/
private void maybeEnableCompression() throws NotConnectedException, NoResponseException, SmackException, InterruptedException {
if (!config.isCompressionEnabled()) {
return;
}
maybeCompressFeaturesReceived.checkIfSuccessOrWait();
Compress.Feature compression = getFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE);
if (compression == null) {
// Server does not support compression
return;
}
// If stream compression was offered by the server and we want to use
// compression then send compression request to the server
if ((compressionHandler = maybeGetCompressionHandler(compression)) != null) {
compressSyncPoint.sendAndWaitForResponseOrThrow(new Compress(compressionHandler.getCompressionMethod()));
} else {
LOGGER.warning("Could not enable compression because no matching handler/method pair was found");
}
}
/**
* Establishes a connection to the XMPP server. It basically
* creates and maintains a socket connection to the server.
* <p>
* Listeners will be preserved from a previous connection if the reconnection
* occurs after an abrupt termination.
* </p>
*
* @throws XMPPException if an error occurs while trying to establish the connection.
* @throws SmackException
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException {
closingStreamReceived.init();
// Establishes the TCP connection to the server and does setup the reader and writer. Throws an exception if
// there is an error establishing the connection
connectUsingConfiguration();
// We connected successfully to the servers TCP port
initConnection();
}
/**
* Sends out a notification that there was an error with the connection
* and closes the connection. Also prints the stack trace of the given exception
*
* @param e the exception that causes the connection close event.
*/
private synchronized void notifyConnectionError(Exception e) {
// Listeners were already notified of the exception, return right here.
if ((packetReader == null || packetReader.done) &&
(packetWriter == null || packetWriter.done())) return;
// Closes the connection temporary. A reconnection is possible
// Note that a connection listener of XMPPTCPConnection will drop the SM state in
// case the Exception is a StreamErrorException.
instantShutdown();
// Notify connection listeners of the error.
callConnectionClosedOnErrorListener(e);
}
/**
* For unit testing purposes
*
* @param writer
*/
protected void setWriter(Writer writer) {
this.writer = writer;
}
@Override
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {
StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
if (startTlsFeature != null) {
if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
notifyConnectionError(new SecurityRequiredByServerException());
return;
}
if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
sendNonza(new StartTls());
}
}
// If TLS is required but the server doesn't offer it, disconnect
// from the server and throw an error. First check if we've already negotiated TLS
// and are secure, however (features get parsed a second time after TLS is established).
if (!isSecureConnection() && startTlsFeature == null
&& getConfiguration().getSecurityMode() == SecurityMode.required) {
throw new SecurityRequiredByClientException();
}
if (getSASLAuthentication().authenticationSuccessful()) {
// If we have received features after the SASL has been successfully completed, then we
// have also *maybe* received, as it is an optional feature, the compression feature
// from the server.
maybeCompressFeaturesReceived.reportSuccess();
}
}
/**
* Resets the parser using the latest connection's reader. Reseting the parser is necessary
* when the plain connection has been secured or when a new opening stream element is going
* to be sent by the server.
*
* @throws SmackException if the parser could not be reset.
* @throws InterruptedException
*/
void openStream() throws SmackException, InterruptedException {
// If possible, provide the receiving entity of the stream open tag, i.e. the server, as much information as
// possible. The 'to' attribute is *always* available. The 'from' attribute if set by the user and no external
// mechanism is used to determine the local entity (user). And the 'id' attribute is available after the first
// response from the server (see e.g. RFC 6120 § 9.1.1 Step 2.)
CharSequence to = getXMPPServiceDomain();
CharSequence from = null;
CharSequence localpart = config.getUsername();
if (localpart != null) {
from = XmppStringUtils.completeJidFrom(localpart, to);
}
String id = getStreamId();
sendNonza(new StreamOpen(to, from, id));
try {
packetReader.parser = PacketParserUtils.newXmppParser(reader);
}
catch (XmlPullParserException e) {
throw new SmackException(e);
}
}
protected class PacketReader {
XmlPullParser parser;
private volatile boolean done;
/**
* Initializes the reader in order to be used. The reader is initialized during the
* first connection and when reconnecting due to an abruptly disconnection.
*/
void init() {
done = false;
Async.go(new Runnable() {
public void run() {
parsePackets();
}
}, "Smack Packet Reader (" + getConnectionCounter() + ")");
}
/**
* Shuts the stanza(/packet) reader down. This method simply sets the 'done' flag to true.
*/
void shutdown() {
done = true;
}
/**
* Parse top-level packets in order to process them further.
*
* @param thread the thread that is being used by the reader to parse incoming packets.
*/
private void parsePackets() {
try {
initalOpenStreamSend.checkIfSuccessOrWait();
int eventType = parser.getEventType();
while (!done) {
switch (eventType) {
case XmlPullParser.START_TAG:
final String name = parser.getName();
switch (name) {
case Message.ELEMENT:
case IQ.IQ_ELEMENT:
case Presence.ELEMENT:
try {
parseAndProcessStanza(parser);
} finally {
clientHandledStanzasCount = SMUtils.incrementHeight(clientHandledStanzasCount);
}
break;
case "stream":
// We found an opening stream.
if ("jabber:client".equals(parser.getNamespace(null))) {
streamId = parser.getAttributeValue("", "id");
String reportedServerDomain = parser.getAttributeValue("", "from");
assert(config.getXMPPServiceDomain().equals(reportedServerDomain));
}
break;
case "error":
throw new StreamErrorException(PacketParserUtils.parseStreamError(parser));
case "features":
parseFeatures(parser);
break;
case "proceed":
try {
// Secure the connection by negotiating TLS
proceedTLSReceived();
// Send a new opening stream to the server
openStream();
}
catch (Exception e) {
// We report any failure regarding TLS in the second stage of XMPP
// connection establishment, namely the SASL authentication
saslFeatureReceived.reportFailure(new SmackException(e));
throw e;
}
break;
case "failure":
String namespace = parser.getNamespace(null);
switch (namespace) {
case "urn:ietf:params:xml:ns:xmpp-tls":
// TLS negotiation has failed. The server will close the connection
// TODO Parse failure stanza
throw new SmackException("TLS negotiation has failed");
case "http://jabber.org/protocol/compress":
// Stream compression has been denied. This is a recoverable
// situation. It is still possible to authenticate and
// use the connection but using an uncompressed connection
// TODO Parse failure stanza
compressSyncPoint.reportFailure(new SmackException(
"Could not establish compression"));
break;
case SaslStreamElements.NAMESPACE:
// SASL authentication has failed. The server may close the connection
// depending on the number of retries
final SASLFailure failure = PacketParserUtils.parseSASLFailure(parser);
getSASLAuthentication().authenticationFailed(failure);
break;
}
break;
case Challenge.ELEMENT:
// The server is challenging the SASL authentication made by the client
String challengeData = parser.nextText();
getSASLAuthentication().challengeReceived(challengeData);
break;
case Success.ELEMENT:
Success success = new Success(parser.nextText());
// We now need to bind a resource for the connection
// Open a new stream and wait for the response
openStream();
// The SASL authentication with the server was successful. The next step
// will be to bind the resource
getSASLAuthentication().authenticated(success);
break;
case Compressed.ELEMENT:
// Server confirmed that it's possible to use stream compression. Start
// stream compression
// Initialize the reader and writer with the new compressed version
initReaderAndWriter();
// Send a new opening stream to the server
openStream();
// Notify that compression is being used
compressSyncPoint.reportSuccess();
break;
case Enabled.ELEMENT:
Enabled enabled = ParseStreamManagement.enabled(parser);
if (enabled.isResumeSet()) {
smSessionId = enabled.getId();
if (StringUtils.isNullOrEmpty(smSessionId)) {
XMPPError.Builder builder = XMPPError.getBuilder(XMPPError.Condition.bad_request);
builder.setDescriptiveEnText("Stream Management 'enabled' element with resume attribute but without session id received");
XMPPErrorException xmppException = new XMPPErrorException(
builder);
smEnabledSyncPoint.reportFailure(xmppException);
throw xmppException;
}
smServerMaxResumptimTime = enabled.getMaxResumptionTime();
} else {
// Mark this a non-resumable stream by setting smSessionId to null
smSessionId = null;
}
clientHandledStanzasCount = 0;
smWasEnabledAtLeastOnce = true;
smEnabledSyncPoint.reportSuccess();
LOGGER.fine("Stream Management (XEP-198): succesfully enabled");
break;
case Failed.ELEMENT:
Failed failed = ParseStreamManagement.failed(parser);
XMPPError.Builder xmppError = XMPPError.getBuilder(failed.getXMPPErrorCondition());
XMPPException xmppException = new XMPPErrorException(xmppError);
// If only XEP-198 would specify different failure elements for the SM
// enable and SM resume failure case. But this is not the case, so we
// need to determine if this is a 'Failed' response for either 'Enable'
// or 'Resume'.
if (smResumedSyncPoint.requestSent()) {
smResumedSyncPoint.reportFailure(xmppException);
}
else {
if (!smEnabledSyncPoint.requestSent()) {
throw new IllegalStateException("Failed element received but SM was not previously enabled");
}
smEnabledSyncPoint.reportFailure(xmppException);
// Report success for last lastFeaturesReceived so that in case a
// failed resumption, we can continue with normal resource binding.
// See text of XEP-198 5. below Example 11.
lastFeaturesReceived.reportSuccess();
}
break;
case Resumed.ELEMENT:
Resumed resumed = ParseStreamManagement.resumed(parser);
if (!smSessionId.equals(resumed.getPrevId())) {
throw new StreamIdDoesNotMatchException(smSessionId, resumed.getPrevId());
}
// Mark SM as enabled and resumption as successful.
smResumedSyncPoint.reportSuccess();
smEnabledSyncPoint.reportSuccess();
// First, drop the stanzas already handled by the server
processHandledCount(resumed.getHandledCount());
// Then re-send what is left in the unacknowledged queue
List<Stanza> stanzasToResend = new ArrayList<>(unacknowledgedStanzas.size());
unacknowledgedStanzas.drainTo(stanzasToResend);
for (Stanza stanza : stanzasToResend) {
sendStanzaInternal(stanza);
}
// If there where stanzas resent, then request a SM ack for them.
// Writer's sendStreamElement() won't do it automatically based on
// predicates.
if (!stanzasToResend.isEmpty()) {
requestSmAcknowledgementInternal();
}
LOGGER.fine("Stream Management (XEP-198): Stream resumed");
break;
case AckAnswer.ELEMENT:
AckAnswer ackAnswer = ParseStreamManagement.ackAnswer(parser);
processHandledCount(ackAnswer.getHandledCount());
break;
case AckRequest.ELEMENT:
ParseStreamManagement.ackRequest(parser);
if (smEnabledSyncPoint.wasSuccessful()) {
sendSmAcknowledgementInternal();
} else {
LOGGER.warning("SM Ack Request received while SM is not enabled");
}
break;
default:
LOGGER.warning("Unknown top level stream element: " + name);
break;
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("stream")) {
if (!parser.getNamespace().equals("http://etherx.jabber.org/streams")) {
LOGGER.warning(XMPPTCPConnection.this + " </stream> but different namespace " + parser.getNamespace());
break;
}
// Check if the queue was already shut down before reporting success on closing stream tag
// received. This avoids a race if there is a disconnect(), followed by a connect(), which
// did re-start the queue again, causing this writer to assume that the queue is not
// shutdown, which results in a call to disconnect().
final boolean queueWasShutdown = packetWriter.queue.isShutdown();
closingStreamReceived.reportSuccess();
if (queueWasShutdown) {
// We received a closing stream element *after* we initiated the
// termination of the session by sending a closing stream element to
// the server first
return;
} else {
// We received a closing stream element from the server without us
// sending a closing stream element first. This means that the
// server wants to terminate the session, therefore disconnect
// the connection
LOGGER.info(XMPPTCPConnection.this
+ " received closing </stream> element."
+ " Server wants to terminate the connection, calling disconnect()");
disconnect();
}
}
break;
case XmlPullParser.END_DOCUMENT:
// END_DOCUMENT only happens in an error case, as otherwise we would see a
// closing stream element before.
throw new SmackException(
"Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element");
}
eventType = parser.next();
}
}
catch (Exception e) {
closingStreamReceived.reportFailure(e);
// The exception can be ignored if the the connection is 'done'
// or if the it was caused because the socket got closed
if (!(done || packetWriter.queue.isShutdown())) {
// Close the connection and notify connection listeners of the
// error.
notifyConnectionError(e);
}
}
}
}
protected class PacketWriter {
public static final int QUEUE_SIZE = XMPPTCPConnection.QUEUE_SIZE;
private final ArrayBlockingQueueWithShutdown<Element> queue = new ArrayBlockingQueueWithShutdown<Element>(
QUEUE_SIZE, true);
/**
* Needs to be protected for unit testing purposes.
*/
protected SynchronizationPoint<NoResponseException> shutdownDone = new SynchronizationPoint<NoResponseException>(
XMPPTCPConnection.this, "shutdown completed");
/**
* If set, the stanza(/packet) writer is shut down
*/
protected volatile Long shutdownTimestamp = null;
private volatile boolean instantShutdown;
/**
* True if some preconditions are given to start the bundle and defer mechanism.
* <p>
* This will likely get set to true right after the start of the writer thread, because
* {@link #nextStreamElement()} will check if {@link queue} is empty, which is probably the case, and then set
* this field to true.
* </p>
*/
private boolean shouldBundleAndDefer;
/**
* Initializes the writer in order to be used. It is called at the first connection and also
* is invoked if the connection is disconnected by an error.
*/
void init() {
shutdownDone.init();
shutdownTimestamp = null;
if (unacknowledgedStanzas != null) {
// It's possible that there are new stanzas in the writer queue that
// came in while we were disconnected but resumable, drain those into
// the unacknowledged queue so that they get resent now
drainWriterQueueToUnacknowledgedStanzas();
}
queue.start();
Async.go(new Runnable() {
@Override
public void run() {
writePackets();
}
}, "Smack Packet Writer (" + getConnectionCounter() + ")");
}
private boolean done() {
return shutdownTimestamp != null;
}
protected void throwNotConnectedExceptionIfDoneAndResumptionNotPossible() throws NotConnectedException {
final boolean done = done();
if (done) {
final boolean smResumptionPossbile = isSmResumptionPossible();
// Don't throw a NotConnectedException is there is an resumable stream available
if (!smResumptionPossbile) {
throw new NotConnectedException(XMPPTCPConnection.this, "done=" + done
+ " smResumptionPossible=" + smResumptionPossbile);
}
}
}
/**
* Sends the specified element to the server.
*
* @param element the element to send.
* @throws NotConnectedException
* @throws InterruptedException
*/
protected void sendStreamElement(Element element) throws NotConnectedException, InterruptedException {
throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
try {
queue.put(element);
}
catch (InterruptedException e) {
// put() may throw an InterruptedException for two reasons:
// 1. If the queue was shut down
// 2. If the thread was interrupted
// so we have to check which is the case
throwNotConnectedExceptionIfDoneAndResumptionNotPossible();
// If the method above did not throw, then the sending thread was interrupted
throw e;
}
}
/**
* Shuts down the stanza(/packet) writer. Once this method has been called, no further
* packets will be written to the server.
* @throws InterruptedException
*/
void shutdown(boolean instant) {
instantShutdown = instant;
queue.shutdown();
shutdownTimestamp = System.currentTimeMillis();
try {
shutdownDone.checkIfSuccessOrWait();
}
catch (NoResponseException | InterruptedException e) {
LOGGER.log(Level.WARNING, "shutdownDone was not marked as successful by the writer thread", e);
}
}
/**
* Maybe return the next available element from the queue for writing. If the queue is shut down <b>or</b> a
* spurious interrupt occurs, <code>null</code> is returned. So it is important to check the 'done' condition in
* that case.
*
* @return the next element for writing or null.
*/
private Element nextStreamElement() {
// It is important the we check if the queue is empty before removing an element from it
if (queue.isEmpty()) {
shouldBundleAndDefer = true;
}
Element packet = null;
try {
packet = queue.take();
}
catch (InterruptedException e) {
if (!queue.isShutdown()) {
// Users shouldn't try to interrupt the packet writer thread
LOGGER.log(Level.WARNING, "Packet writer thread was interrupted. Don't do that. Use disconnect() instead.", e);
}
}
return packet;
}
private void writePackets() {
Exception writerException = null;
try {
openStream();
initalOpenStreamSend.reportSuccess();
// Write out packets from the queue.
while (!done()) {
Element element = nextStreamElement();
if (element == null) {
continue;
}
// Get a local version of the bundle and defer callback, in case it's unset
// between the null check and the method invocation
final BundleAndDeferCallback localBundleAndDeferCallback = bundleAndDeferCallback;
// If the preconditions are given (e.g. bundleAndDefer callback is set, queue is
// empty), then we could wait a bit for further stanzas attempting to decrease
// our energy consumption
if (localBundleAndDeferCallback != null && isAuthenticated() && shouldBundleAndDefer) {
// Reset shouldBundleAndDefer to false, nextStreamElement() will set it to true once the
// queue is empty again.
shouldBundleAndDefer = false;
final AtomicBoolean bundlingAndDeferringStopped = new AtomicBoolean();
final int bundleAndDeferMillis = localBundleAndDeferCallback.getBundleAndDeferMillis(new BundleAndDefer(
bundlingAndDeferringStopped));
if (bundleAndDeferMillis > 0) {
long remainingWait = bundleAndDeferMillis;
final long waitStart = System.currentTimeMillis();
synchronized (bundlingAndDeferringStopped) {
while (!bundlingAndDeferringStopped.get() && remainingWait > 0) {
bundlingAndDeferringStopped.wait(remainingWait);
remainingWait = bundleAndDeferMillis
- (System.currentTimeMillis() - waitStart);
}
}
}
}
Stanza packet = null;
if (element instanceof Stanza) {
packet = (Stanza) element;
}
else if (element instanceof Enable) {
// The client needs to add messages to the unacknowledged stanzas queue
// right after it sent 'enabled'. Stanza will be added once
// unacknowledgedStanzas is not null.
unacknowledgedStanzas = new ArrayBlockingQueue<>(QUEUE_SIZE);
}
// Check if the stream element should be put to the unacknowledgedStanza
// queue. Note that we can not do the put() in sendStanzaInternal() and the
// packet order is not stable at this point (sendStanzaInternal() can be
// called concurrently).
if (unacknowledgedStanzas != null && packet != null) {
// If the unacknowledgedStanza queue is nearly full, request an new ack
// from the server in order to drain it
if (unacknowledgedStanzas.size() == 0.8 * XMPPTCPConnection.QUEUE_SIZE) {
writer.write(AckRequest.INSTANCE.toXML().toString());
writer.flush();
}
try {
// It is important the we put the stanza in the unacknowledged stanza
// queue before we put it on the wire
unacknowledgedStanzas.put(packet);
}
catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
CharSequence elementXml = element.toXML();
if (elementXml instanceof XmlStringBuilder) {
((XmlStringBuilder) elementXml).write(writer);
}
else {
writer.write(elementXml.toString());
}
if (queue.isEmpty()) {
writer.flush();
}
if (packet != null) {
firePacketSendingListeners(packet);
}
}
if (!instantShutdown) {
// Flush out the rest of the queue.
try {
while (!queue.isEmpty()) {
Element packet = queue.remove();
writer.write(packet.toXML().toString());
}
writer.flush();
}
catch (Exception e) {
LOGGER.log(Level.WARNING,
"Exception flushing queue during shutdown, ignore and continue",
e);
}
// Close the stream.
try {
writer.write("</stream:stream>");
writer.flush();
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception writing closing stream element", e);
}
// Delete the queue contents (hopefully nothing is left).
queue.clear();
} else if (instantShutdown && isSmEnabled()) {
// This was an instantShutdown and SM is enabled, drain all remaining stanzas
// into the unacknowledgedStanzas queue
drainWriterQueueToUnacknowledgedStanzas();
}
// Do *not* close the writer here, as it will cause the socket
// to get closed. But we may want to receive further stanzas
// until the closing stream tag is received. The socket will be
// closed in shutdown().
}
catch (Exception e) {
// The exception can be ignored if the the connection is 'done'
// or if the it was caused because the socket got closed
if (!(done() || queue.isShutdown())) {
writerException = e;
} else {
LOGGER.log(Level.FINE, "Ignoring Exception in writePackets()", e);
}
} finally {
LOGGER.fine("Reporting shutdownDone success in writer thread");
shutdownDone.reportSuccess();
}
// Delay notifyConnectionError after shutdownDone has been reported in the finally block.
if (writerException != null) {
notifyConnectionError(writerException);
}
}
private void drainWriterQueueToUnacknowledgedStanzas() {
List<Element> elements = new ArrayList<Element>(queue.size());
queue.drainTo(elements);
for (Element element : elements) {
if (element instanceof Stanza) {
unacknowledgedStanzas.add((Stanza) element);
}
}
}
}
/**
* Set if Stream Management should be used by default for new connections.
*
* @param useSmDefault true to use Stream Management for new connections.
*/
public static void setUseStreamManagementDefault(boolean useSmDefault) {
XMPPTCPConnection.useSmDefault = useSmDefault;
}
/**
* Set if Stream Management resumption should be used by default for new connections.
*
* @param useSmResumptionDefault true to use Stream Management resumption for new connections.
* @deprecated use {@link #setUseStreamManagementResumptionDefault(boolean)} instead.
*/
@Deprecated
public static void setUseStreamManagementResumptiodDefault(boolean useSmResumptionDefault) {
setUseStreamManagementResumptionDefault(useSmResumptionDefault);
}
/**
* Set if Stream Management resumption should be used by default for new connections.
*
* @param useSmResumptionDefault true to use Stream Management resumption for new connections.
*/
public static void setUseStreamManagementResumptionDefault(boolean useSmResumptionDefault) {
if (useSmResumptionDefault) {
// Also enable SM is resumption is enabled
setUseStreamManagementDefault(useSmResumptionDefault);
}
XMPPTCPConnection.useSmResumptionDefault = useSmResumptionDefault;
}
/**
* Set if Stream Management should be used if supported by the server.
*
* @param useSm true to use Stream Management.
*/
public void setUseStreamManagement(boolean useSm) {
this.useSm = useSm;
}
/**
* Set if Stream Management resumption should be used if supported by the server.
*
* @param useSmResumption true to use Stream Management resumption.
*/
public void setUseStreamManagementResumption(boolean useSmResumption) {
if (useSmResumption) {
// Also enable SM is resumption is enabled
setUseStreamManagement(useSmResumption);
}
this.useSmResumption = useSmResumption;
}
/**
* Set the preferred resumption time in seconds.
* @param resumptionTime the preferred resumption time in seconds
*/
public void setPreferredResumptionTime(int resumptionTime) {
smClientMaxResumptionTime = resumptionTime;
}
/**
* Add a predicate for Stream Management acknowledgment requests.
* <p>
* Those predicates are used to determine when a Stream Management acknowledgement request is send to the server.
* Some pre-defined predicates are found in the <code>org.jivesoftware.smack.sm.predicates</code> package.
* </p>
* <p>
* If not predicate is configured, the {@link Predicate#forMessagesOrAfter5Stanzas()} will be used.
* </p>
*
* @param predicate the predicate to add.
* @return if the predicate was not already active.
*/
public boolean addRequestAckPredicate(StanzaFilter predicate) {
synchronized (requestAckPredicates) {
return requestAckPredicates.add(predicate);
}
}
/**
* Remove the given predicate for Stream Management acknowledgment request.
* @param predicate the predicate to remove.
* @return true if the predicate was removed.
*/
public boolean removeRequestAckPredicate(StanzaFilter predicate) {
synchronized (requestAckPredicates) {
return requestAckPredicates.remove(predicate);
}
}
/**
* Remove all predicates for Stream Management acknowledgment requests.
*/
public void removeAllRequestAckPredicates() {
synchronized (requestAckPredicates) {
requestAckPredicates.clear();
}
}
/**
* Send an unconditional Stream Management acknowledgement request to the server.
*
* @throws StreamManagementNotEnabledException if Stream Mangement is not enabled.
* @throws NotConnectedException if the connection is not connected.
* @throws InterruptedException
*/
public void requestSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException, InterruptedException {
if (!isSmEnabled()) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
requestSmAcknowledgementInternal();
}
private void requestSmAcknowledgementInternal() throws NotConnectedException, InterruptedException {
packetWriter.sendStreamElement(AckRequest.INSTANCE);
}
/**
* Send a unconditional Stream Management acknowledgment to the server.
* <p>
* See <a href="http://xmpp.org/extensions/xep-0198.html#acking">XEP-198: Stream Management § 4. Acks</a>:
* "Either party MAY send an <a/> element at any time (e.g., after it has received a certain number of stanzas,
* or after a certain period of time), even if it has not received an <r/> element from the other party."
* </p>
*
* @throws StreamManagementNotEnabledException if Stream Management is not enabled.
* @throws NotConnectedException if the connection is not connected.
* @throws InterruptedException
*/
public void sendSmAcknowledgement() throws StreamManagementNotEnabledException, NotConnectedException, InterruptedException {
if (!isSmEnabled()) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
sendSmAcknowledgementInternal();
}
private void sendSmAcknowledgementInternal() throws NotConnectedException, InterruptedException {
packetWriter.sendStreamElement(new AckAnswer(clientHandledStanzasCount));
}
/**
* Add a Stanza acknowledged listener.
* <p>
* Those listeners will be invoked every time a Stanza has been acknowledged by the server. The will not get
* automatically removed. Consider using {@link #addStanzaIdAcknowledgedListener(String, StanzaListener)} when
* possible.
* </p>
*
* @param listener the listener to add.
*/
public void addStanzaAcknowledgedListener(StanzaListener listener) {
stanzaAcknowledgedListeners.add(listener);
}
/**
* Remove the given Stanza acknowledged listener.
*
* @param listener the listener.
* @return true if the listener was removed.
*/
public boolean removeStanzaAcknowledgedListener(StanzaListener listener) {
return stanzaAcknowledgedListeners.remove(listener);
}
/**
* Remove all stanza acknowledged listeners.
*/
public void removeAllStanzaAcknowledgedListeners() {
stanzaAcknowledgedListeners.clear();
}
/**
* Add a new Stanza ID acknowledged listener for the given ID.
* <p>
* The listener will be invoked if the stanza with the given ID was acknowledged by the server. It will
* automatically be removed after the listener was run.
* </p>
*
* @param id the stanza ID.
* @param listener the listener to invoke.
* @return the previous listener for this stanza ID or null.
* @throws StreamManagementNotEnabledException if Stream Management is not enabled.
*/
public StanzaListener addStanzaIdAcknowledgedListener(final String id, StanzaListener listener) throws StreamManagementNotEnabledException {
// Prevent users from adding callbacks that will never get removed
if (!smWasEnabledAtLeastOnce) {
throw new StreamManagementException.StreamManagementNotEnabledException();
}
// Remove the listener after max. 12 hours
final int removeAfterSeconds = Math.min(getMaxSmResumptionTime(), 12 * 60 * 60);
schedule(new Runnable() {
@Override
public void run() {
stanzaIdAcknowledgedListeners.remove(id);
}
}, removeAfterSeconds, TimeUnit.SECONDS);
return stanzaIdAcknowledgedListeners.put(id, listener);
}
/**
* Remove the Stanza ID acknowledged listener for the given ID.
*
* @param id the stanza ID.
* @return true if the listener was found and removed, false otherwise.
*/
public StanzaListener removeStanzaIdAcknowledgedListener(String id) {
return stanzaIdAcknowledgedListeners.remove(id);
}
/**
* Removes all Stanza ID acknowledged listeners.
*/
public void removeAllStanzaIdAcknowledgedListeners() {
stanzaIdAcknowledgedListeners.clear();
}
/**
* Returns true if Stream Management is supported by the server.
*
* @return true if Stream Management is supported by the server.
*/
public boolean isSmAvailable() {
return hasFeature(StreamManagementFeature.ELEMENT, StreamManagement.NAMESPACE);
}
/**
* Returns true if Stream Management was successfully negotiated with the server.
*
* @return true if Stream Management was negotiated.
*/
public boolean isSmEnabled() {
return smEnabledSyncPoint.wasSuccessful();
}
/**
* Returns true if the stream was successfully resumed with help of Stream Management.
*
* @return true if the stream was resumed.
*/
public boolean streamWasResumed() {
return smResumedSyncPoint.wasSuccessful();
}
/**
* Returns true if the connection is disconnected by a Stream resumption via Stream Management is possible.
*
* @return true if disconnected but resumption possible.
*/
public boolean isDisconnectedButSmResumptionPossible() {
return disconnectedButResumeable && isSmResumptionPossible();
}
/**
* Returns true if the stream is resumable.
*
* @return true if the stream is resumable.
*/
public boolean isSmResumptionPossible() {
// There is no resumable stream available
if (smSessionId == null)
return false;
final Long shutdownTimestamp = packetWriter.shutdownTimestamp;
// Seems like we are already reconnected, report true
if (shutdownTimestamp == null) {
return true;
}
// See if resumption time is over
long current = System.currentTimeMillis();
long maxResumptionMillies = ((long) getMaxSmResumptionTime()) * 1000;
if (current > shutdownTimestamp + maxResumptionMillies) {
// Stream resumption is *not* possible if the current timestamp is greater then the greatest timestamp where
// resumption is possible
return false;
} else {
return true;
}
}
/**
* Drop the stream management state. Sets {@link #smSessionId} and
* {@link #unacknowledgedStanzas} to <code>null</code>.
*/
private void dropSmState() {
// clientHandledCount and serverHandledCount will be reset on <enable/> and <enabled/>
// respective. No need to reset them here.
smSessionId = null;
unacknowledgedStanzas = null;
}
/**
* Get the maximum resumption time in seconds after which a managed stream can be resumed.
* <p>
* This method will return {@link Integer#MAX_VALUE} if neither the client nor the server specify a maximum
* resumption time. Be aware of integer overflows when using this value, e.g. do not add arbitrary values to it
* without checking for overflows before.
* </p>
*
* @return the maximum resumption time in seconds or {@link Integer#MAX_VALUE} if none set.
*/
public int getMaxSmResumptionTime() {
int clientResumptionTime = smClientMaxResumptionTime > 0 ? smClientMaxResumptionTime : Integer.MAX_VALUE;
int serverResumptionTime = smServerMaxResumptimTime > 0 ? smServerMaxResumptimTime : Integer.MAX_VALUE;
return Math.min(clientResumptionTime, serverResumptionTime);
}
private void processHandledCount(long handledCount) throws StreamManagementCounterError {
long ackedStanzasCount = SMUtils.calculateDelta(handledCount, serverHandledStanzasCount);
final List<Stanza> ackedStanzas = new ArrayList<Stanza>(
ackedStanzasCount <= Integer.MAX_VALUE ? (int) ackedStanzasCount
: Integer.MAX_VALUE);
for (long i = 0; i < ackedStanzasCount; i++) {
Stanza ackedStanza = unacknowledgedStanzas.poll();
// If the server ack'ed a stanza, then it must be in the
// unacknowledged stanza queue. There can be no exception.
if (ackedStanza == null) {
throw new StreamManagementCounterError(handledCount, serverHandledStanzasCount,
ackedStanzasCount, ackedStanzas);
}
ackedStanzas.add(ackedStanza);
}
boolean atLeastOneStanzaAcknowledgedListener = false;
if (!stanzaAcknowledgedListeners.isEmpty()) {
// If stanzaAcknowledgedListeners is not empty, the we have at least one
atLeastOneStanzaAcknowledgedListener = true;
}
else {
// Otherwise we look for a matching id in the stanza *id* acknowledged listeners
for (Stanza ackedStanza : ackedStanzas) {
String id = ackedStanza.getStanzaId();
if (id != null && stanzaIdAcknowledgedListeners.containsKey(id)) {
atLeastOneStanzaAcknowledgedListener = true;
break;
}
}
}
// Only spawn a new thread if there is a chance that some listener is invoked
if (atLeastOneStanzaAcknowledgedListener) {
asyncGo(new Runnable() {
@Override
public void run() {
for (Stanza ackedStanza : ackedStanzas) {
for (StanzaListener listener : stanzaAcknowledgedListeners) {
try {
listener.processPacket(ackedStanza);
}
catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.FINER, "Received exception", e);
}
}
String id = ackedStanza.getStanzaId();
if (StringUtils.isNullOrEmpty(id)) {
continue;
}
StanzaListener listener = stanzaIdAcknowledgedListeners.remove(id);
if (listener != null) {
try {
listener.processPacket(ackedStanza);
}
catch (InterruptedException | NotConnectedException e) {
LOGGER.log(Level.FINER, "Received exception", e);
}
}
}
}
});
}
serverHandledStanzasCount = handledCount;
}
/**
* Set the default bundle and defer callback used for new connections.
*
* @param defaultBundleAndDeferCallback
* @see BundleAndDeferCallback
* @since 4.1
*/
public static void setDefaultBundleAndDeferCallback(BundleAndDeferCallback defaultBundleAndDeferCallback) {
XMPPTCPConnection.defaultBundleAndDeferCallback = defaultBundleAndDeferCallback;
}
/**
* Set the bundle and defer callback used for this connection.
* <p>
* You can use <code>null</code> as argument to reset the callback. Outgoing stanzas will then
* no longer get deferred.
* </p>
*
* @param bundleAndDeferCallback the callback or <code>null</code>.
* @see BundleAndDeferCallback
* @since 4.1
*/
public void setBundleandDeferCallback(BundleAndDeferCallback bundleAndDeferCallback) {
this.bundleAndDeferCallback = bundleAndDeferCallback;
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/bad_4769_1
|
crossvul-java_data_good_2298_1
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.contexts.cache;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.weld.tests.category.Integration;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
@RunWith(Arquillian.class)
@Category(Integration.class)
public class RequestScopedCacheLeakTest {
@ArquillianResource
private URL contextPath;
@Deployment(testable = false)
public static WebArchive getDeployment() {
return ShrinkWrap.create(WebArchive.class).addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addClasses(SimpleServlet.class, ConversationScopedBean.class);
}
@Test
public void test() throws Exception {
WebClient webClient = new WebClient();
webClient.setThrowExceptionOnFailingStatusCode(false);
for (int i = 0; i < 100; i++) {
// first, send out a hundred of poisoning requests
// each of these should leave a thread in a broken state
sendRequest(webClient, i, true);
}
for (int i = 0; i < 100; i++) {
// now send out normal requests to see if they are affected by the thread's broken state
String result = sendRequest(webClient, i, false);
Assert.assertFalse("Invalid state detected after " + (i + 1) + " requests", result.startsWith("bar"));
}
}
private String sendRequest(WebClient webClient, int sequence, boolean poison) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
final String path = getPath("getAndSet", sequence, poison);
return webClient.getPage(path).getWebResponse().getContentAsString().trim();
}
private String getPath(String test, int sequence, boolean poison) {
String path = contextPath + "/servlet?action=" + test + "&sequence=" + sequence;
if (poison) {
path += "&poison=true";
}
return path;
}
}
|
./CrossVul/dataset_final_sorted/CWE-362/java/good_2298_1
|
crossvul-java_data_bad_1896_2
|
package io.onedev.server.web.component.markdown;
import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxChannel;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.FormComponentPanel;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unbescape.javascript.JavaScriptEscape;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import io.onedev.commons.launcher.loader.AppLoader;
import io.onedev.server.OneDev;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.model.Build;
import io.onedev.server.model.Issue;
import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.User;
import io.onedev.server.util.markdown.MarkdownManager;
import io.onedev.server.util.validation.ProjectNameValidator;
import io.onedev.server.web.avatar.AvatarManager;
import io.onedev.server.web.behavior.AbstractPostAjaxBehavior;
import io.onedev.server.web.component.floating.FloatingPanel;
import io.onedev.server.web.component.link.DropdownLink;
import io.onedev.server.web.component.markdown.emoji.EmojiOnes;
import io.onedev.server.web.component.modal.ModalPanel;
import io.onedev.server.web.page.project.ProjectPage;
import io.onedev.server.web.page.project.blob.render.BlobRenderContext;
@SuppressWarnings("serial")
public class MarkdownEditor extends FormComponentPanel<String> {
protected static final int ATWHO_LIMIT = 10;
private static final Logger logger = LoggerFactory.getLogger(MarkdownEditor.class);
private final boolean compactMode;
private final boolean initialSplit;
private final BlobRenderContext blobRenderContext;
private WebMarkupContainer container;
private TextArea<String> input;
private AbstractPostAjaxBehavior actionBehavior;
private AbstractPostAjaxBehavior attachmentUploadBehavior;
/**
* @param id
* component id of the editor
* @param model
* markdown model of the editor
* @param compactMode
* editor in compact mode occupies horizontal space and is suitable
* to be used in places such as comment aside the code
*/
public MarkdownEditor(String id, IModel<String> model, boolean compactMode,
@Nullable BlobRenderContext blobRenderContext) {
super(id, model);
this.compactMode = compactMode;
String cookieKey;
if (compactMode)
cookieKey = "markdownEditor.compactMode.split";
else
cookieKey = "markdownEditor.normalMode.split";
WebRequest request = (WebRequest) RequestCycle.get().getRequest();
Cookie cookie = request.getCookie(cookieKey);
initialSplit = cookie!=null && "true".equals(cookie.getValue());
this.blobRenderContext = blobRenderContext;
}
@Override
protected void onModelChanged() {
super.onModelChanged();
input.setModelObject(getModelObject());
}
public void clearMarkdown() {
setModelObject("");
input.setConvertedInput(null);
}
private String renderInput(String input) {
if (StringUtils.isNotBlank(input)) {
// Normalize line breaks to make source position tracking information comparable
// to textarea caret position when sync edit/preview scroll bar
input = StringUtils.replace(input, "\r\n", "\n");
return renderMarkdown(input);
} else {
return "<div class='message'>Nothing to preview</div>";
}
}
protected String renderMarkdown(String markdown) {
Project project ;
if (getPage() instanceof ProjectPage)
project = ((ProjectPage) getPage()).getProject();
else
project = null;
MarkdownManager manager = OneDev.getInstance(MarkdownManager.class);
return manager.process(manager.render(markdown), project, blobRenderContext);
}
@Override
protected void onInitialize() {
super.onInitialize();
container = new WebMarkupContainer("container");
container.setOutputMarkupId(true);
add(container);
WebMarkupContainer editLink = new WebMarkupContainer("editLink");
WebMarkupContainer splitLink = new WebMarkupContainer("splitLink");
WebMarkupContainer preview = new WebMarkupContainer("preview");
WebMarkupContainer edit = new WebMarkupContainer("edit");
container.add(editLink);
container.add(splitLink);
container.add(preview);
container.add(edit);
container.add(AttributeAppender.append("class", compactMode?"compact-mode":"normal-mode"));
container.add(new DropdownLink("doReference") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new Fragment(id, "referenceMenuFrag", MarkdownEditor.this) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.setupActionMenu($('#%s'), $('#%s'));",
container.getMarkupId(), getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setOutputMarkupId(true);
}
}.setVisible(getReferenceSupport() != null));
container.add(new DropdownLink("actionMenuTrigger") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new Fragment(id, "actionMenuFrag", MarkdownEditor.this) {
@Override
protected void onInitialize() {
super.onInitialize();
add(new WebMarkupContainer("doMention").setVisible(getUserMentionSupport() != null));
if (getReferenceSupport() != null)
add(new Fragment("doReference", "referenceMenuFrag", MarkdownEditor.this));
else
add(new WebMarkupContainer("doReference").setVisible(false));
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.setupActionMenu($('#%s'), $('#%s'));",
container.getMarkupId(), getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setOutputMarkupId(true);
}
});
container.add(new WebMarkupContainer("doMention").setVisible(getUserMentionSupport() != null));
edit.add(input = new TextArea<String>("input", Model.of(getModelObject())));
for (AttributeModifier modifier: getInputModifiers())
input.add(modifier);
if (initialSplit) {
container.add(AttributeAppender.append("class", "split-mode"));
preview.add(new Label("rendered", new LoadableDetachableModel<String>() {
@Override
protected String load() {
return renderInput(input.getConvertedInput());
}
}) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format(
"onedev.server.markdown.initRendered($('#%s>.body>.preview>.markdown-rendered'));",
container.getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setEscapeModelStrings(false));
splitLink.add(AttributeAppender.append("class", "active"));
} else {
container.add(AttributeAppender.append("class", "edit-mode"));
preview.add(new WebMarkupContainer("rendered"));
editLink.add(AttributeAppender.append("class", "active"));
}
container.add(new WebMarkupContainer("canAttachFile").setVisible(getAttachmentSupport()!=null));
container.add(actionBehavior = new AbstractPostAjaxBehavior() {
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.setChannel(new AjaxChannel("markdown-preview", AjaxChannel.Type.DROP));
}
@Override
protected void respond(AjaxRequestTarget target) {
IRequestParameters params = RequestCycle.get().getRequest().getPostParameters();
String action = params.getParameterValue("action").toString("");
switch (action) {
case "render":
String markdown = params.getParameterValue("param1").toString();
String rendered = renderInput(markdown);
String script = String.format("onedev.server.markdown.onRendered('%s', '%s');",
container.getMarkupId(), JavaScriptEscape.escapeJavaScript(rendered));
target.appendJavaScript(script);
break;
case "emojiQuery":
List<String> emojiNames = new ArrayList<>();
String emojiQuery = params.getParameterValue("param1").toOptionalString();
if (StringUtils.isNotBlank(emojiQuery)) {
emojiQuery = emojiQuery.toLowerCase();
for (String emojiName: EmojiOnes.getInstance().all().keySet()) {
if (emojiName.toLowerCase().contains(emojiQuery))
emojiNames.add(emojiName);
}
emojiNames.sort((name1, name2) -> name1.length() - name2.length());
} else {
emojiNames.add("smile");
emojiNames.add("worried");
emojiNames.add("blush");
emojiNames.add("+1");
emojiNames.add("-1");
}
List<Map<String, String>> emojis = new ArrayList<>();
for (String emojiName: emojiNames) {
if (emojis.size() < ATWHO_LIMIT) {
String emojiCode = EmojiOnes.getInstance().all().get(emojiName);
CharSequence url = RequestCycle.get().urlFor(new PackageResourceReference(
EmojiOnes.class, "icon/" + emojiCode + ".png"), new PageParameters());
Map<String, String> emoji = new HashMap<>();
emoji.put("name", emojiName);
emoji.put("url", url.toString());
emojis.add(emoji);
}
}
String json;
try {
json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(emojis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoEmojiRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "loadEmojis":
emojis = new ArrayList<>();
String urlPattern = RequestCycle.get().urlFor(new PackageResourceReference(EmojiOnes.class,
"icon/FILENAME.png"), new PageParameters()).toString();
for (Map.Entry<String, String> entry: EmojiOnes.getInstance().all().entrySet()) {
Map<String, String> emoji = new HashMap<>();
emoji.put("name", entry.getKey());
emoji.put("url", urlPattern.replace("FILENAME", entry.getValue()));
emojis.add(emoji);
}
try {
json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(emojis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("onedev.server.markdown.onEmojisLoaded('%s', %s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "userQuery":
String userQuery = params.getParameterValue("param1").toOptionalString();
AvatarManager avatarManager = OneDev.getInstance(AvatarManager.class);
List<Map<String, String>> userList = new ArrayList<>();
for (User user: getUserMentionSupport().findUsers(userQuery, ATWHO_LIMIT)) {
Map<String, String> userMap = new HashMap<>();
userMap.put("name", user.getName());
if (user.getFullName() != null)
userMap.put("fullName", user.getFullName());
String noSpaceName = StringUtils.deleteWhitespace(user.getName());
if (user.getFullName() != null) {
String noSpaceFullName = StringUtils.deleteWhitespace(user.getFullName());
userMap.put("searchKey", noSpaceName + " " + noSpaceFullName);
} else {
userMap.put("searchKey", noSpaceName);
}
String avatarUrl = avatarManager.getAvatarUrl(user);
userMap.put("avatarUrl", avatarUrl);
userList.add(userMap);
}
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(userList);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoUserRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "referenceQuery":
String referenceQuery = params.getParameterValue("param1").toOptionalString();
String referenceQueryType = params.getParameterValue("param2").toOptionalString();
String referenceProjectName = params.getParameterValue("param3").toOptionalString();
List<Map<String, String>> referenceList = new ArrayList<>();
Project referenceProject;
if (StringUtils.isNotBlank(referenceProjectName))
referenceProject = OneDev.getInstance(ProjectManager.class).find(referenceProjectName);
else
referenceProject = null;
if (referenceProject != null || StringUtils.isBlank(referenceProjectName)) {
if ("issue".equals(referenceQueryType)) {
for (Issue issue: getReferenceSupport().findIssues(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "issue");
referenceMap.put("referenceNumber", String.valueOf(issue.getNumber()));
referenceMap.put("referenceTitle", issue.getTitle());
referenceMap.put("searchKey", issue.getNumber() + " " + StringUtils.deleteWhitespace(issue.getTitle()));
referenceList.add(referenceMap);
}
} else if ("pullrequest".equals(referenceQueryType)) {
for (PullRequest request: getReferenceSupport().findPullRequests(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "pull request");
referenceMap.put("referenceNumber", String.valueOf(request.getNumber()));
referenceMap.put("referenceTitle", request.getTitle());
referenceMap.put("searchKey", request.getNumber() + " " + StringUtils.deleteWhitespace(request.getTitle()));
referenceList.add(referenceMap);
}
} else if ("build".equals(referenceQueryType)) {
for (Build build: getReferenceSupport().findBuilds(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "build");
referenceMap.put("referenceNumber", String.valueOf(build.getNumber()));
String title;
if (build.getVersion() != null)
title = "(" + build.getVersion() + ") " + build.getJobName();
else
title = build.getJobName();
referenceMap.put("referenceTitle", title);
referenceMap.put("searchKey", build.getNumber() + " " + StringUtils.deleteWhitespace(title));
referenceList.add(referenceMap);
}
}
}
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(referenceList);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoReferenceRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "selectImage":
case "selectLink":
new ModalPanel(target) {
@Override
protected Component newContent(String id) {
return new InsertUrlPanel(id, MarkdownEditor.this, action.equals("selectImage")) {
@Override
protected void onClose(AjaxRequestTarget target) {
close();
}
};
}
@Override
protected void onClosed() {
super.onClosed();
AjaxRequestTarget target =
Preconditions.checkNotNull(RequestCycle.get().find(AjaxRequestTarget.class));
target.appendJavaScript(String.format("$('#%s textarea').focus();", container.getMarkupId()));
}
};
break;
case "insertUrl":
String name;
try {
name = URLDecoder.decode(params.getParameterValue("param1").toString(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String replaceMessage = params.getParameterValue("param2").toString();
String url = getAttachmentSupport().getAttachmentUrl(name);
insertUrl(target, isWebSafeImage(name), url, name, replaceMessage);
break;
default:
throw new IllegalStateException("Unknown action: " + action);
}
}
});
container.add(attachmentUploadBehavior = new AbstractPostAjaxBehavior() {
@Override
protected void respond(AjaxRequestTarget target) {
Preconditions.checkNotNull(getAttachmentSupport(), "Unexpected attachment upload request");
HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
HttpServletResponse response = (HttpServletResponse) RequestCycle.get().getResponse().getContainerResponse();
try {
String fileName = URLDecoder.decode(request.getHeader("File-Name"), StandardCharsets.UTF_8.name());
String attachmentName = getAttachmentSupport().saveAttachment(fileName, request.getInputStream());
response.getWriter().print(URLEncoder.encode(attachmentName, StandardCharsets.UTF_8.name()));
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
logger.error("Error uploading attachment.", e);
try {
if (e.getMessage() != null)
response.getWriter().print(e.getMessage());
else
response.getWriter().print("Internal server error");
} catch (IOException e2) {
throw new RuntimeException(e2);
}
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
});
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
}
@Override
public void convertInput() {
setConvertedInput(input.getConvertedInput());
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forReference(new MarkdownResourceReference()));
String actionCallback = actionBehavior.getCallbackFunction(explicit("action"), explicit("param1"), explicit("param2"),
explicit("param3")).toString();
String attachmentUploadUrl = attachmentUploadBehavior.getCallbackUrl().toString();
String autosaveKey = getAutosaveKey();
if (autosaveKey != null)
autosaveKey = "'" + JavaScriptEscape.escapeJavaScript(autosaveKey) + "'";
else
autosaveKey = "undefined";
String script = String.format("onedev.server.markdown.onDomReady('%s', %s, %d, %s, %d, %b, %b, '%s', %s);",
container.getMarkupId(),
actionCallback,
ATWHO_LIMIT,
getAttachmentSupport()!=null? "'" + attachmentUploadUrl + "'": "undefined",
getAttachmentSupport()!=null? getAttachmentSupport().getAttachmentMaxSize(): 0,
getUserMentionSupport() != null,
getReferenceSupport() != null,
JavaScriptEscape.escapeJavaScript(ProjectNameValidator.PATTERN.pattern()),
autosaveKey);
response.render(OnDomReadyHeaderItem.forScript(script));
script = String.format("onedev.server.markdown.onLoad('%s');", container.getMarkupId());
response.render(OnLoadHeaderItem.forScript(script));
}
public void insertUrl(AjaxRequestTarget target, boolean isImage, String url,
String name, @Nullable String replaceMessage) {
String script = String.format("onedev.server.markdown.insertUrl('%s', %s, '%s', '%s', %s);",
container.getMarkupId(), isImage, StringEscapeUtils.escapeEcmaScript(url),
StringEscapeUtils.escapeEcmaScript(name),
replaceMessage!=null?"'"+replaceMessage+"'":"undefined");
target.appendJavaScript(script);
}
public boolean isWebSafeImage(String fileName) {
fileName = fileName.toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
|| fileName.endsWith(".gif") || fileName.endsWith(".png");
}
@Nullable
protected AttachmentSupport getAttachmentSupport() {
return null;
}
@Nullable
protected UserMentionSupport getUserMentionSupport() {
return null;
}
@Nullable
protected AtWhoReferenceSupport getReferenceSupport() {
return null;
}
protected List<AttributeModifier> getInputModifiers() {
return new ArrayList<>();
}
@Nullable
protected String getAutosaveKey() {
return null;
}
@Nullable
public BlobRenderContext getBlobRenderContext() {
return blobRenderContext;
}
static class ReferencedEntity implements Serializable {
String entityType;
String entityTitle;
String entityNumber;
String searchKey;
}
}
|
./CrossVul/dataset_final_sorted/CWE-434/java/bad_1896_2
|
crossvul-java_data_good_1896_1
|
package io.onedev.server.web.component.markdown;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Nullable;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.wicket.Component;
import org.apache.wicket.MetaDataKey;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.feedback.FencedFeedbackPanel;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.image.ExternalImage;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.lang.Bytes;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.unbescape.javascript.JavaScriptEscape;
import com.google.common.base.Preconditions;
import io.onedev.commons.utils.PathUtils;
import io.onedev.commons.utils.StringUtils;
import io.onedev.server.git.BlobIdent;
import io.onedev.server.git.BlobIdentFilter;
import io.onedev.server.git.exception.GitException;
import io.onedev.server.model.Project;
import io.onedev.server.util.FilenameUtils;
import io.onedev.server.util.UrlUtils;
import io.onedev.server.web.ajaxlistener.ConfirmClickListener;
import io.onedev.server.web.behavior.ReferenceInputBehavior;
import io.onedev.server.web.component.blob.folderpicker.BlobFolderPicker;
import io.onedev.server.web.component.blob.picker.BlobPicker;
import io.onedev.server.web.component.dropzonefield.DropzoneField;
import io.onedev.server.web.component.floating.FloatingPanel;
import io.onedev.server.web.component.link.DropdownLink;
import io.onedev.server.web.component.tabbable.AjaxActionTab;
import io.onedev.server.web.component.tabbable.Tab;
import io.onedev.server.web.component.tabbable.Tabbable;
import io.onedev.server.web.page.project.blob.ProjectBlobPage;
import io.onedev.server.web.page.project.blob.render.BlobRenderContext;
@SuppressWarnings("serial")
abstract class InsertUrlPanel extends Panel {
private static final MimetypesFileTypeMap MIME_TYPES = new MimetypesFileTypeMap();
private static final MetaDataKey<String> ACTIVE_TAB = new MetaDataKey<String>(){};
private static final MetaDataKey<String> UPLOAD_DIRECTORY = new MetaDataKey<String>(){};
private static final MetaDataKey<HashSet<String>> FILE_PICKER_STATE = new MetaDataKey<HashSet<String>>(){};
private static final MetaDataKey<HashSet<String>> FOLDER_PICKER_STATE = new MetaDataKey<HashSet<String>>(){};
static final String TAB_INPUT_URL = "Input URL";
static final String TAB_PICK_EXISTING = "Pick Existing";
static final String TAB_UPLOAD = "Upload";
private static final String CONTENT_ID = "content";
private Collection<FileUpload> uploads;
private String url;
private String text;
private String summaryCommitMessage;
private String detailCommitMessage;
private final MarkdownEditor markdownEditor;
private final boolean isImage;
public InsertUrlPanel(String id, MarkdownEditor markdownEditor, boolean isImage) {
super(id);
this.markdownEditor = markdownEditor;
this.isImage = isImage;
}
private Component newInputUrlPanel() {
Fragment fragment = new Fragment(CONTENT_ID, "inputUrlFrag", this) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.onInputUrlDomReady('%s');", getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
};
Form<?> form = new Form<Void>("form");
form.add(new FencedFeedbackPanel("feedback", form));
form.add(new Label("urlLabel", isImage?"Image URL":"Link URL"));
form.add(new Label("urlHelp", isImage?"Absolute or relative url of the image":"Absolute or relative url of the link"));
form.add(new TextField<String>("url", new PropertyModel<String>(this, "url")));
form.add(new Label("textLabel", isImage?"Image Text": "Link Text"));
form.add(new TextField<String>("text", new PropertyModel<String>(this, "text")));
form.add(new AjaxButton("insert", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
if (StringUtils.isBlank(url)) {
if (isImage)
error("Image URL should be specified");
else
error("Link URL should be specified");
target.add(fragment);
} else {
if (text == null)
text = UrlUtils.describe(url);
markdownEditor.insertUrl(target, isImage, url, text, null);
onClose(target);
}
}
});
fragment.add(form);
fragment.setOutputMarkupId(true);
return fragment;
}
private ObjectId resolveCommitId(BlobRenderContext context) {
/*
* We resolve revision to get latest commit id so that we can select to insert newly
* added/uploaded files while editing a markdown file
*/
String revision = context.getBlobIdent().revision;
if (revision == null)
revision = "master";
try {
return context.getProject().getRepository().resolve(revision);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Set<BlobIdent> getPickerState(@Nullable ObjectId commitId, BlobIdent currentBlobIdent,
@Nullable Set<String> expandedPaths) {
Set<BlobIdent> pickerState = new HashSet<>();
if (commitId != null) {
if (expandedPaths != null) {
for (String path: expandedPaths)
pickerState.add(new BlobIdent(commitId.name(), path, FileMode.TREE.getBits()));
}
String parentPath;
if (currentBlobIdent.isTree())
parentPath = currentBlobIdent.path;
else if (currentBlobIdent.path.contains("/"))
parentPath = StringUtils.substringBeforeLast(currentBlobIdent.path, "/");
else
parentPath = null;
while (parentPath != null) {
pickerState.add(new BlobIdent(commitId.name(), parentPath, FileMode.TYPE_TREE));
if (parentPath.contains("/"))
parentPath = StringUtils.substringBeforeLast(parentPath, "/");
else
parentPath = null;
}
}
return pickerState;
}
private Component newPickExistingPanel() {
Fragment fragment;
BlobRenderContext context = markdownEditor.getBlobRenderContext();
if (context != null) {
fragment = new Fragment(CONTENT_ID, "pickBlobFrag", this);
BlobIdentFilter blobIdentFilter = new BlobIdentFilter() {
@Override
public boolean filter(BlobIdent blobIdent) {
if (isImage) {
if (blobIdent.isTree()) {
return true;
} else {
String mimetype= MIME_TYPES.getContentType(new File(blobIdent.path));
return mimetype.split("/")[0].equals("image");
}
} else {
return true;
}
}
};
ObjectId commitId = resolveCommitId(context);
Set<BlobIdent> filePickerState = getPickerState(commitId, context.getBlobIdent(),
WebSession.get().getMetaData(FILE_PICKER_STATE));
fragment.add(new BlobPicker("files", commitId) {
@Override
protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {
blobIdent = new BlobIdent(context.getBlobIdent().revision, blobIdent.path, blobIdent.mode);
String baseUrl = context.getDirectoryUrl();
String referenceUrl = urlFor(ProjectBlobPage.class,
ProjectBlobPage.paramsOf(context.getProject(), blobIdent)).toString();
String relativized = PathUtils.relativize(baseUrl, referenceUrl);
markdownEditor.insertUrl(target, isImage, relativized, UrlUtils.describe(blobIdent.getName()), null);
onClose(target);
}
@Override
protected BlobIdentFilter getBlobIdentFilter() {
return blobIdentFilter;
}
@Override
protected Project getProject() {
return markdownEditor.getBlobRenderContext().getProject();
}
@Override
protected void onStateChange() {
HashSet<String> expandedPaths = new HashSet<>();
for (BlobIdent blobIdent: filePickerState)
expandedPaths.add(blobIdent.path);
WebSession.get().setMetaData(FILE_PICKER_STATE, expandedPaths);
}
@Override
protected Set<BlobIdent> getState() {
return filePickerState;
}
});
} else {
AttachmentSupport attachmentSupport = Preconditions.checkNotNull(markdownEditor.getAttachmentSupport());
if (isImage) {
fragment = new Fragment(CONTENT_ID, "pickAttachedImageFrag", this);
fragment.add(new ListView<String>("attachments", new LoadableDetachableModel<List<String>>() {
@Override
protected List<String> load() {
List<String> attachmentNames = new ArrayList<>();
for (String attachmentName: attachmentSupport.getAttachments()) {
if (markdownEditor.isWebSafeImage(attachmentName))
attachmentNames.add(attachmentName);
}
return attachmentNames;
}
}) {
@Override
protected void populateItem(final ListItem<String> item) {
String attachmentName = item.getModelObject();
String attachmentUrl = attachmentSupport.getAttachmentUrl(attachmentName);
AjaxLink<Void> selectLink = new AjaxLink<Void>("select") {
@Override
public void onClick(AjaxRequestTarget target) {
String displayName = UrlUtils.describe(attachmentName);
markdownEditor.insertUrl(target, true, attachmentUrl, displayName, null);
onClose(target);
}
};
selectLink.add(new ExternalImage("image", StringEscapeUtils.escapeHtml4(attachmentUrl)));
item.add(selectLink);
item.add(new AjaxLink<Void>("delete") {
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new ConfirmClickListener("Do you really want to delete '" + attachmentName + "'?"));
}
@Override
protected void onConfigure() {
super.onConfigure();
setVisible(attachmentSupport.canDeleteAttachment());
}
@Override
public void onClick(AjaxRequestTarget target) {
attachmentSupport.deleteAttachemnt(attachmentName);
target.add(fragment);
}
});
}
});
} else {
fragment = new Fragment(CONTENT_ID, "pickAttachedFileFrag", this);
fragment.add(new ListView<String>("attachments", new LoadableDetachableModel<List<String>>() {
@Override
protected List<String> load() {
return attachmentSupport.getAttachments();
}
}) {
@Override
protected void populateItem(final ListItem<String> item) {
String attachmentName = item.getModelObject();
String attachmentUrl = attachmentSupport.getAttachmentUrl(attachmentName);
AjaxLink<Void> selectLink = new AjaxLink<Void>("select") {
@Override
public void onClick(AjaxRequestTarget target) {
String displayName = UrlUtils.describe(attachmentName);
markdownEditor.insertUrl(target, false, attachmentUrl, displayName, null);
onClose(target);
}
};
selectLink.add(new Label("file", StringEscapeUtils.escapeHtml4(attachmentName)));
item.add(selectLink);
item.add(new AjaxLink<Void>("delete") {
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new ConfirmClickListener("Do you really want to delete '" + attachmentName + "'?"));
}
@Override
public void onClick(AjaxRequestTarget target) {
attachmentSupport.deleteAttachemnt(attachmentName);
target.add(fragment);
}
});
}
});
}
}
fragment.setOutputMarkupId(true);
return fragment;
}
private Component newUploadPanel() {
Fragment fragment;
IModel<Collection<FileUpload>> model = new PropertyModel<Collection<FileUpload>>(this, "uploads");
String acceptedFiles;
if (isImage)
acceptedFiles = "image/*";
else
acceptedFiles = null;
AttachmentSupport attachmentSupport = markdownEditor.getAttachmentSupport();
if (attachmentSupport != null) {
fragment = new Fragment(CONTENT_ID, "uploadAttachmentFrag", this);
Form<?> form = new Form<Void>("form") {
@Override
protected void onSubmit() {
super.onSubmit();
AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class);
String attachmentName;
FileUpload upload = uploads.iterator().next();
try (InputStream is = upload.getInputStream()) {
attachmentName = attachmentSupport.saveAttachment(
FilenameUtils.sanitizeFilename(upload.getClientFileName()), is);
} catch (IOException e) {
throw new RuntimeException(e);
}
markdownEditor.insertUrl(target, isImage,
attachmentSupport.getAttachmentUrl(attachmentName), UrlUtils.describe(attachmentName), null);
onClose(target);
}
@Override
protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
throw new RuntimeException(e);
}
};
form.setMaxSize(Bytes.bytes(attachmentSupport.getAttachmentMaxSize()));
form.setMultiPart(true);
form.add(new FencedFeedbackPanel("feedback", form));
int maxFilesize = (int) (attachmentSupport.getAttachmentMaxSize()/1024/1024);
if (maxFilesize <= 0)
maxFilesize = 1;
form.add(new DropzoneField("file", model, acceptedFiles, 1, maxFilesize)
.setRequired(true).setLabel(Model.of("Attachment")));
form.add(new AjaxButton("insert"){});
fragment.add(form);
} else {
fragment = new Fragment(CONTENT_ID, "uploadBlobFrag", this);
Form<?> form = new Form<Void>("form");
form.setMultiPart(true);
form.setFileMaxSize(Bytes.megabytes(Project.MAX_UPLOAD_SIZE));
add(form);
FencedFeedbackPanel feedback = new FencedFeedbackPanel("feedback", form);
feedback.setOutputMarkupPlaceholderTag(true);
form.add(feedback);
form.add(new DropzoneField("file", model, acceptedFiles, 1, Project.MAX_UPLOAD_SIZE)
.setRequired(true).setLabel(Model.of("Attachment")));
form.add(new TextField<String>("directory", new IModel<String>() {
@Override
public void detach() {
}
@Override
public String getObject() {
return WebSession.get().getMetaData(UPLOAD_DIRECTORY);
}
@Override
public void setObject(String object) {
WebSession.get().setMetaData(UPLOAD_DIRECTORY, object);
}
}));
BlobRenderContext context = Preconditions.checkNotNull(markdownEditor.getBlobRenderContext());
ObjectId commitId = resolveCommitId(context);
Set<BlobIdent> folderPickerState = getPickerState(commitId, context.getBlobIdent(),
WebSession.get().getMetaData(FOLDER_PICKER_STATE));
form.add(new DropdownLink("select") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new BlobFolderPicker(id, commitId) {
@Override
protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {
dropdown.close();
String relativePath = PathUtils.relativize(context.getDirectory(), blobIdent.path);
String script = String.format("$('form.upload-blob .directory input').val('%s');",
JavaScriptEscape.escapeJavaScript(relativePath));
target.appendJavaScript(script);
}
@Override
protected Project getProject() {
return markdownEditor.getBlobRenderContext().getProject();
}
@Override
protected void onStateChange() {
HashSet<String> expandedPaths = new HashSet<>();
for (BlobIdent blobIdent: folderPickerState)
expandedPaths.add(blobIdent.path);
WebSession.get().setMetaData(FOLDER_PICKER_STATE, expandedPaths);
}
@Override
protected Set<BlobIdent> getState() {
return folderPickerState;
}
};
}
});
ReferenceInputBehavior behavior = new ReferenceInputBehavior(true) {
@Override
protected Project getProject() {
return markdownEditor.getBlobRenderContext().getProject();
}
};
form.add(new TextField<String>("summaryCommitMessage",
new PropertyModel<String>(this, "summaryCommitMessage")).add(behavior));
behavior = new ReferenceInputBehavior(true) {
@Override
protected Project getProject() {
return markdownEditor.getBlobRenderContext().getProject();
}
};
form.add(new TextArea<String>("detailCommitMessage",
new PropertyModel<String>(this, "detailCommitMessage")).add(behavior));
form.add(new AjaxButton("insert") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
BlobRenderContext context = Preconditions.checkNotNull(markdownEditor.getBlobRenderContext());
String commitMessage = summaryCommitMessage;
if (StringUtils.isBlank(commitMessage))
commitMessage = "Add files via upload";
if (StringUtils.isNotBlank(detailCommitMessage))
commitMessage += "\n\n" + detailCommitMessage;
try {
String directory = WebSession.get().getMetaData(UPLOAD_DIRECTORY);
context.onCommitted(null, context.uploadFiles(uploads, directory, commitMessage), null);
String fileName = uploads.iterator().next().getClientFileName();
String url;
if (directory != null)
url = directory + "/" + UrlUtils.encodePath(fileName);
else
url = UrlUtils.encodePath(fileName);
markdownEditor.insertUrl(target, isImage, url, UrlUtils.describe(fileName), null);
onClose(target);
} catch (GitException e) {
form.error(e.getMessage());
target.add(feedback);
}
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
super.onError(target, form);
target.add(feedback);
}
});
fragment.add(form);
}
fragment.setOutputMarkupId(true);
return fragment;
}
@Override
protected void onInitialize() {
super.onInitialize();
add(new Label("title", isImage?"Insert Image":"Insert Link"));
if (markdownEditor.getBlobRenderContext() == null && markdownEditor.getAttachmentSupport() == null) {
add(newInputUrlPanel());
} else {
Fragment fragment = new Fragment(CONTENT_ID, "tabbedFrag", this);
List<Tab> tabs = new ArrayList<>();
AjaxActionTab inputUrlTab = new AjaxActionTab(Model.of(TAB_INPUT_URL)) {
@Override
protected void onSelect(AjaxRequestTarget target, Component tabLink) {
Component content = newInputUrlPanel();
target.add(content);
fragment.replace(content);
WebSession.get().setMetaData(ACTIVE_TAB, TAB_INPUT_URL);
}
};
tabs.add(inputUrlTab);
AjaxActionTab pickExistingTab = new AjaxActionTab(Model.of(TAB_PICK_EXISTING)) {
@Override
protected void onSelect(AjaxRequestTarget target, Component tabLink) {
Component content = newPickExistingPanel();
target.add(content);
fragment.replace(content);
WebSession.get().setMetaData(ACTIVE_TAB, TAB_PICK_EXISTING);
}
};
tabs.add(pickExistingTab);
AjaxActionTab uploadTab = new AjaxActionTab(Model.of(TAB_UPLOAD)) {
@Override
protected void onSelect(AjaxRequestTarget target, Component tabLink) {
Component content = newUploadPanel();
target.add(content);
fragment.replace(content);
WebSession.get().setMetaData(ACTIVE_TAB, TAB_UPLOAD);
}
};
tabs.add(uploadTab);
fragment.add(new Tabbable("tabs", tabs));
inputUrlTab.setSelected(false);
String activeTab = WebSession.get().getMetaData(ACTIVE_TAB);
if (TAB_PICK_EXISTING.equals(activeTab)) {
pickExistingTab.setSelected(true);
fragment.add(newPickExistingPanel());
} else if (TAB_UPLOAD.equals(activeTab)) {
uploadTab.setSelected(true);
fragment.add(newUploadPanel());
} else {
inputUrlTab.setSelected(true);
fragment.add(newInputUrlPanel());
}
add(fragment);
}
add(new AjaxLink<Void>("close") {
@Override
public void onClick(AjaxRequestTarget target) {
onClose(target);
}
});
}
protected abstract void onClose(AjaxRequestTarget target);
}
|
./CrossVul/dataset_final_sorted/CWE-434/java/good_1896_1
|
crossvul-java_data_good_1896_0
|
package io.onedev.server.util;
public class FilenameUtils extends org.apache.commons.io.FilenameUtils {
public static String sanitizeFilename(String fileName) {
return fileName.replace("..", "_").replace('/', '_').replace('\\', '_');
}
}
|
./CrossVul/dataset_final_sorted/CWE-434/java/good_1896_0
|
crossvul-java_data_bad_1896_3
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-434/java/bad_1896_3
|
crossvul-java_data_bad_1896_0
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-434/java/bad_1896_0
|
crossvul-java_data_bad_1896_1
|
package io.onedev.server.web.component.markdown;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Nullable;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.wicket.Component;
import org.apache.wicket.MetaDataKey;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.feedback.FencedFeedbackPanel;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.image.ExternalImage;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.lang.Bytes;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.unbescape.javascript.JavaScriptEscape;
import com.google.common.base.Preconditions;
import io.onedev.commons.utils.PathUtils;
import io.onedev.commons.utils.StringUtils;
import io.onedev.server.git.BlobIdent;
import io.onedev.server.git.BlobIdentFilter;
import io.onedev.server.git.exception.GitException;
import io.onedev.server.model.Project;
import io.onedev.server.util.UrlUtils;
import io.onedev.server.web.ajaxlistener.ConfirmClickListener;
import io.onedev.server.web.behavior.ReferenceInputBehavior;
import io.onedev.server.web.component.blob.folderpicker.BlobFolderPicker;
import io.onedev.server.web.component.blob.picker.BlobPicker;
import io.onedev.server.web.component.dropzonefield.DropzoneField;
import io.onedev.server.web.component.floating.FloatingPanel;
import io.onedev.server.web.component.link.DropdownLink;
import io.onedev.server.web.component.tabbable.AjaxActionTab;
import io.onedev.server.web.component.tabbable.Tab;
import io.onedev.server.web.component.tabbable.Tabbable;
import io.onedev.server.web.page.project.blob.ProjectBlobPage;
import io.onedev.server.web.page.project.blob.render.BlobRenderContext;
@SuppressWarnings("serial")
abstract class InsertUrlPanel extends Panel {
private static final MimetypesFileTypeMap MIME_TYPES = new MimetypesFileTypeMap();
private static final MetaDataKey<String> ACTIVE_TAB = new MetaDataKey<String>(){};
private static final MetaDataKey<String> UPLOAD_DIRECTORY = new MetaDataKey<String>(){};
private static final MetaDataKey<HashSet<String>> FILE_PICKER_STATE = new MetaDataKey<HashSet<String>>(){};
private static final MetaDataKey<HashSet<String>> FOLDER_PICKER_STATE = new MetaDataKey<HashSet<String>>(){};
static final String TAB_INPUT_URL = "Input URL";
static final String TAB_PICK_EXISTING = "Pick Existing";
static final String TAB_UPLOAD = "Upload";
private static final String CONTENT_ID = "content";
private Collection<FileUpload> uploads;
private String url;
private String text;
private String summaryCommitMessage;
private String detailCommitMessage;
private final MarkdownEditor markdownEditor;
private final boolean isImage;
public InsertUrlPanel(String id, MarkdownEditor markdownEditor, boolean isImage) {
super(id);
this.markdownEditor = markdownEditor;
this.isImage = isImage;
}
private Component newInputUrlPanel() {
Fragment fragment = new Fragment(CONTENT_ID, "inputUrlFrag", this) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.onInputUrlDomReady('%s');", getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
};
Form<?> form = new Form<Void>("form");
form.add(new FencedFeedbackPanel("feedback", form));
form.add(new Label("urlLabel", isImage?"Image URL":"Link URL"));
form.add(new Label("urlHelp", isImage?"Absolute or relative url of the image":"Absolute or relative url of the link"));
form.add(new TextField<String>("url", new PropertyModel<String>(this, "url")));
form.add(new Label("textLabel", isImage?"Image Text": "Link Text"));
form.add(new TextField<String>("text", new PropertyModel<String>(this, "text")));
form.add(new AjaxButton("insert", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
if (StringUtils.isBlank(url)) {
if (isImage)
error("Image URL should be specified");
else
error("Link URL should be specified");
target.add(fragment);
} else {
if (text == null)
text = UrlUtils.describe(url);
markdownEditor.insertUrl(target, isImage, url, text, null);
onClose(target);
}
}
});
fragment.add(form);
fragment.setOutputMarkupId(true);
return fragment;
}
private ObjectId resolveCommitId(BlobRenderContext context) {
/*
* We resolve revision to get latest commit id so that we can select to insert newly
* added/uploaded files while editing a markdown file
*/
String revision = context.getBlobIdent().revision;
if (revision == null)
revision = "master";
try {
return context.getProject().getRepository().resolve(revision);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Set<BlobIdent> getPickerState(@Nullable ObjectId commitId, BlobIdent currentBlobIdent,
@Nullable Set<String> expandedPaths) {
Set<BlobIdent> pickerState = new HashSet<>();
if (commitId != null) {
if (expandedPaths != null) {
for (String path: expandedPaths)
pickerState.add(new BlobIdent(commitId.name(), path, FileMode.TREE.getBits()));
}
String parentPath;
if (currentBlobIdent.isTree())
parentPath = currentBlobIdent.path;
else if (currentBlobIdent.path.contains("/"))
parentPath = StringUtils.substringBeforeLast(currentBlobIdent.path, "/");
else
parentPath = null;
while (parentPath != null) {
pickerState.add(new BlobIdent(commitId.name(), parentPath, FileMode.TYPE_TREE));
if (parentPath.contains("/"))
parentPath = StringUtils.substringBeforeLast(parentPath, "/");
else
parentPath = null;
}
}
return pickerState;
}
private Component newPickExistingPanel() {
Fragment fragment;
BlobRenderContext context = markdownEditor.getBlobRenderContext();
if (context != null) {
fragment = new Fragment(CONTENT_ID, "pickBlobFrag", this);
BlobIdentFilter blobIdentFilter = new BlobIdentFilter() {
@Override
public boolean filter(BlobIdent blobIdent) {
if (isImage) {
if (blobIdent.isTree()) {
return true;
} else {
String mimetype= MIME_TYPES.getContentType(new File(blobIdent.path));
return mimetype.split("/")[0].equals("image");
}
} else {
return true;
}
}
};
ObjectId commitId = resolveCommitId(context);
Set<BlobIdent> filePickerState = getPickerState(commitId, context.getBlobIdent(),
WebSession.get().getMetaData(FILE_PICKER_STATE));
fragment.add(new BlobPicker("files", commitId) {
@Override
protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {
blobIdent = new BlobIdent(context.getBlobIdent().revision, blobIdent.path, blobIdent.mode);
String baseUrl = context.getDirectoryUrl();
String referenceUrl = urlFor(ProjectBlobPage.class,
ProjectBlobPage.paramsOf(context.getProject(), blobIdent)).toString();
String relativized = PathUtils.relativize(baseUrl, referenceUrl);
markdownEditor.insertUrl(target, isImage, relativized, UrlUtils.describe(blobIdent.getName()), null);
onClose(target);
}
@Override
protected BlobIdentFilter getBlobIdentFilter() {
return blobIdentFilter;
}
@Override
protected Project getProject() {
return markdownEditor.getBlobRenderContext().getProject();
}
@Override
protected void onStateChange() {
HashSet<String> expandedPaths = new HashSet<>();
for (BlobIdent blobIdent: filePickerState)
expandedPaths.add(blobIdent.path);
WebSession.get().setMetaData(FILE_PICKER_STATE, expandedPaths);
}
@Override
protected Set<BlobIdent> getState() {
return filePickerState;
}
});
} else {
AttachmentSupport attachmentSupport = Preconditions.checkNotNull(markdownEditor.getAttachmentSupport());
if (isImage) {
fragment = new Fragment(CONTENT_ID, "pickAttachedImageFrag", this);
fragment.add(new ListView<String>("attachments", new LoadableDetachableModel<List<String>>() {
@Override
protected List<String> load() {
List<String> attachmentNames = new ArrayList<>();
for (String attachmentName: attachmentSupport.getAttachments()) {
if (markdownEditor.isWebSafeImage(attachmentName))
attachmentNames.add(attachmentName);
}
return attachmentNames;
}
}) {
@Override
protected void populateItem(final ListItem<String> item) {
String attachmentName = item.getModelObject();
String attachmentUrl = attachmentSupport.getAttachmentUrl(attachmentName);
AjaxLink<Void> selectLink = new AjaxLink<Void>("select") {
@Override
public void onClick(AjaxRequestTarget target) {
String displayName = UrlUtils.describe(attachmentName);
markdownEditor.insertUrl(target, true, attachmentUrl, displayName, null);
onClose(target);
}
};
selectLink.add(new ExternalImage("image", StringEscapeUtils.escapeHtml4(attachmentUrl)));
item.add(selectLink);
item.add(new AjaxLink<Void>("delete") {
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new ConfirmClickListener("Do you really want to delete '" + attachmentName + "'?"));
}
@Override
protected void onConfigure() {
super.onConfigure();
setVisible(attachmentSupport.canDeleteAttachment());
}
@Override
public void onClick(AjaxRequestTarget target) {
attachmentSupport.deleteAttachemnt(attachmentName);
target.add(fragment);
}
});
}
});
} else {
fragment = new Fragment(CONTENT_ID, "pickAttachedFileFrag", this);
fragment.add(new ListView<String>("attachments", new LoadableDetachableModel<List<String>>() {
@Override
protected List<String> load() {
return attachmentSupport.getAttachments();
}
}) {
@Override
protected void populateItem(final ListItem<String> item) {
String attachmentName = item.getModelObject();
String attachmentUrl = attachmentSupport.getAttachmentUrl(attachmentName);
AjaxLink<Void> selectLink = new AjaxLink<Void>("select") {
@Override
public void onClick(AjaxRequestTarget target) {
String displayName = UrlUtils.describe(attachmentName);
markdownEditor.insertUrl(target, false, attachmentUrl, displayName, null);
onClose(target);
}
};
selectLink.add(new Label("file", StringEscapeUtils.escapeHtml4(attachmentName)));
item.add(selectLink);
item.add(new AjaxLink<Void>("delete") {
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new ConfirmClickListener("Do you really want to delete '" + attachmentName + "'?"));
}
@Override
public void onClick(AjaxRequestTarget target) {
attachmentSupport.deleteAttachemnt(attachmentName);
target.add(fragment);
}
});
}
});
}
}
fragment.setOutputMarkupId(true);
return fragment;
}
private Component newUploadPanel() {
Fragment fragment;
IModel<Collection<FileUpload>> model = new PropertyModel<Collection<FileUpload>>(this, "uploads");
String acceptedFiles;
if (isImage)
acceptedFiles = "image/*";
else
acceptedFiles = null;
AttachmentSupport attachmentSupport = markdownEditor.getAttachmentSupport();
if (attachmentSupport != null) {
fragment = new Fragment(CONTENT_ID, "uploadAttachmentFrag", this);
Form<?> form = new Form<Void>("form") {
@Override
protected void onSubmit() {
super.onSubmit();
AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class);
String attachmentName;
FileUpload upload = uploads.iterator().next();
try (InputStream is = upload.getInputStream()) {
attachmentName = attachmentSupport.saveAttachment(upload.getClientFileName(), is);
} catch (IOException e) {
throw new RuntimeException(e);
}
markdownEditor.insertUrl(target, isImage,
attachmentSupport.getAttachmentUrl(attachmentName), UrlUtils.describe(attachmentName), null);
onClose(target);
}
@Override
protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
throw new RuntimeException(e);
}
};
form.setMaxSize(Bytes.bytes(attachmentSupport.getAttachmentMaxSize()));
form.setMultiPart(true);
form.add(new FencedFeedbackPanel("feedback", form));
int maxFilesize = (int) (attachmentSupport.getAttachmentMaxSize()/1024/1024);
if (maxFilesize <= 0)
maxFilesize = 1;
form.add(new DropzoneField("file", model, acceptedFiles, 1, maxFilesize)
.setRequired(true).setLabel(Model.of("Attachment")));
form.add(new AjaxButton("insert"){});
fragment.add(form);
} else {
fragment = new Fragment(CONTENT_ID, "uploadBlobFrag", this);
Form<?> form = new Form<Void>("form");
form.setMultiPart(true);
form.setFileMaxSize(Bytes.megabytes(Project.MAX_UPLOAD_SIZE));
add(form);
FencedFeedbackPanel feedback = new FencedFeedbackPanel("feedback", form);
feedback.setOutputMarkupPlaceholderTag(true);
form.add(feedback);
form.add(new DropzoneField("file", model, acceptedFiles, 1, Project.MAX_UPLOAD_SIZE)
.setRequired(true).setLabel(Model.of("Attachment")));
form.add(new TextField<String>("directory", new IModel<String>() {
@Override
public void detach() {
}
@Override
public String getObject() {
return WebSession.get().getMetaData(UPLOAD_DIRECTORY);
}
@Override
public void setObject(String object) {
WebSession.get().setMetaData(UPLOAD_DIRECTORY, object);
}
}));
BlobRenderContext context = Preconditions.checkNotNull(markdownEditor.getBlobRenderContext());
ObjectId commitId = resolveCommitId(context);
Set<BlobIdent> folderPickerState = getPickerState(commitId, context.getBlobIdent(),
WebSession.get().getMetaData(FOLDER_PICKER_STATE));
form.add(new DropdownLink("select") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new BlobFolderPicker(id, commitId) {
@Override
protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {
dropdown.close();
String relativePath = PathUtils.relativize(context.getDirectory(), blobIdent.path);
String script = String.format("$('form.upload-blob .directory input').val('%s');",
JavaScriptEscape.escapeJavaScript(relativePath));
target.appendJavaScript(script);
}
@Override
protected Project getProject() {
return markdownEditor.getBlobRenderContext().getProject();
}
@Override
protected void onStateChange() {
HashSet<String> expandedPaths = new HashSet<>();
for (BlobIdent blobIdent: folderPickerState)
expandedPaths.add(blobIdent.path);
WebSession.get().setMetaData(FOLDER_PICKER_STATE, expandedPaths);
}
@Override
protected Set<BlobIdent> getState() {
return folderPickerState;
}
};
}
});
ReferenceInputBehavior behavior = new ReferenceInputBehavior(true) {
@Override
protected Project getProject() {
return markdownEditor.getBlobRenderContext().getProject();
}
};
form.add(new TextField<String>("summaryCommitMessage",
new PropertyModel<String>(this, "summaryCommitMessage")).add(behavior));
behavior = new ReferenceInputBehavior(true) {
@Override
protected Project getProject() {
return markdownEditor.getBlobRenderContext().getProject();
}
};
form.add(new TextArea<String>("detailCommitMessage",
new PropertyModel<String>(this, "detailCommitMessage")).add(behavior));
form.add(new AjaxButton("insert") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
BlobRenderContext context = Preconditions.checkNotNull(markdownEditor.getBlobRenderContext());
String commitMessage = summaryCommitMessage;
if (StringUtils.isBlank(commitMessage))
commitMessage = "Add files via upload";
if (StringUtils.isNotBlank(detailCommitMessage))
commitMessage += "\n\n" + detailCommitMessage;
try {
String directory = WebSession.get().getMetaData(UPLOAD_DIRECTORY);
context.onCommitted(null, context.uploadFiles(uploads, directory, commitMessage), null);
String fileName = uploads.iterator().next().getClientFileName();
String url;
if (directory != null)
url = directory + "/" + UrlUtils.encodePath(fileName);
else
url = UrlUtils.encodePath(fileName);
markdownEditor.insertUrl(target, isImage, url, UrlUtils.describe(fileName), null);
onClose(target);
} catch (GitException e) {
form.error(e.getMessage());
target.add(feedback);
}
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
super.onError(target, form);
target.add(feedback);
}
});
fragment.add(form);
}
fragment.setOutputMarkupId(true);
return fragment;
}
@Override
protected void onInitialize() {
super.onInitialize();
add(new Label("title", isImage?"Insert Image":"Insert Link"));
if (markdownEditor.getBlobRenderContext() == null && markdownEditor.getAttachmentSupport() == null) {
add(newInputUrlPanel());
} else {
Fragment fragment = new Fragment(CONTENT_ID, "tabbedFrag", this);
List<Tab> tabs = new ArrayList<>();
AjaxActionTab inputUrlTab = new AjaxActionTab(Model.of(TAB_INPUT_URL)) {
@Override
protected void onSelect(AjaxRequestTarget target, Component tabLink) {
Component content = newInputUrlPanel();
target.add(content);
fragment.replace(content);
WebSession.get().setMetaData(ACTIVE_TAB, TAB_INPUT_URL);
}
};
tabs.add(inputUrlTab);
AjaxActionTab pickExistingTab = new AjaxActionTab(Model.of(TAB_PICK_EXISTING)) {
@Override
protected void onSelect(AjaxRequestTarget target, Component tabLink) {
Component content = newPickExistingPanel();
target.add(content);
fragment.replace(content);
WebSession.get().setMetaData(ACTIVE_TAB, TAB_PICK_EXISTING);
}
};
tabs.add(pickExistingTab);
AjaxActionTab uploadTab = new AjaxActionTab(Model.of(TAB_UPLOAD)) {
@Override
protected void onSelect(AjaxRequestTarget target, Component tabLink) {
Component content = newUploadPanel();
target.add(content);
fragment.replace(content);
WebSession.get().setMetaData(ACTIVE_TAB, TAB_UPLOAD);
}
};
tabs.add(uploadTab);
fragment.add(new Tabbable("tabs", tabs));
inputUrlTab.setSelected(false);
String activeTab = WebSession.get().getMetaData(ACTIVE_TAB);
if (TAB_PICK_EXISTING.equals(activeTab)) {
pickExistingTab.setSelected(true);
fragment.add(newPickExistingPanel());
} else if (TAB_UPLOAD.equals(activeTab)) {
uploadTab.setSelected(true);
fragment.add(newUploadPanel());
} else {
inputUrlTab.setSelected(true);
fragment.add(newInputUrlPanel());
}
add(fragment);
}
add(new AjaxLink<Void>("close") {
@Override
public void onClick(AjaxRequestTarget target) {
onClose(target);
}
});
}
protected abstract void onClose(AjaxRequestTarget target);
}
|
./CrossVul/dataset_final_sorted/CWE-434/java/bad_1896_1
|
crossvul-java_data_good_1896_3
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-434/java/good_1896_3
|
crossvul-java_data_good_1896_2
|
package io.onedev.server.web.component.markdown;
import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxChannel;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.FormComponentPanel;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unbescape.javascript.JavaScriptEscape;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import io.onedev.commons.launcher.loader.AppLoader;
import io.onedev.server.OneDev;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.model.Build;
import io.onedev.server.model.Issue;
import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.User;
import io.onedev.server.util.FilenameUtils;
import io.onedev.server.util.markdown.MarkdownManager;
import io.onedev.server.util.validation.ProjectNameValidator;
import io.onedev.server.web.avatar.AvatarManager;
import io.onedev.server.web.behavior.AbstractPostAjaxBehavior;
import io.onedev.server.web.component.floating.FloatingPanel;
import io.onedev.server.web.component.link.DropdownLink;
import io.onedev.server.web.component.markdown.emoji.EmojiOnes;
import io.onedev.server.web.component.modal.ModalPanel;
import io.onedev.server.web.page.project.ProjectPage;
import io.onedev.server.web.page.project.blob.render.BlobRenderContext;
@SuppressWarnings("serial")
public class MarkdownEditor extends FormComponentPanel<String> {
protected static final int ATWHO_LIMIT = 10;
private static final Logger logger = LoggerFactory.getLogger(MarkdownEditor.class);
private final boolean compactMode;
private final boolean initialSplit;
private final BlobRenderContext blobRenderContext;
private WebMarkupContainer container;
private TextArea<String> input;
private AbstractPostAjaxBehavior actionBehavior;
private AbstractPostAjaxBehavior attachmentUploadBehavior;
/**
* @param id
* component id of the editor
* @param model
* markdown model of the editor
* @param compactMode
* editor in compact mode occupies horizontal space and is suitable
* to be used in places such as comment aside the code
*/
public MarkdownEditor(String id, IModel<String> model, boolean compactMode,
@Nullable BlobRenderContext blobRenderContext) {
super(id, model);
this.compactMode = compactMode;
String cookieKey;
if (compactMode)
cookieKey = "markdownEditor.compactMode.split";
else
cookieKey = "markdownEditor.normalMode.split";
WebRequest request = (WebRequest) RequestCycle.get().getRequest();
Cookie cookie = request.getCookie(cookieKey);
initialSplit = cookie!=null && "true".equals(cookie.getValue());
this.blobRenderContext = blobRenderContext;
}
@Override
protected void onModelChanged() {
super.onModelChanged();
input.setModelObject(getModelObject());
}
public void clearMarkdown() {
setModelObject("");
input.setConvertedInput(null);
}
private String renderInput(String input) {
if (StringUtils.isNotBlank(input)) {
// Normalize line breaks to make source position tracking information comparable
// to textarea caret position when sync edit/preview scroll bar
input = StringUtils.replace(input, "\r\n", "\n");
return renderMarkdown(input);
} else {
return "<div class='message'>Nothing to preview</div>";
}
}
protected String renderMarkdown(String markdown) {
Project project ;
if (getPage() instanceof ProjectPage)
project = ((ProjectPage) getPage()).getProject();
else
project = null;
MarkdownManager manager = OneDev.getInstance(MarkdownManager.class);
return manager.process(manager.render(markdown), project, blobRenderContext);
}
@Override
protected void onInitialize() {
super.onInitialize();
container = new WebMarkupContainer("container");
container.setOutputMarkupId(true);
add(container);
WebMarkupContainer editLink = new WebMarkupContainer("editLink");
WebMarkupContainer splitLink = new WebMarkupContainer("splitLink");
WebMarkupContainer preview = new WebMarkupContainer("preview");
WebMarkupContainer edit = new WebMarkupContainer("edit");
container.add(editLink);
container.add(splitLink);
container.add(preview);
container.add(edit);
container.add(AttributeAppender.append("class", compactMode?"compact-mode":"normal-mode"));
container.add(new DropdownLink("doReference") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new Fragment(id, "referenceMenuFrag", MarkdownEditor.this) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.setupActionMenu($('#%s'), $('#%s'));",
container.getMarkupId(), getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setOutputMarkupId(true);
}
}.setVisible(getReferenceSupport() != null));
container.add(new DropdownLink("actionMenuTrigger") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new Fragment(id, "actionMenuFrag", MarkdownEditor.this) {
@Override
protected void onInitialize() {
super.onInitialize();
add(new WebMarkupContainer("doMention").setVisible(getUserMentionSupport() != null));
if (getReferenceSupport() != null)
add(new Fragment("doReference", "referenceMenuFrag", MarkdownEditor.this));
else
add(new WebMarkupContainer("doReference").setVisible(false));
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.setupActionMenu($('#%s'), $('#%s'));",
container.getMarkupId(), getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setOutputMarkupId(true);
}
});
container.add(new WebMarkupContainer("doMention").setVisible(getUserMentionSupport() != null));
edit.add(input = new TextArea<String>("input", Model.of(getModelObject())));
for (AttributeModifier modifier: getInputModifiers())
input.add(modifier);
if (initialSplit) {
container.add(AttributeAppender.append("class", "split-mode"));
preview.add(new Label("rendered", new LoadableDetachableModel<String>() {
@Override
protected String load() {
return renderInput(input.getConvertedInput());
}
}) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format(
"onedev.server.markdown.initRendered($('#%s>.body>.preview>.markdown-rendered'));",
container.getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setEscapeModelStrings(false));
splitLink.add(AttributeAppender.append("class", "active"));
} else {
container.add(AttributeAppender.append("class", "edit-mode"));
preview.add(new WebMarkupContainer("rendered"));
editLink.add(AttributeAppender.append("class", "active"));
}
container.add(new WebMarkupContainer("canAttachFile").setVisible(getAttachmentSupport()!=null));
container.add(actionBehavior = new AbstractPostAjaxBehavior() {
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.setChannel(new AjaxChannel("markdown-preview", AjaxChannel.Type.DROP));
}
@Override
protected void respond(AjaxRequestTarget target) {
IRequestParameters params = RequestCycle.get().getRequest().getPostParameters();
String action = params.getParameterValue("action").toString("");
switch (action) {
case "render":
String markdown = params.getParameterValue("param1").toString();
String rendered = renderInput(markdown);
String script = String.format("onedev.server.markdown.onRendered('%s', '%s');",
container.getMarkupId(), JavaScriptEscape.escapeJavaScript(rendered));
target.appendJavaScript(script);
break;
case "emojiQuery":
List<String> emojiNames = new ArrayList<>();
String emojiQuery = params.getParameterValue("param1").toOptionalString();
if (StringUtils.isNotBlank(emojiQuery)) {
emojiQuery = emojiQuery.toLowerCase();
for (String emojiName: EmojiOnes.getInstance().all().keySet()) {
if (emojiName.toLowerCase().contains(emojiQuery))
emojiNames.add(emojiName);
}
emojiNames.sort((name1, name2) -> name1.length() - name2.length());
} else {
emojiNames.add("smile");
emojiNames.add("worried");
emojiNames.add("blush");
emojiNames.add("+1");
emojiNames.add("-1");
}
List<Map<String, String>> emojis = new ArrayList<>();
for (String emojiName: emojiNames) {
if (emojis.size() < ATWHO_LIMIT) {
String emojiCode = EmojiOnes.getInstance().all().get(emojiName);
CharSequence url = RequestCycle.get().urlFor(new PackageResourceReference(
EmojiOnes.class, "icon/" + emojiCode + ".png"), new PageParameters());
Map<String, String> emoji = new HashMap<>();
emoji.put("name", emojiName);
emoji.put("url", url.toString());
emojis.add(emoji);
}
}
String json;
try {
json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(emojis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoEmojiRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "loadEmojis":
emojis = new ArrayList<>();
String urlPattern = RequestCycle.get().urlFor(new PackageResourceReference(EmojiOnes.class,
"icon/FILENAME.png"), new PageParameters()).toString();
for (Map.Entry<String, String> entry: EmojiOnes.getInstance().all().entrySet()) {
Map<String, String> emoji = new HashMap<>();
emoji.put("name", entry.getKey());
emoji.put("url", urlPattern.replace("FILENAME", entry.getValue()));
emojis.add(emoji);
}
try {
json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(emojis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("onedev.server.markdown.onEmojisLoaded('%s', %s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "userQuery":
String userQuery = params.getParameterValue("param1").toOptionalString();
AvatarManager avatarManager = OneDev.getInstance(AvatarManager.class);
List<Map<String, String>> userList = new ArrayList<>();
for (User user: getUserMentionSupport().findUsers(userQuery, ATWHO_LIMIT)) {
Map<String, String> userMap = new HashMap<>();
userMap.put("name", user.getName());
if (user.getFullName() != null)
userMap.put("fullName", user.getFullName());
String noSpaceName = StringUtils.deleteWhitespace(user.getName());
if (user.getFullName() != null) {
String noSpaceFullName = StringUtils.deleteWhitespace(user.getFullName());
userMap.put("searchKey", noSpaceName + " " + noSpaceFullName);
} else {
userMap.put("searchKey", noSpaceName);
}
String avatarUrl = avatarManager.getAvatarUrl(user);
userMap.put("avatarUrl", avatarUrl);
userList.add(userMap);
}
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(userList);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoUserRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "referenceQuery":
String referenceQuery = params.getParameterValue("param1").toOptionalString();
String referenceQueryType = params.getParameterValue("param2").toOptionalString();
String referenceProjectName = params.getParameterValue("param3").toOptionalString();
List<Map<String, String>> referenceList = new ArrayList<>();
Project referenceProject;
if (StringUtils.isNotBlank(referenceProjectName))
referenceProject = OneDev.getInstance(ProjectManager.class).find(referenceProjectName);
else
referenceProject = null;
if (referenceProject != null || StringUtils.isBlank(referenceProjectName)) {
if ("issue".equals(referenceQueryType)) {
for (Issue issue: getReferenceSupport().findIssues(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "issue");
referenceMap.put("referenceNumber", String.valueOf(issue.getNumber()));
referenceMap.put("referenceTitle", issue.getTitle());
referenceMap.put("searchKey", issue.getNumber() + " " + StringUtils.deleteWhitespace(issue.getTitle()));
referenceList.add(referenceMap);
}
} else if ("pullrequest".equals(referenceQueryType)) {
for (PullRequest request: getReferenceSupport().findPullRequests(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "pull request");
referenceMap.put("referenceNumber", String.valueOf(request.getNumber()));
referenceMap.put("referenceTitle", request.getTitle());
referenceMap.put("searchKey", request.getNumber() + " " + StringUtils.deleteWhitespace(request.getTitle()));
referenceList.add(referenceMap);
}
} else if ("build".equals(referenceQueryType)) {
for (Build build: getReferenceSupport().findBuilds(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "build");
referenceMap.put("referenceNumber", String.valueOf(build.getNumber()));
String title;
if (build.getVersion() != null)
title = "(" + build.getVersion() + ") " + build.getJobName();
else
title = build.getJobName();
referenceMap.put("referenceTitle", title);
referenceMap.put("searchKey", build.getNumber() + " " + StringUtils.deleteWhitespace(title));
referenceList.add(referenceMap);
}
}
}
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(referenceList);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoReferenceRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "selectImage":
case "selectLink":
new ModalPanel(target) {
@Override
protected Component newContent(String id) {
return new InsertUrlPanel(id, MarkdownEditor.this, action.equals("selectImage")) {
@Override
protected void onClose(AjaxRequestTarget target) {
close();
}
};
}
@Override
protected void onClosed() {
super.onClosed();
AjaxRequestTarget target =
Preconditions.checkNotNull(RequestCycle.get().find(AjaxRequestTarget.class));
target.appendJavaScript(String.format("$('#%s textarea').focus();", container.getMarkupId()));
}
};
break;
case "insertUrl":
String name;
try {
name = URLDecoder.decode(params.getParameterValue("param1").toString(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String replaceMessage = params.getParameterValue("param2").toString();
String url = getAttachmentSupport().getAttachmentUrl(name);
insertUrl(target, isWebSafeImage(name), url, name, replaceMessage);
break;
default:
throw new IllegalStateException("Unknown action: " + action);
}
}
});
container.add(attachmentUploadBehavior = new AbstractPostAjaxBehavior() {
@Override
protected void respond(AjaxRequestTarget target) {
Preconditions.checkNotNull(getAttachmentSupport(), "Unexpected attachment upload request");
HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
HttpServletResponse response = (HttpServletResponse) RequestCycle.get().getResponse().getContainerResponse();
try {
String fileName = FilenameUtils.sanitizeFilename(
URLDecoder.decode(request.getHeader("File-Name"), StandardCharsets.UTF_8.name()));
String attachmentName = getAttachmentSupport().saveAttachment(fileName, request.getInputStream());
response.getWriter().print(URLEncoder.encode(attachmentName, StandardCharsets.UTF_8.name()));
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
logger.error("Error uploading attachment.", e);
try {
if (e.getMessage() != null)
response.getWriter().print(e.getMessage());
else
response.getWriter().print("Internal server error");
} catch (IOException e2) {
throw new RuntimeException(e2);
}
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
});
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
}
@Override
public void convertInput() {
setConvertedInput(input.getConvertedInput());
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forReference(new MarkdownResourceReference()));
String actionCallback = actionBehavior.getCallbackFunction(explicit("action"), explicit("param1"), explicit("param2"),
explicit("param3")).toString();
String attachmentUploadUrl = attachmentUploadBehavior.getCallbackUrl().toString();
String autosaveKey = getAutosaveKey();
if (autosaveKey != null)
autosaveKey = "'" + JavaScriptEscape.escapeJavaScript(autosaveKey) + "'";
else
autosaveKey = "undefined";
String script = String.format("onedev.server.markdown.onDomReady('%s', %s, %d, %s, %d, %b, %b, '%s', %s);",
container.getMarkupId(),
actionCallback,
ATWHO_LIMIT,
getAttachmentSupport()!=null? "'" + attachmentUploadUrl + "'": "undefined",
getAttachmentSupport()!=null? getAttachmentSupport().getAttachmentMaxSize(): 0,
getUserMentionSupport() != null,
getReferenceSupport() != null,
JavaScriptEscape.escapeJavaScript(ProjectNameValidator.PATTERN.pattern()),
autosaveKey);
response.render(OnDomReadyHeaderItem.forScript(script));
script = String.format("onedev.server.markdown.onLoad('%s');", container.getMarkupId());
response.render(OnLoadHeaderItem.forScript(script));
}
public void insertUrl(AjaxRequestTarget target, boolean isImage, String url,
String name, @Nullable String replaceMessage) {
String script = String.format("onedev.server.markdown.insertUrl('%s', %s, '%s', '%s', %s);",
container.getMarkupId(), isImage, StringEscapeUtils.escapeEcmaScript(url),
StringEscapeUtils.escapeEcmaScript(name),
replaceMessage!=null?"'"+replaceMessage+"'":"undefined");
target.appendJavaScript(script);
}
public boolean isWebSafeImage(String fileName) {
fileName = fileName.toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
|| fileName.endsWith(".gif") || fileName.endsWith(".png");
}
@Nullable
protected AttachmentSupport getAttachmentSupport() {
return null;
}
@Nullable
protected UserMentionSupport getUserMentionSupport() {
return null;
}
@Nullable
protected AtWhoReferenceSupport getReferenceSupport() {
return null;
}
protected List<AttributeModifier> getInputModifiers() {
return new ArrayList<>();
}
@Nullable
protected String getAutosaveKey() {
return null;
}
@Nullable
public BlobRenderContext getBlobRenderContext() {
return blobRenderContext;
}
static class ReferencedEntity implements Serializable {
String entityType;
String entityTitle;
String entityNumber;
String searchKey;
}
}
|
./CrossVul/dataset_final_sorted/CWE-434/java/good_1896_2
|
crossvul-java_data_good_4310_0
|
/*
* Copyright (C) 2004 Red Hat Inc.
* Copyright (C) 2005 Martin Koegler
* Copyright (C) 2010 m-privacy GmbH
* Copyright (C) 2010 TigerVNC Team
* Copyright (C) 2011-2019 Brian P. Hinz
* Copyright (C) 2015 D. R. Commander. All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package com.tigervnc.rfb;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.security.cert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.HostnameVerifier;
import javax.swing.JOptionPane;
import com.tigervnc.rdr.*;
import com.tigervnc.network.*;
import com.tigervnc.vncviewer.*;
import static javax.swing.JOptionPane.*;
public class CSecurityTLS extends CSecurity {
public static StringParameter X509CA
= new StringParameter("X509CA",
"X509 CA certificate", "", Configuration.ConfigurationObject.ConfViewer);
public static StringParameter X509CRL
= new StringParameter("X509CRL",
"X509 CRL file", "", Configuration.ConfigurationObject.ConfViewer);
public static UserMsgBox msg;
private void initGlobal()
{
try {
ctx = SSLContext.getInstance("TLS");
} catch(NoSuchAlgorithmException e) {
throw new Exception(e.toString());
}
}
public CSecurityTLS(boolean _anon)
{
anon = _anon;
manager = null;
setDefaults();
cafile = X509CA.getData();
crlfile = X509CRL.getData();
}
public static String getDefaultCA() {
if (UserPreferences.get("viewer", "x509ca") != null)
return UserPreferences.get("viewer", "x509ca");
return FileUtils.getVncHomeDir()+"x509_ca.pem";
}
public static String getDefaultCRL() {
if (UserPreferences.get("viewer", "x509crl") != null)
return UserPreferences.get("viewer", "x509crl");
return FileUtils.getVncHomeDir()+"x509_crl.pem";
}
public static void setDefaults()
{
if (new File(getDefaultCA()).exists())
X509CA.setDefaultStr(getDefaultCA());
if (new File(getDefaultCRL()).exists())
X509CRL.setDefaultStr(getDefaultCRL());
}
public boolean processMsg(CConnection cc) {
is = (FdInStream)cc.getInStream();
os = (FdOutStream)cc.getOutStream();
client = cc;
initGlobal();
if (manager == null) {
if (!is.checkNoWait(1))
return false;
if (is.readU8() == 0) {
int result = is.readU32();
String reason;
if (result == Security.secResultFailed ||
result == Security.secResultTooMany)
reason = is.readString();
else
reason = new String("Authentication failure (protocol error)");
throw new AuthFailureException(reason);
}
setParam();
}
try {
manager = new SSLEngineManager(engine, is, os);
manager.doHandshake();
} catch(java.lang.Exception e) {
throw new SystemException(e.toString());
}
cc.setStreams(new TLSInStream(is, manager),
new TLSOutStream(os, manager));
return true;
}
private void setParam() {
if (anon) {
try {
ctx.init(null, null, null);
} catch(KeyManagementException e) {
throw new AuthFailureException(e.toString());
}
} else {
try {
TrustManager[] myTM = new TrustManager[] {
new MyX509TrustManager()
};
ctx.init (null, myTM, null);
} catch (java.security.GeneralSecurityException e) {
throw new AuthFailureException(e.toString());
}
}
SSLSocketFactory sslfactory = ctx.getSocketFactory();
engine = ctx.createSSLEngine(client.getServerName(),
client.getServerPort());
engine.setUseClientMode(true);
String[] supported = engine.getSupportedProtocols();
ArrayList<String> enabled = new ArrayList<String>();
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS.*"))
enabled.add(supported[i]);
engine.setEnabledProtocols(enabled.toArray(new String[0]));
if (anon) {
supported = engine.getSupportedCipherSuites();
enabled = new ArrayList<String>();
// prefer ECDH over DHE
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_ECDH_anon.*"))
enabled.add(supported[i]);
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_DH_anon.*"))
enabled.add(supported[i]);
engine.setEnabledCipherSuites(enabled.toArray(new String[0]));
} else {
engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
}
}
class MyX509TrustManager implements X509TrustManager
{
X509TrustManager tm;
MyX509TrustManager() throws java.security.GeneralSecurityException
{
KeyStore ks = KeyStore.getInstance("JKS");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
try {
ks.load(null, null);
String a = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(a);
tmf.init((KeyStore)null);
for (TrustManager m : tmf.getTrustManagers())
if (m instanceof X509TrustManager)
for (X509Certificate c : ((X509TrustManager)m).getAcceptedIssuers())
ks.setCertificateEntry(getThumbprint((X509Certificate)c), c);
File cacert = new File(cafile);
if (cacert.exists() && cacert.canRead()) {
InputStream caStream = new MyFileInputStream(cacert);
Collection<? extends Certificate> cacerts =
cf.generateCertificates(caStream);
for (Certificate cert : cacerts) {
String thumbprint = getThumbprint((X509Certificate)cert);
ks.setCertificateEntry(thumbprint, (X509Certificate)cert);
}
}
PKIXBuilderParameters params =
new PKIXBuilderParameters(ks, new X509CertSelector());
File crlcert = new File(crlfile);
if (!crlcert.exists() || !crlcert.canRead()) {
params.setRevocationEnabled(false);
} else {
InputStream crlStream = new FileInputStream(crlfile);
Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
params.addCertStore(store);
params.setRevocationEnabled(true);
}
tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(new CertPathTrustManagerParameters(params));
tm = (X509TrustManager)tmf.getTrustManagers()[0];
} catch (java.lang.Exception e) {
throw new Exception(e.getMessage());
}
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
tm.checkClientTrusted(chain, authType);
}
private final char[] hexCode = "0123456789ABCDEF".toCharArray();
private String printHexBinary(byte[] data)
{
StringBuilder r = new StringBuilder(data.length*2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
Collection<? extends Certificate> certs = null;
X509Certificate cert = chain[0];
String pk =
Base64.getEncoder().encodeToString(cert.getPublicKey().getEncoded());
try {
cert.checkValidity();
verifyHostname(cert);
} catch(CertificateParsingException e) {
throw new SystemException(e.getMessage());
} catch(CertificateNotYetValidException e) {
throw new AuthFailureException("server certificate has not been activated");
} catch(CertificateExpiredException e) {
if (!msg.showMsgBox(YES_NO_OPTION, "certificate has expired",
"The certificate of the server has expired, "+
"do you want to continue?"))
throw new AuthFailureException("server certificate has expired");
}
File vncDir = new File(FileUtils.getVncHomeDir());
if (!vncDir.exists())
throw new AuthFailureException("Could not obtain VNC home directory "+
"path for known hosts storage");
File dbPath = new File(vncDir, "x509_known_hosts");
String info =
" Subject: "+cert.getSubjectX500Principal().getName()+"\n"+
" Issuer: "+cert.getIssuerX500Principal().getName()+"\n"+
" Serial Number: "+cert.getSerialNumber()+"\n"+
" Version: "+cert.getVersion()+"\n"+
" Signature Algorithm: "+cert.getPublicKey().getAlgorithm()+"\n"+
" Not Valid Before: "+cert.getNotBefore()+"\n"+
" Not Valid After: "+cert.getNotAfter()+"\n"+
" SHA-1 Fingerprint: "+getThumbprint(cert)+"\n";
try {
if (dbPath.exists()) {
FileReader db = new FileReader(dbPath);
BufferedReader dbBuf = new BufferedReader(db);
String line;
String server = client.getServerName().toLowerCase();
while ((line = dbBuf.readLine())!=null) {
String fields[] = line.split("\\|");
if (fields.length==6) {
if (server.equals(fields[2]) && pk.equals(fields[5])) {
vlog.debug("Server certificate found in known hosts file");
dbBuf.close();
return;
} else if (server.equals(fields[2]) && !pk.equals(fields[5]) ||
!server.equals(fields[2]) && pk.equals(fields[5])) {
throw new CertStoreException();
}
}
}
dbBuf.close();
}
tm.checkServerTrusted(chain, authType);
} catch (IOException e) {
throw new AuthFailureException("Could not load known hosts database");
} catch (CertStoreException e) {
vlog.debug("Server host key mismatch");
vlog.debug(info);
String text =
"This host is previously known with a different "+
"certificate, and the new certificate has been "+
"signed by an unknown authority\n"+
"\n"+info+"\n"+
"Someone could be trying to impersonate the site and you should not continue.\n"+
"\n"+
"Do you want to make an exception for this server?";
if (!msg.showMsgBox(YES_NO_OPTION, "Unexpected certificate issuer", text))
throw new AuthFailureException("Unexpected certificate issuer");
store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);
} catch (java.lang.Exception e) {
if (e.getCause() instanceof CertPathBuilderException) {
vlog.debug("Server host not previously known");
vlog.debug(info);
String text =
"This certificate has been signed by an unknown authority\n"+
"\n"+info+"\n"+
"Someone could be trying to impersonate the site and you should not continue.\n"+
"\n"+
"Do you want to make an exception for this server?";
if (!msg.showMsgBox(YES_NO_OPTION, "Unknown certificate issuer", text))
throw new AuthFailureException("Unknown certificate issuer");
store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);
} else {
throw new SystemException(e.getMessage());
}
}
}
private void store_pubkey(File dbPath, String serverName, String pk)
{
ArrayList<String> lines = new ArrayList<String>();
File vncDir = new File(FileUtils.getVncHomeDir());
try {
if (dbPath.exists()) {
FileReader db = new FileReader(dbPath);
BufferedReader dbBuf = new BufferedReader(db);
String line;
while ((line = dbBuf.readLine())!=null) {
String fields[] = line.split("\\|");
if (fields.length==6)
if (!serverName.equals(fields[2]) && !pk.equals(fields[5]))
lines.add(line);
}
dbBuf.close();
}
} catch (IOException e) {
throw new AuthFailureException("Could not load known hosts database");
}
try {
if (!dbPath.exists())
dbPath.createNewFile();
FileWriter fw = new FileWriter(dbPath.getAbsolutePath(), false);
Iterator i = lines.iterator();
while (i.hasNext())
fw.write((String)i.next()+"\n");
fw.write("|g0|"+serverName+"|*|0|"+pk+"\n");
fw.close();
} catch (IOException e) {
vlog.error("Failed to store server certificate to known hosts database");
}
}
public X509Certificate[] getAcceptedIssuers ()
{
return tm.getAcceptedIssuers();
}
private String getThumbprint(X509Certificate cert)
{
String thumbprint = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(cert.getEncoded());
thumbprint = printHexBinary(md.digest());
thumbprint = thumbprint.replaceAll("..(?!$)", "$0 ");
} catch(CertificateEncodingException e) {
throw new SystemException(e.getMessage());
} catch(NoSuchAlgorithmException e) {
throw new SystemException(e.getMessage());
}
return thumbprint;
}
private void verifyHostname(X509Certificate cert)
throws CertificateParsingException
{
try {
Collection sans = cert.getSubjectAlternativeNames();
if (sans == null) {
String dn = cert.getSubjectX500Principal().getName();
LdapName ln = new LdapName(dn);
for (Rdn rdn : ln.getRdns()) {
if (rdn.getType().equalsIgnoreCase("CN")) {
String peer = client.getServerName().toLowerCase();
if (peer.equals(((String)rdn.getValue()).toLowerCase()))
return;
}
}
} else {
Iterator i = sans.iterator();
while (i.hasNext()) {
List nxt = (List)i.next();
if (((Integer)nxt.get(0)).intValue() == 2) {
String peer = client.getServerName().toLowerCase();
if (peer.equals(((String)nxt.get(1)).toLowerCase()))
return;
} else if (((Integer)nxt.get(0)).intValue() == 7) {
String peer = ((CConn)client).getSocket().getPeerAddress();
if (peer.equals(((String)nxt.get(1)).toLowerCase()))
return;
}
}
}
Object[] answer = {"YES", "NO"};
int ret = JOptionPane.showOptionDialog(null,
"Hostname ("+client.getServerName()+") does not match the"+
" server certificate, do you want to continue?",
"Certificate hostname mismatch",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
null, answer, answer[0]);
if (ret != JOptionPane.YES_OPTION)
throw new WarningException("Certificate hostname mismatch.");
} catch (CertificateParsingException e) {
throw new SystemException(e.getMessage());
} catch (InvalidNameException e) {
throw new SystemException(e.getMessage());
}
}
private class MyFileInputStream extends InputStream {
// Blank lines in a certificate file will cause Java 6 to throw a
// "DerInputStream.getLength(): lengthTag=127, too big" exception.
ByteBuffer buf;
public MyFileInputStream(String name) {
this(new File(name));
}
public MyFileInputStream(File file) {
StringBuffer sb = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String l;
while ((l = reader.readLine()) != null) {
if (l.trim().length() > 0 )
sb.append(l+"\n");
}
} catch (java.lang.Exception e) {
throw new Exception(e.toString());
} finally {
try {
if (reader != null)
reader.close();
} catch(IOException ioe) {
throw new Exception(ioe.getMessage());
}
}
Charset utf8 = Charset.forName("UTF-8");
buf = ByteBuffer.wrap(sb.toString().getBytes(utf8));
buf.limit(buf.capacity());
}
@Override
public int read(byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (!buf.hasRemaining())
return -1;
len = Math.min(len, buf.remaining());
buf.get(b, off, len);
return len;
}
@Override
public int read() throws IOException {
if (!buf.hasRemaining())
return -1;
return buf.get() & 0xFF;
}
}
}
public final int getType() { return anon ? Security.secTypeTLSNone : Security.secTypeX509None; }
public final String description()
{ return anon ? "TLS Encryption without VncAuth" : "X509 Encryption without VncAuth"; }
public boolean isSecure() { return !anon; }
protected CConnection client;
private SSLContext ctx;
private SSLEngine engine;
private SSLEngineManager manager;
private boolean anon;
private String cafile, crlfile;
private FdInStream is;
private FdOutStream os;
static LogWriter vlog = new LogWriter("CSecurityTLS");
}
|
./CrossVul/dataset_final_sorted/CWE-295/java/good_4310_0
|
crossvul-java_data_good_4313_0
|
/*
* Copyright (C) 2004 Red Hat Inc.
* Copyright (C) 2005 Martin Koegler
* Copyright (C) 2010 m-privacy GmbH
* Copyright (C) 2010 TigerVNC Team
* Copyright (C) 2011-2019 Brian P. Hinz
* Copyright (C) 2015 D. R. Commander. All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package com.tigervnc.rfb;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.security.cert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.HostnameVerifier;
import javax.swing.JOptionPane;
import com.tigervnc.rdr.*;
import com.tigervnc.network.*;
import com.tigervnc.vncviewer.*;
import static javax.swing.JOptionPane.*;
public class CSecurityTLS extends CSecurity {
public static StringParameter X509CA
= new StringParameter("X509CA",
"X509 CA certificate", "", Configuration.ConfigurationObject.ConfViewer);
public static StringParameter X509CRL
= new StringParameter("X509CRL",
"X509 CRL file", "", Configuration.ConfigurationObject.ConfViewer);
public static UserMsgBox msg;
private void initGlobal()
{
try {
ctx = SSLContext.getInstance("TLS");
} catch(NoSuchAlgorithmException e) {
throw new Exception(e.toString());
}
}
public CSecurityTLS(boolean _anon)
{
anon = _anon;
manager = null;
setDefaults();
cafile = X509CA.getData();
crlfile = X509CRL.getData();
}
public static String getDefaultCA() {
if (UserPreferences.get("viewer", "x509ca") != null)
return UserPreferences.get("viewer", "x509ca");
return FileUtils.getVncHomeDir()+"x509_ca.pem";
}
public static String getDefaultCRL() {
if (UserPreferences.get("viewer", "x509crl") != null)
return UserPreferences.get("viewer", "x509crl");
return FileUtils.getVncHomeDir()+"x509_crl.pem";
}
public static void setDefaults()
{
if (new File(getDefaultCA()).exists())
X509CA.setDefaultStr(getDefaultCA());
if (new File(getDefaultCRL()).exists())
X509CRL.setDefaultStr(getDefaultCRL());
}
public boolean processMsg(CConnection cc) {
is = (FdInStream)cc.getInStream();
os = (FdOutStream)cc.getOutStream();
client = cc;
initGlobal();
if (manager == null) {
if (!is.checkNoWait(1))
return false;
if (is.readU8() == 0) {
int result = is.readU32();
String reason;
if (result == Security.secResultFailed ||
result == Security.secResultTooMany)
reason = is.readString();
else
reason = new String("Authentication failure (protocol error)");
throw new AuthFailureException(reason);
}
setParam();
}
try {
manager = new SSLEngineManager(engine, is, os);
manager.doHandshake();
} catch(java.lang.Exception e) {
throw new SystemException(e.toString());
}
cc.setStreams(new TLSInStream(is, manager),
new TLSOutStream(os, manager));
return true;
}
private void setParam() {
if (anon) {
try {
ctx.init(null, null, null);
} catch(KeyManagementException e) {
throw new AuthFailureException(e.toString());
}
} else {
try {
TrustManager[] myTM = new TrustManager[] {
new MyX509TrustManager()
};
ctx.init (null, myTM, null);
} catch (java.security.GeneralSecurityException e) {
throw new AuthFailureException(e.toString());
}
}
SSLSocketFactory sslfactory = ctx.getSocketFactory();
engine = ctx.createSSLEngine(client.getServerName(),
client.getServerPort());
engine.setUseClientMode(true);
String[] supported = engine.getSupportedProtocols();
ArrayList<String> enabled = new ArrayList<String>();
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS.*"))
enabled.add(supported[i]);
engine.setEnabledProtocols(enabled.toArray(new String[0]));
if (anon) {
supported = engine.getSupportedCipherSuites();
enabled = new ArrayList<String>();
// prefer ECDH over DHE
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_ECDH_anon.*"))
enabled.add(supported[i]);
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_DH_anon.*"))
enabled.add(supported[i]);
engine.setEnabledCipherSuites(enabled.toArray(new String[0]));
} else {
engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
}
}
class MyX509TrustManager implements X509TrustManager
{
X509TrustManager tm;
MyX509TrustManager() throws java.security.GeneralSecurityException
{
KeyStore ks = KeyStore.getInstance("JKS");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
try {
ks.load(null, null);
String a = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(a);
tmf.init((KeyStore)null);
for (TrustManager m : tmf.getTrustManagers())
if (m instanceof X509TrustManager)
for (X509Certificate c : ((X509TrustManager)m).getAcceptedIssuers())
ks.setCertificateEntry(getThumbprint((X509Certificate)c), c);
File cacert = new File(cafile);
if (cacert.exists() && cacert.canRead()) {
InputStream caStream = new MyFileInputStream(cacert);
Collection<? extends Certificate> cacerts =
cf.generateCertificates(caStream);
for (Certificate cert : cacerts) {
String thumbprint = getThumbprint((X509Certificate)cert);
ks.setCertificateEntry(thumbprint, (X509Certificate)cert);
}
}
PKIXBuilderParameters params =
new PKIXBuilderParameters(ks, new X509CertSelector());
File crlcert = new File(crlfile);
if (!crlcert.exists() || !crlcert.canRead()) {
params.setRevocationEnabled(false);
} else {
InputStream crlStream = new FileInputStream(crlfile);
Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
params.addCertStore(store);
params.setRevocationEnabled(true);
}
tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(new CertPathTrustManagerParameters(params));
tm = (X509TrustManager)tmf.getTrustManagers()[0];
} catch (java.lang.Exception e) {
throw new Exception(e.getMessage());
}
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
tm.checkClientTrusted(chain, authType);
}
private final char[] hexCode = "0123456789ABCDEF".toCharArray();
private String printHexBinary(byte[] data)
{
StringBuilder r = new StringBuilder(data.length*2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
Collection<? extends Certificate> certs = null;
X509Certificate cert = chain[0];
String pk =
Base64.getEncoder().encodeToString(cert.getPublicKey().getEncoded());
try {
cert.checkValidity();
verifyHostname(cert);
} catch(CertificateParsingException e) {
throw new SystemException(e.getMessage());
} catch(CertificateNotYetValidException e) {
throw new AuthFailureException("server certificate has not been activated");
} catch(CertificateExpiredException e) {
if (!msg.showMsgBox(YES_NO_OPTION, "certificate has expired",
"The certificate of the server has expired, "+
"do you want to continue?"))
throw new AuthFailureException("server certificate has expired");
}
File vncDir = new File(FileUtils.getVncHomeDir());
if (!vncDir.exists())
throw new AuthFailureException("Could not obtain VNC home directory "+
"path for known hosts storage");
File dbPath = new File(vncDir, "x509_known_hosts");
String info =
" Subject: "+cert.getSubjectX500Principal().getName()+"\n"+
" Issuer: "+cert.getIssuerX500Principal().getName()+"\n"+
" Serial Number: "+cert.getSerialNumber()+"\n"+
" Version: "+cert.getVersion()+"\n"+
" Signature Algorithm: "+cert.getPublicKey().getAlgorithm()+"\n"+
" Not Valid Before: "+cert.getNotBefore()+"\n"+
" Not Valid After: "+cert.getNotAfter()+"\n"+
" SHA-1 Fingerprint: "+getThumbprint(cert)+"\n";
try {
if (dbPath.exists()) {
FileReader db = new FileReader(dbPath);
BufferedReader dbBuf = new BufferedReader(db);
String line;
String server = client.getServerName().toLowerCase();
while ((line = dbBuf.readLine())!=null) {
String fields[] = line.split("\\|");
if (fields.length==6) {
if (server.equals(fields[2]) && pk.equals(fields[5])) {
vlog.debug("Server certificate found in known hosts file");
dbBuf.close();
return;
} else if (server.equals(fields[2]) && !pk.equals(fields[5]) ||
!server.equals(fields[2]) && pk.equals(fields[5])) {
throw new CertStoreException();
}
}
}
dbBuf.close();
}
tm.checkServerTrusted(chain, authType);
} catch (IOException e) {
throw new AuthFailureException("Could not load known hosts database");
} catch (CertStoreException e) {
vlog.debug("Server host key mismatch");
vlog.debug(info);
String text =
"This host is previously known with a different "+
"certificate, and the new certificate has been "+
"signed by an unknown authority\n"+
"\n"+info+"\n"+
"Someone could be trying to impersonate the site and you should not continue.\n"+
"\n"+
"Do you want to make an exception for this server?";
if (!msg.showMsgBox(YES_NO_OPTION, "Unexpected certificate issuer", text))
throw new AuthFailureException("Unexpected certificate issuer");
store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);
} catch (java.lang.Exception e) {
if (e.getCause() instanceof CertPathBuilderException) {
vlog.debug("Server host not previously known");
vlog.debug(info);
String text =
"This certificate has been signed by an unknown authority\n"+
"\n"+info+"\n"+
"Someone could be trying to impersonate the site and you should not continue.\n"+
"\n"+
"Do you want to make an exception for this server?";
if (!msg.showMsgBox(YES_NO_OPTION, "Unknown certificate issuer", text))
throw new AuthFailureException("Unknown certificate issuer");
store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);
} else {
throw new SystemException(e.getMessage());
}
}
}
private void store_pubkey(File dbPath, String serverName, String pk)
{
ArrayList<String> lines = new ArrayList<String>();
File vncDir = new File(FileUtils.getVncHomeDir());
try {
if (dbPath.exists()) {
FileReader db = new FileReader(dbPath);
BufferedReader dbBuf = new BufferedReader(db);
String line;
while ((line = dbBuf.readLine())!=null) {
String fields[] = line.split("\\|");
if (fields.length==6)
if (!serverName.equals(fields[2]) && !pk.equals(fields[5]))
lines.add(line);
}
dbBuf.close();
}
} catch (IOException e) {
throw new AuthFailureException("Could not load known hosts database");
}
try {
if (!dbPath.exists())
dbPath.createNewFile();
FileWriter fw = new FileWriter(dbPath.getAbsolutePath(), false);
Iterator i = lines.iterator();
while (i.hasNext())
fw.write((String)i.next()+"\n");
fw.write("|g0|"+serverName+"|*|0|"+pk+"\n");
fw.close();
} catch (IOException e) {
vlog.error("Failed to store server certificate to known hosts database");
}
}
public X509Certificate[] getAcceptedIssuers ()
{
return tm.getAcceptedIssuers();
}
private String getThumbprint(X509Certificate cert)
{
String thumbprint = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(cert.getEncoded());
thumbprint = printHexBinary(md.digest());
thumbprint = thumbprint.replaceAll("..(?!$)", "$0 ");
} catch(CertificateEncodingException e) {
throw new SystemException(e.getMessage());
} catch(NoSuchAlgorithmException e) {
throw new SystemException(e.getMessage());
}
return thumbprint;
}
private void verifyHostname(X509Certificate cert)
throws CertificateParsingException
{
try {
Collection sans = cert.getSubjectAlternativeNames();
if (sans == null) {
String dn = cert.getSubjectX500Principal().getName();
LdapName ln = new LdapName(dn);
for (Rdn rdn : ln.getRdns()) {
if (rdn.getType().equalsIgnoreCase("CN")) {
String peer = client.getServerName().toLowerCase();
if (peer.equals(((String)rdn.getValue()).toLowerCase()))
return;
}
}
} else {
Iterator i = sans.iterator();
while (i.hasNext()) {
List nxt = (List)i.next();
if (((Integer)nxt.get(0)).intValue() == 2) {
String peer = client.getServerName().toLowerCase();
if (peer.equals(((String)nxt.get(1)).toLowerCase()))
return;
} else if (((Integer)nxt.get(0)).intValue() == 7) {
String peer = ((CConn)client).getSocket().getPeerAddress();
if (peer.equals(((String)nxt.get(1)).toLowerCase()))
return;
}
}
}
Object[] answer = {"YES", "NO"};
int ret = JOptionPane.showOptionDialog(null,
"Hostname ("+client.getServerName()+") does not match the"+
" server certificate, do you want to continue?",
"Certificate hostname mismatch",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
null, answer, answer[0]);
if (ret != JOptionPane.YES_OPTION)
throw new WarningException("Certificate hostname mismatch.");
} catch (CertificateParsingException e) {
throw new SystemException(e.getMessage());
} catch (InvalidNameException e) {
throw new SystemException(e.getMessage());
}
}
private class MyFileInputStream extends InputStream {
// Blank lines in a certificate file will cause Java 6 to throw a
// "DerInputStream.getLength(): lengthTag=127, too big" exception.
ByteBuffer buf;
public MyFileInputStream(String name) {
this(new File(name));
}
public MyFileInputStream(File file) {
StringBuffer sb = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String l;
while ((l = reader.readLine()) != null) {
if (l.trim().length() > 0 )
sb.append(l+"\n");
}
} catch (java.lang.Exception e) {
throw new Exception(e.toString());
} finally {
try {
if (reader != null)
reader.close();
} catch(IOException ioe) {
throw new Exception(ioe.getMessage());
}
}
Charset utf8 = Charset.forName("UTF-8");
buf = ByteBuffer.wrap(sb.toString().getBytes(utf8));
buf.limit(buf.capacity());
}
@Override
public int read(byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (!buf.hasRemaining())
return -1;
len = Math.min(len, buf.remaining());
buf.get(b, off, len);
return len;
}
@Override
public int read() throws IOException {
if (!buf.hasRemaining())
return -1;
return buf.get() & 0xFF;
}
}
}
public final int getType() { return anon ? Security.secTypeTLSNone : Security.secTypeX509None; }
public final String description()
{ return anon ? "TLS Encryption without VncAuth" : "X509 Encryption without VncAuth"; }
public boolean isSecure() { return !anon; }
protected CConnection client;
private SSLContext ctx;
private SSLEngine engine;
private SSLEngineManager manager;
private boolean anon;
private String cafile, crlfile;
private FdInStream is;
private FdOutStream os;
static LogWriter vlog = new LogWriter("CSecurityTLS");
}
|
./CrossVul/dataset_final_sorted/CWE-295/java/good_4313_0
|
crossvul-java_data_bad_4313_0
|
/*
* Copyright (C) 2004 Red Hat Inc.
* Copyright (C) 2005 Martin Koegler
* Copyright (C) 2010 m-privacy GmbH
* Copyright (C) 2010 TigerVNC Team
* Copyright (C) 2011-2019 Brian P. Hinz
* Copyright (C) 2015 D. R. Commander. All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package com.tigervnc.rfb;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.security.cert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.HostnameVerifier;
import javax.swing.JOptionPane;
import com.tigervnc.rdr.*;
import com.tigervnc.network.*;
import com.tigervnc.vncviewer.*;
import static javax.swing.JOptionPane.*;
public class CSecurityTLS extends CSecurity {
public static StringParameter X509CA
= new StringParameter("X509CA",
"X509 CA certificate", "", Configuration.ConfigurationObject.ConfViewer);
public static StringParameter X509CRL
= new StringParameter("X509CRL",
"X509 CRL file", "", Configuration.ConfigurationObject.ConfViewer);
public static UserMsgBox msg;
private void initGlobal()
{
try {
ctx = SSLContext.getInstance("TLS");
} catch(NoSuchAlgorithmException e) {
throw new Exception(e.toString());
}
}
public CSecurityTLS(boolean _anon)
{
anon = _anon;
manager = null;
setDefaults();
cafile = X509CA.getData();
crlfile = X509CRL.getData();
}
public static String getDefaultCA() {
if (UserPreferences.get("viewer", "x509ca") != null)
return UserPreferences.get("viewer", "x509ca");
return FileUtils.getVncHomeDir()+"x509_ca.pem";
}
public static String getDefaultCRL() {
if (UserPreferences.get("viewer", "x509crl") != null)
return UserPreferences.get("viewer", "x509crl");
return FileUtils.getVncHomeDir()+"x509_crl.pem";
}
public static void setDefaults()
{
if (new File(getDefaultCA()).exists())
X509CA.setDefaultStr(getDefaultCA());
if (new File(getDefaultCRL()).exists())
X509CRL.setDefaultStr(getDefaultCRL());
}
// FIXME:
// Need to shutdown the connection cleanly
// FIXME?
// add a finalizer method that calls shutdown
public boolean processMsg(CConnection cc) {
is = (FdInStream)cc.getInStream();
os = (FdOutStream)cc.getOutStream();
client = cc;
initGlobal();
if (manager == null) {
if (!is.checkNoWait(1))
return false;
if (is.readU8() == 0) {
int result = is.readU32();
String reason;
if (result == Security.secResultFailed ||
result == Security.secResultTooMany)
reason = is.readString();
else
reason = new String("Authentication failure (protocol error)");
throw new AuthFailureException(reason);
}
setParam();
}
try {
manager = new SSLEngineManager(engine, is, os);
manager.doHandshake();
} catch(java.lang.Exception e) {
throw new SystemException(e.toString());
}
cc.setStreams(new TLSInStream(is, manager),
new TLSOutStream(os, manager));
return true;
}
private void setParam() {
if (anon) {
try {
ctx.init(null, null, null);
} catch(KeyManagementException e) {
throw new AuthFailureException(e.toString());
}
} else {
try {
TrustManager[] myTM = new TrustManager[] {
new MyX509TrustManager()
};
ctx.init (null, myTM, null);
} catch (java.security.GeneralSecurityException e) {
throw new AuthFailureException(e.toString());
}
}
SSLSocketFactory sslfactory = ctx.getSocketFactory();
engine = ctx.createSSLEngine(client.getServerName(),
client.getServerPort());
engine.setUseClientMode(true);
String[] supported = engine.getSupportedProtocols();
ArrayList<String> enabled = new ArrayList<String>();
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS.*"))
enabled.add(supported[i]);
engine.setEnabledProtocols(enabled.toArray(new String[0]));
if (anon) {
supported = engine.getSupportedCipherSuites();
enabled = new ArrayList<String>();
// prefer ECDH over DHE
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_ECDH_anon.*"))
enabled.add(supported[i]);
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_DH_anon.*"))
enabled.add(supported[i]);
engine.setEnabledCipherSuites(enabled.toArray(new String[0]));
} else {
engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
}
}
class MyX509TrustManager implements X509TrustManager
{
X509TrustManager tm;
MyX509TrustManager() throws java.security.GeneralSecurityException
{
KeyStore ks = KeyStore.getInstance("JKS");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
try {
ks.load(null, null);
String a = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(a);
tmf.init((KeyStore)null);
for (TrustManager m : tmf.getTrustManagers())
if (m instanceof X509TrustManager)
for (X509Certificate c : ((X509TrustManager)m).getAcceptedIssuers())
ks.setCertificateEntry(getThumbprint((X509Certificate)c), c);
File cacert = new File(cafile);
if (cacert.exists() && cacert.canRead()) {
InputStream caStream = new MyFileInputStream(cacert);
Collection<? extends Certificate> cacerts =
cf.generateCertificates(caStream);
for (Certificate cert : cacerts) {
String thumbprint = getThumbprint((X509Certificate)cert);
ks.setCertificateEntry(thumbprint, (X509Certificate)cert);
}
}
PKIXBuilderParameters params =
new PKIXBuilderParameters(ks, new X509CertSelector());
File crlcert = new File(crlfile);
if (!crlcert.exists() || !crlcert.canRead()) {
params.setRevocationEnabled(false);
} else {
InputStream crlStream = new FileInputStream(crlfile);
Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
params.addCertStore(store);
params.setRevocationEnabled(true);
}
tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(new CertPathTrustManagerParameters(params));
tm = (X509TrustManager)tmf.getTrustManagers()[0];
} catch (java.lang.Exception e) {
throw new Exception(e.getMessage());
}
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
tm.checkClientTrusted(chain, authType);
}
private final char[] hexCode = "0123456789ABCDEF".toCharArray();
private String printHexBinary(byte[] data)
{
StringBuilder r = new StringBuilder(data.length*2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
Collection<? extends Certificate> certs = null;
X509Certificate cert = chain[0];
try {
cert.checkValidity();
} catch(CertificateNotYetValidException e) {
throw new AuthFailureException("server certificate has not been activated");
} catch(CertificateExpiredException e) {
if (!msg.showMsgBox(YES_NO_OPTION, "certificate has expired",
"The certificate of the server has expired, "+
"do you want to continue?"))
throw new AuthFailureException("server certificate has expired");
}
String thumbprint = getThumbprint(cert);
File vncDir = new File(FileUtils.getVncHomeDir());
File certFile = new File(vncDir, "x509_savedcerts.pem");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
if (vncDir.exists() && certFile.exists() && certFile.canRead()) {
InputStream certStream = new MyFileInputStream(certFile);
certs = cf.generateCertificates(certStream);
for (Certificate c : certs)
if (thumbprint.equals(getThumbprint((X509Certificate)c)))
return;
}
try {
verifyHostname(cert);
tm.checkServerTrusted(chain, authType);
} catch (java.lang.Exception e) {
if (e.getCause() instanceof CertPathBuilderException) {
String certinfo =
"This certificate has been signed by an unknown authority\n"+
"\n"+
" Subject: "+cert.getSubjectX500Principal().getName()+"\n"+
" Issuer: "+cert.getIssuerX500Principal().getName()+"\n"+
" Serial Number: "+cert.getSerialNumber()+"\n"+
" Version: "+cert.getVersion()+"\n"+
" Signature Algorithm: "+cert.getPublicKey().getAlgorithm()+"\n"+
" Not Valid Before: "+cert.getNotBefore()+"\n"+
" Not Valid After: "+cert.getNotAfter()+"\n"+
" SHA1 Fingerprint: "+getThumbprint(cert)+"\n"+
"\n"+
"Do you want to save it and continue?";
if (!msg.showMsgBox(YES_NO_OPTION, "certificate issuer unknown",
certinfo)) {
throw new AuthFailureException("certificate issuer unknown");
}
if (certs == null || !certs.contains(cert)) {
byte[] der = cert.getEncoded();
String pem = Base64.getEncoder().encodeToString(der);
pem = pem.replaceAll("(.{64})", "$1\n");
FileWriter fw = null;
try {
if (!vncDir.exists())
vncDir.mkdir();
if (!certFile.exists() && !certFile.createNewFile()) {
vlog.error("Certificate save failed.");
} else {
fw = new FileWriter(certFile.getAbsolutePath(), true);
fw.write("-----BEGIN CERTIFICATE-----\n");
fw.write(pem+"\n");
fw.write("-----END CERTIFICATE-----\n");
}
} catch (IOException ioe) {
msg.showMsgBox(OK_OPTION, "certificate save failed",
"Could not save the certificate");
} finally {
try {
if (fw != null)
fw.close();
} catch(IOException ioe2) {
throw new Exception(ioe2.getMessage());
}
}
}
} else {
throw new SystemException(e.getMessage());
}
}
}
public X509Certificate[] getAcceptedIssuers ()
{
return tm.getAcceptedIssuers();
}
private String getThumbprint(X509Certificate cert)
{
String thumbprint = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(cert.getEncoded());
thumbprint = printHexBinary(md.digest());
thumbprint = thumbprint.replaceAll("..(?!$)", "$0 ");
} catch(CertificateEncodingException e) {
throw new SystemException(e.getMessage());
} catch(NoSuchAlgorithmException e) {
throw new SystemException(e.getMessage());
}
return thumbprint;
}
private void verifyHostname(X509Certificate cert)
throws CertificateParsingException
{
try {
Collection sans = cert.getSubjectAlternativeNames();
if (sans == null) {
String dn = cert.getSubjectX500Principal().getName();
LdapName ln = new LdapName(dn);
for (Rdn rdn : ln.getRdns()) {
if (rdn.getType().equalsIgnoreCase("CN")) {
String peer = client.getServerName().toLowerCase();
if (peer.equals(((String)rdn.getValue()).toLowerCase()))
return;
}
}
} else {
Iterator i = sans.iterator();
while (i.hasNext()) {
List nxt = (List)i.next();
if (((Integer)nxt.get(0)).intValue() == 2) {
String peer = client.getServerName().toLowerCase();
if (peer.equals(((String)nxt.get(1)).toLowerCase()))
return;
} else if (((Integer)nxt.get(0)).intValue() == 7) {
String peer = ((CConn)client).getSocket().getPeerAddress();
if (peer.equals(((String)nxt.get(1)).toLowerCase()))
return;
}
}
}
Object[] answer = {"YES", "NO"};
int ret = JOptionPane.showOptionDialog(null,
"Hostname verification failed. Do you want to continue?",
"Hostname Verification Failure",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
null, answer, answer[0]);
if (ret != JOptionPane.YES_OPTION)
throw new WarningException("Hostname verification failed.");
} catch (CertificateParsingException e) {
throw new SystemException(e.getMessage());
} catch (InvalidNameException e) {
throw new SystemException(e.getMessage());
}
}
private class MyFileInputStream extends InputStream {
// Blank lines in a certificate file will cause Java 6 to throw a
// "DerInputStream.getLength(): lengthTag=127, too big" exception.
ByteBuffer buf;
public MyFileInputStream(String name) {
this(new File(name));
}
public MyFileInputStream(File file) {
StringBuffer sb = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String l;
while ((l = reader.readLine()) != null) {
if (l.trim().length() > 0 )
sb.append(l+"\n");
}
} catch (java.lang.Exception e) {
throw new Exception(e.toString());
} finally {
try {
if (reader != null)
reader.close();
} catch(IOException ioe) {
throw new Exception(ioe.getMessage());
}
}
Charset utf8 = Charset.forName("UTF-8");
buf = ByteBuffer.wrap(sb.toString().getBytes(utf8));
buf.limit(buf.capacity());
}
@Override
public int read(byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (!buf.hasRemaining())
return -1;
len = Math.min(len, buf.remaining());
buf.get(b, off, len);
return len;
}
@Override
public int read() throws IOException {
if (!buf.hasRemaining())
return -1;
return buf.get() & 0xFF;
}
}
}
public final int getType() { return anon ? Security.secTypeTLSNone : Security.secTypeX509None; }
public final String description()
{ return anon ? "TLS Encryption without VncAuth" : "X509 Encryption without VncAuth"; }
public boolean isSecure() { return !anon; }
protected CConnection client;
private SSLContext ctx;
private SSLEngine engine;
private SSLEngineManager manager;
private boolean anon;
private String cafile, crlfile;
private FdInStream is;
private FdOutStream os;
static LogWriter vlog = new LogWriter("CSecurityTLS");
}
|
./CrossVul/dataset_final_sorted/CWE-295/java/bad_4313_0
|
crossvul-java_data_bad_4310_0
|
/*
* Copyright (C) 2004 Red Hat Inc.
* Copyright (C) 2005 Martin Koegler
* Copyright (C) 2010 m-privacy GmbH
* Copyright (C) 2010 TigerVNC Team
* Copyright (C) 2011-2019 Brian P. Hinz
* Copyright (C) 2015 D. R. Commander. All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package com.tigervnc.rfb;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.security.cert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.HostnameVerifier;
import javax.swing.JOptionPane;
import com.tigervnc.rdr.*;
import com.tigervnc.network.*;
import com.tigervnc.vncviewer.*;
import static javax.swing.JOptionPane.*;
public class CSecurityTLS extends CSecurity {
public static StringParameter X509CA
= new StringParameter("X509CA",
"X509 CA certificate", "", Configuration.ConfigurationObject.ConfViewer);
public static StringParameter X509CRL
= new StringParameter("X509CRL",
"X509 CRL file", "", Configuration.ConfigurationObject.ConfViewer);
public static UserMsgBox msg;
private void initGlobal()
{
try {
ctx = SSLContext.getInstance("TLS");
} catch(NoSuchAlgorithmException e) {
throw new Exception(e.toString());
}
}
public CSecurityTLS(boolean _anon)
{
anon = _anon;
manager = null;
setDefaults();
cafile = X509CA.getData();
crlfile = X509CRL.getData();
}
public static String getDefaultCA() {
if (UserPreferences.get("viewer", "x509ca") != null)
return UserPreferences.get("viewer", "x509ca");
return FileUtils.getVncHomeDir()+"x509_ca.pem";
}
public static String getDefaultCRL() {
if (UserPreferences.get("viewer", "x509crl") != null)
return UserPreferences.get("viewer", "x509crl");
return FileUtils.getVncHomeDir()+"x509_crl.pem";
}
public static void setDefaults()
{
if (new File(getDefaultCA()).exists())
X509CA.setDefaultStr(getDefaultCA());
if (new File(getDefaultCRL()).exists())
X509CRL.setDefaultStr(getDefaultCRL());
}
// FIXME:
// Need to shutdown the connection cleanly
// FIXME?
// add a finalizer method that calls shutdown
public boolean processMsg(CConnection cc) {
is = (FdInStream)cc.getInStream();
os = (FdOutStream)cc.getOutStream();
client = cc;
initGlobal();
if (manager == null) {
if (!is.checkNoWait(1))
return false;
if (is.readU8() == 0) {
int result = is.readU32();
String reason;
if (result == Security.secResultFailed ||
result == Security.secResultTooMany)
reason = is.readString();
else
reason = new String("Authentication failure (protocol error)");
throw new AuthFailureException(reason);
}
setParam();
}
try {
manager = new SSLEngineManager(engine, is, os);
manager.doHandshake();
} catch(java.lang.Exception e) {
throw new SystemException(e.toString());
}
cc.setStreams(new TLSInStream(is, manager),
new TLSOutStream(os, manager));
return true;
}
private void setParam() {
if (anon) {
try {
ctx.init(null, null, null);
} catch(KeyManagementException e) {
throw new AuthFailureException(e.toString());
}
} else {
try {
TrustManager[] myTM = new TrustManager[] {
new MyX509TrustManager()
};
ctx.init (null, myTM, null);
} catch (java.security.GeneralSecurityException e) {
throw new AuthFailureException(e.toString());
}
}
SSLSocketFactory sslfactory = ctx.getSocketFactory();
engine = ctx.createSSLEngine(client.getServerName(),
client.getServerPort());
engine.setUseClientMode(true);
String[] supported = engine.getSupportedProtocols();
ArrayList<String> enabled = new ArrayList<String>();
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS.*"))
enabled.add(supported[i]);
engine.setEnabledProtocols(enabled.toArray(new String[0]));
if (anon) {
supported = engine.getSupportedCipherSuites();
enabled = new ArrayList<String>();
// prefer ECDH over DHE
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_ECDH_anon.*"))
enabled.add(supported[i]);
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_DH_anon.*"))
enabled.add(supported[i]);
engine.setEnabledCipherSuites(enabled.toArray(new String[0]));
} else {
engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
}
}
class MyX509TrustManager implements X509TrustManager
{
X509TrustManager tm;
MyX509TrustManager() throws java.security.GeneralSecurityException
{
KeyStore ks = KeyStore.getInstance("JKS");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
try {
ks.load(null, null);
String a = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(a);
tmf.init((KeyStore)null);
for (TrustManager m : tmf.getTrustManagers())
if (m instanceof X509TrustManager)
for (X509Certificate c : ((X509TrustManager)m).getAcceptedIssuers())
ks.setCertificateEntry(getThumbprint((X509Certificate)c), c);
File cacert = new File(cafile);
if (cacert.exists() && cacert.canRead()) {
InputStream caStream = new MyFileInputStream(cacert);
Collection<? extends Certificate> cacerts =
cf.generateCertificates(caStream);
for (Certificate cert : cacerts) {
String thumbprint = getThumbprint((X509Certificate)cert);
ks.setCertificateEntry(thumbprint, (X509Certificate)cert);
}
}
PKIXBuilderParameters params =
new PKIXBuilderParameters(ks, new X509CertSelector());
File crlcert = new File(crlfile);
if (!crlcert.exists() || !crlcert.canRead()) {
params.setRevocationEnabled(false);
} else {
InputStream crlStream = new FileInputStream(crlfile);
Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
params.addCertStore(store);
params.setRevocationEnabled(true);
}
tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(new CertPathTrustManagerParameters(params));
tm = (X509TrustManager)tmf.getTrustManagers()[0];
} catch (java.lang.Exception e) {
throw new Exception(e.getMessage());
}
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
tm.checkClientTrusted(chain, authType);
}
private final char[] hexCode = "0123456789ABCDEF".toCharArray();
private String printHexBinary(byte[] data)
{
StringBuilder r = new StringBuilder(data.length*2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
Collection<? extends Certificate> certs = null;
X509Certificate cert = chain[0];
try {
cert.checkValidity();
} catch(CertificateNotYetValidException e) {
throw new AuthFailureException("server certificate has not been activated");
} catch(CertificateExpiredException e) {
if (!msg.showMsgBox(YES_NO_OPTION, "certificate has expired",
"The certificate of the server has expired, "+
"do you want to continue?"))
throw new AuthFailureException("server certificate has expired");
}
String thumbprint = getThumbprint(cert);
File vncDir = new File(FileUtils.getVncHomeDir());
File certFile = new File(vncDir, "x509_savedcerts.pem");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
if (vncDir.exists() && certFile.exists() && certFile.canRead()) {
InputStream certStream = new MyFileInputStream(certFile);
certs = cf.generateCertificates(certStream);
for (Certificate c : certs)
if (thumbprint.equals(getThumbprint((X509Certificate)c)))
return;
}
try {
verifyHostname(cert);
tm.checkServerTrusted(chain, authType);
} catch (java.lang.Exception e) {
if (e.getCause() instanceof CertPathBuilderException) {
String certinfo =
"This certificate has been signed by an unknown authority\n"+
"\n"+
" Subject: "+cert.getSubjectX500Principal().getName()+"\n"+
" Issuer: "+cert.getIssuerX500Principal().getName()+"\n"+
" Serial Number: "+cert.getSerialNumber()+"\n"+
" Version: "+cert.getVersion()+"\n"+
" Signature Algorithm: "+cert.getPublicKey().getAlgorithm()+"\n"+
" Not Valid Before: "+cert.getNotBefore()+"\n"+
" Not Valid After: "+cert.getNotAfter()+"\n"+
" SHA1 Fingerprint: "+getThumbprint(cert)+"\n"+
"\n"+
"Do you want to save it and continue?";
if (!msg.showMsgBox(YES_NO_OPTION, "certificate issuer unknown",
certinfo)) {
throw new AuthFailureException("certificate issuer unknown");
}
if (certs == null || !certs.contains(cert)) {
byte[] der = cert.getEncoded();
String pem = Base64.getEncoder().encodeToString(der);
pem = pem.replaceAll("(.{64})", "$1\n");
FileWriter fw = null;
try {
if (!vncDir.exists())
vncDir.mkdir();
if (!certFile.exists() && !certFile.createNewFile()) {
vlog.error("Certificate save failed.");
} else {
fw = new FileWriter(certFile.getAbsolutePath(), true);
fw.write("-----BEGIN CERTIFICATE-----\n");
fw.write(pem+"\n");
fw.write("-----END CERTIFICATE-----\n");
}
} catch (IOException ioe) {
msg.showMsgBox(OK_OPTION, "certificate save failed",
"Could not save the certificate");
} finally {
try {
if (fw != null)
fw.close();
} catch(IOException ioe2) {
throw new Exception(ioe2.getMessage());
}
}
}
} else {
throw new SystemException(e.getMessage());
}
}
}
public X509Certificate[] getAcceptedIssuers ()
{
return tm.getAcceptedIssuers();
}
private String getThumbprint(X509Certificate cert)
{
String thumbprint = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(cert.getEncoded());
thumbprint = printHexBinary(md.digest());
thumbprint = thumbprint.replaceAll("..(?!$)", "$0 ");
} catch(CertificateEncodingException e) {
throw new SystemException(e.getMessage());
} catch(NoSuchAlgorithmException e) {
throw new SystemException(e.getMessage());
}
return thumbprint;
}
private void verifyHostname(X509Certificate cert)
throws CertificateParsingException
{
try {
Collection sans = cert.getSubjectAlternativeNames();
if (sans == null) {
String dn = cert.getSubjectX500Principal().getName();
LdapName ln = new LdapName(dn);
for (Rdn rdn : ln.getRdns()) {
if (rdn.getType().equalsIgnoreCase("CN")) {
String peer = client.getServerName().toLowerCase();
if (peer.equals(((String)rdn.getValue()).toLowerCase()))
return;
}
}
} else {
Iterator i = sans.iterator();
while (i.hasNext()) {
List nxt = (List)i.next();
if (((Integer)nxt.get(0)).intValue() == 2) {
String peer = client.getServerName().toLowerCase();
if (peer.equals(((String)nxt.get(1)).toLowerCase()))
return;
} else if (((Integer)nxt.get(0)).intValue() == 7) {
String peer = ((CConn)client).getSocket().getPeerAddress();
if (peer.equals(((String)nxt.get(1)).toLowerCase()))
return;
}
}
}
Object[] answer = {"YES", "NO"};
int ret = JOptionPane.showOptionDialog(null,
"Hostname verification failed. Do you want to continue?",
"Hostname Verification Failure",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
null, answer, answer[0]);
if (ret != JOptionPane.YES_OPTION)
throw new WarningException("Hostname verification failed.");
} catch (CertificateParsingException e) {
throw new SystemException(e.getMessage());
} catch (InvalidNameException e) {
throw new SystemException(e.getMessage());
}
}
private class MyFileInputStream extends InputStream {
// Blank lines in a certificate file will cause Java 6 to throw a
// "DerInputStream.getLength(): lengthTag=127, too big" exception.
ByteBuffer buf;
public MyFileInputStream(String name) {
this(new File(name));
}
public MyFileInputStream(File file) {
StringBuffer sb = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String l;
while ((l = reader.readLine()) != null) {
if (l.trim().length() > 0 )
sb.append(l+"\n");
}
} catch (java.lang.Exception e) {
throw new Exception(e.toString());
} finally {
try {
if (reader != null)
reader.close();
} catch(IOException ioe) {
throw new Exception(ioe.getMessage());
}
}
Charset utf8 = Charset.forName("UTF-8");
buf = ByteBuffer.wrap(sb.toString().getBytes(utf8));
buf.limit(buf.capacity());
}
@Override
public int read(byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (!buf.hasRemaining())
return -1;
len = Math.min(len, buf.remaining());
buf.get(b, off, len);
return len;
}
@Override
public int read() throws IOException {
if (!buf.hasRemaining())
return -1;
return buf.get() & 0xFF;
}
}
}
public final int getType() { return anon ? Security.secTypeTLSNone : Security.secTypeX509None; }
public final String description()
{ return anon ? "TLS Encryption without VncAuth" : "X509 Encryption without VncAuth"; }
public boolean isSecure() { return !anon; }
protected CConnection client;
private SSLContext ctx;
private SSLEngine engine;
private SSLEngineManager manager;
private boolean anon;
private String cafile, crlfile;
private FdInStream is;
private FdOutStream os;
static LogWriter vlog = new LogWriter("CSecurityTLS");
}
|
./CrossVul/dataset_final_sorted/CWE-295/java/bad_4310_0
|
crossvul-java_data_bad_42_4
|
package org.bouncycastle.pqc.crypto.xmss;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;
/**
* Utils for XMSS implementation.
*/
public class XMSSUtil
{
/**
* Calculates the logarithm base 2 for a given Integer.
*
* @param n Number.
* @return Logarithm to base 2 of {@code n}.
*/
public static int log2(int n)
{
int log = 0;
while ((n >>= 1) != 0)
{
log++;
}
return log;
}
/**
* Convert int/long to n-byte array.
*
* @param value int/long value.
* @param sizeInByte Size of byte array in byte.
* @return int/long as big-endian byte array of size {@code sizeInByte}.
*/
public static byte[] toBytesBigEndian(long value, int sizeInByte)
{
byte[] out = new byte[sizeInByte];
for (int i = (sizeInByte - 1); i >= 0; i--)
{
out[i] = (byte)value;
value >>>= 8;
}
return out;
}
/*
* Copy long to byte array in big-endian at specific offset.
*/
public static void longToBigEndian(long value, byte[] in, int offset)
{
if (in == null)
{
throw new NullPointerException("in == null");
}
if ((in.length - offset) < 8)
{
throw new IllegalArgumentException("not enough space in array");
}
in[offset] = (byte)((value >> 56) & 0xff);
in[offset + 1] = (byte)((value >> 48) & 0xff);
in[offset + 2] = (byte)((value >> 40) & 0xff);
in[offset + 3] = (byte)((value >> 32) & 0xff);
in[offset + 4] = (byte)((value >> 24) & 0xff);
in[offset + 5] = (byte)((value >> 16) & 0xff);
in[offset + 6] = (byte)((value >> 8) & 0xff);
in[offset + 7] = (byte)((value) & 0xff);
}
/*
* Generic convert from big endian byte array to long.
*/
public static long bytesToXBigEndian(byte[] in, int offset, int size)
{
if (in == null)
{
throw new NullPointerException("in == null");
}
long res = 0;
for (int i = offset; i < (offset + size); i++)
{
res = (res << 8) | (in[i] & 0xff);
}
return res;
}
/**
* Clone a byte array.
*
* @param in byte array.
* @return Copy of byte array.
*/
public static byte[] cloneArray(byte[] in)
{
if (in == null)
{
throw new NullPointerException("in == null");
}
byte[] out = new byte[in.length];
for (int i = 0; i < in.length; i++)
{
out[i] = in[i];
}
return out;
}
/**
* Clone a 2d byte array.
*
* @param in 2d byte array.
* @return Copy of 2d byte array.
*/
public static byte[][] cloneArray(byte[][] in)
{
if (hasNullPointer(in))
{
throw new NullPointerException("in has null pointers");
}
byte[][] out = new byte[in.length][];
for (int i = 0; i < in.length; i++)
{
out[i] = new byte[in[i].length];
for (int j = 0; j < in[i].length; j++)
{
out[i][j] = in[i][j];
}
}
return out;
}
/**
* Compares two 2d-byte arrays.
*
* @param a 2d-byte array 1.
* @param b 2d-byte array 2.
* @return true if all values in 2d-byte array are equal false else.
*/
public static boolean areEqual(byte[][] a, byte[][] b)
{
if (hasNullPointer(a) || hasNullPointer(b))
{
throw new NullPointerException("a or b == null");
}
for (int i = 0; i < a.length; i++)
{
if (!Arrays.areEqual(a[i], b[i]))
{
return false;
}
}
return true;
}
/**
* Dump content of 2d byte array.
*
* @param x byte array.
*/
public static void dumpByteArray(byte[][] x)
{
if (hasNullPointer(x))
{
throw new NullPointerException("x has null pointers");
}
for (int i = 0; i < x.length; i++)
{
System.out.println(Hex.toHexString(x[i]));
}
}
/**
* Checks whether 2d byte array has null pointers.
*
* @param in 2d byte array.
* @return true if at least one null pointer is found false else.
*/
public static boolean hasNullPointer(byte[][] in)
{
if (in == null)
{
return true;
}
for (int i = 0; i < in.length; i++)
{
if (in[i] == null)
{
return true;
}
}
return false;
}
/**
* Copy src byte array to dst byte array at offset.
*
* @param dst Destination.
* @param src Source.
* @param offset Destination offset.
*/
public static void copyBytesAtOffset(byte[] dst, byte[] src, int offset)
{
if (dst == null)
{
throw new NullPointerException("dst == null");
}
if (src == null)
{
throw new NullPointerException("src == null");
}
if (offset < 0)
{
throw new IllegalArgumentException("offset hast to be >= 0");
}
if ((src.length + offset) > dst.length)
{
throw new IllegalArgumentException("src length + offset must not be greater than size of destination");
}
for (int i = 0; i < src.length; i++)
{
dst[offset + i] = src[i];
}
}
/**
* Copy length bytes at position offset from src.
*
* @param src Source byte array.
* @param offset Offset in source byte array.
* @param length Length of bytes to copy.
* @return New byte array.
*/
public static byte[] extractBytesAtOffset(byte[] src, int offset, int length)
{
if (src == null)
{
throw new NullPointerException("src == null");
}
if (offset < 0)
{
throw new IllegalArgumentException("offset hast to be >= 0");
}
if (length < 0)
{
throw new IllegalArgumentException("length hast to be >= 0");
}
if ((offset + length) > src.length)
{
throw new IllegalArgumentException("offset + length must not be greater then size of source array");
}
byte[] out = new byte[length];
for (int i = 0; i < out.length; i++)
{
out[i] = src[offset + i];
}
return out;
}
/**
* Check whether an index is valid or not.
*
* @param height Height of binary tree.
* @param index Index to validate.
* @return true if index is valid false else.
*/
public static boolean isIndexValid(int height, long index)
{
if (index < 0)
{
throw new IllegalStateException("index must not be negative");
}
return index < (1L << height);
}
/**
* Determine digest size of digest.
*
* @param digest Digest.
* @return Digest size.
*/
public static int getDigestSize(Digest digest)
{
if (digest == null)
{
throw new NullPointerException("digest == null");
}
String algorithmName = digest.getAlgorithmName();
if (algorithmName.equals("SHAKE128"))
{
return 32;
}
if (algorithmName.equals("SHAKE256"))
{
return 64;
}
return digest.getDigestSize();
}
public static long getTreeIndex(long index, int xmssTreeHeight)
{
return index >> xmssTreeHeight;
}
public static int getLeafIndex(long index, int xmssTreeHeight)
{
return (int)(index & ((1L << xmssTreeHeight) - 1L));
}
public static byte[] serialize(Object obj)
throws IOException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(obj);
oos.flush();
return out.toByteArray();
}
public static Object deserialize(byte[] data)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
public static int calculateTau(int index, int height)
{
int tau = 0;
for (int i = 0; i < height; i++)
{
if (((index >> i) & 1) == 0)
{
tau = i;
break;
}
}
return tau;
}
public static boolean isNewBDSInitNeeded(long globalIndex, int xmssHeight, int layer)
{
if (globalIndex == 0)
{
return false;
}
return (globalIndex % (long)Math.pow((1 << xmssHeight), layer + 1) == 0) ? true : false;
}
public static boolean isNewAuthenticationPathNeeded(long globalIndex, int xmssHeight, int layer)
{
if (globalIndex == 0)
{
return false;
}
return ((globalIndex + 1) % (long)Math.pow((1 << xmssHeight), layer) == 0) ? true : false;
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_4
|
crossvul-java_data_bad_1893_5
|
package io.onedev.server.product;
import java.util.EnumSet;
import javax.inject.Inject;
import javax.servlet.DispatcherType;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.shiro.web.env.EnvironmentLoader;
import org.apache.shiro.web.env.EnvironmentLoaderListener;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.apache.wicket.protocol.http.WicketServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;
import io.onedev.commons.launcher.bootstrap.Bootstrap;
import io.onedev.server.git.GitFilter;
import io.onedev.server.git.hookcallback.GitPostReceiveCallback;
import io.onedev.server.git.hookcallback.GitPreReceiveCallback;
import io.onedev.server.security.DefaultWebEnvironment;
import io.onedev.server.util.ServerConfig;
import io.onedev.server.util.jetty.ClasspathAssetServlet;
import io.onedev.server.util.jetty.FileAssetServlet;
import io.onedev.server.util.jetty.ServletConfigurator;
import io.onedev.server.web.asset.icon.IconScope;
import io.onedev.server.web.component.markdown.AttachmentUploadServlet;
import io.onedev.server.web.img.ImageScope;
import io.onedev.server.web.websocket.WebSocketManager;
public class ProductServletConfigurator implements ServletConfigurator {
private final ServerConfig serverConfig;
private final ShiroFilter shiroFilter;
private final GitFilter gitFilter;
private final GitPreReceiveCallback preReceiveServlet;
private final GitPostReceiveCallback postReceiveServlet;
private final WicketServlet wicketServlet;
private final AttachmentUploadServlet attachmentUploadServlet;
private final ServletContainer jerseyServlet;
private final WebSocketManager webSocketManager;
@Inject
public ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter,
GitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet,
WicketServlet wicketServlet, WebSocketManager webSocketManager,
AttachmentUploadServlet attachmentUploadServlet, ServletContainer jerseyServlet) {
this.serverConfig = serverConfig;
this.shiroFilter = shiroFilter;
this.gitFilter = gitFilter;
this.preReceiveServlet = preReceiveServlet;
this.postReceiveServlet = postReceiveServlet;
this.wicketServlet = wicketServlet;
this.webSocketManager = webSocketManager;
this.jerseyServlet = jerseyServlet;
this.attachmentUploadServlet = attachmentUploadServlet;
}
@Override
public void configure(ServletContextHandler context) {
context.setContextPath("/");
context.getSessionHandler().setMaxInactiveInterval(serverConfig.getSessionTimeout());
context.setInitParameter(EnvironmentLoader.ENVIRONMENT_CLASS_PARAM, DefaultWebEnvironment.class.getName());
context.addEventListener(new EnvironmentLoaderListener());
context.addFilter(new FilterHolder(shiroFilter), "/*", EnumSet.allOf(DispatcherType.class));
context.addFilter(new FilterHolder(gitFilter), "/*", EnumSet.allOf(DispatcherType.class));
context.addServlet(new ServletHolder(preReceiveServlet), GitPreReceiveCallback.PATH + "/*");
context.addServlet(new ServletHolder(postReceiveServlet), GitPostReceiveCallback.PATH + "/*");
/*
* Add wicket servlet as the default servlet which will serve all requests failed to
* match a path pattern
*/
context.addServlet(new ServletHolder(wicketServlet), "/");
context.addServlet(new ServletHolder(attachmentUploadServlet), "/attachment_upload");
context.addServlet(new ServletHolder(new ClasspathAssetServlet(ImageScope.class)), "/img/*");
context.addServlet(new ServletHolder(new ClasspathAssetServlet(IconScope.class)), "/icon/*");
context.getSessionHandler().addEventListener(new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
webSocketManager.onDestroySession(se.getSession().getId());
}
});
/*
* Configure a servlet to serve contents under site folder. Site folder can be used
* to hold site specific web assets.
*/
ServletHolder fileServletHolder = new ServletHolder(new FileAssetServlet(Bootstrap.getSiteDir()));
context.addServlet(fileServletHolder, "/site/*");
context.addServlet(fileServletHolder, "/robots.txt");
context.addServlet(new ServletHolder(jerseyServlet), "/rest/*");
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_1893_5
|
crossvul-java_data_good_662_0
|
/**
* Copyright (c) 2004-2011 QOS.ch
* 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, 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.
*
*/
package org.slf4j.ext;
import java.io.Serializable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.beans.ExceptionListener;
/**
* Base class for Event Data. Event Data contains data to be logged about an
* event. Users may extend this class for each EventType they want to log.
*
* @author Ralph Goers
*
* @deprecated Due to a security vulnerability, this class will be removed without replacement.
*/
public class EventData implements Serializable {
private static final long serialVersionUID = 153270778642103985L;
private Map<String, Object> eventData = new HashMap<String, Object>();
public static final String EVENT_MESSAGE = "EventMessage";
public static final String EVENT_TYPE = "EventType";
public static final String EVENT_DATETIME = "EventDateTime";
public static final String EVENT_ID = "EventId";
/**
* Default Constructor
*/
public EventData() {
}
/**
* Constructor to create event data from a Map.
*
* @param map
* The event data.
*/
public EventData(Map<String, Object> map) {
eventData.putAll(map);
}
/**
* Construct from a serialized form of the Map containing the RequestInfo
* elements
*
* @param xml
* The serialized form of the RequestInfo Map.
*/
@SuppressWarnings("unchecked")
public EventData(String xml) {
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
try {
XMLDecoder decoder = new XMLDecoder(bais);
this.eventData = (Map<String, Object>) decoder.readObject();
} catch (Exception e) {
throw new EventException("Error decoding " + xml, e);
}
}
/**
* Serialize all the EventData items into an XML representation.
*
* @return an XML String containing all the EventData items.
*/
public String toXML() {
return toXML(eventData);
}
/**
* Serialize all the EventData items into an XML representation.
*
* @param map the Map to transform
* @return an XML String containing all the EventData items.
*/
public static String toXML(Map<String, Object> map) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
XMLEncoder encoder = new XMLEncoder(baos);
encoder.setExceptionListener(new ExceptionListener() {
public void exceptionThrown(Exception exception) {
exception.printStackTrace();
}
});
encoder.writeObject(map);
encoder.close();
return baos.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Retrieve the event identifier.
*
* @return The event identifier
*/
public String getEventId() {
return (String) this.eventData.get(EVENT_ID);
}
/**
* Set the event identifier.
*
* @param eventId
* The event identifier.
*/
public void setEventId(String eventId) {
if (eventId == null) {
throw new IllegalArgumentException("eventId cannot be null");
}
this.eventData.put(EVENT_ID, eventId);
}
/**
* Retrieve the message text associated with this event, if any.
*
* @return The message text associated with this event or null if there is
* none.
*/
public String getMessage() {
return (String) this.eventData.get(EVENT_MESSAGE);
}
/**
* Set the message text associated with this event.
*
* @param message
* The message text.
*/
public void setMessage(String message) {
this.eventData.put(EVENT_MESSAGE, message);
}
/**
* Retrieve the date and time the event occurred.
*
* @return The Date associated with the event.
*/
public Date getEventDateTime() {
return (Date) this.eventData.get(EVENT_DATETIME);
}
/**
* Set the date and time the event occurred in case it is not the same as when
* the event was logged.
*
* @param eventDateTime
* The event Date.
*/
public void setEventDateTime(Date eventDateTime) {
this.eventData.put(EVENT_DATETIME, eventDateTime);
}
/**
* Set the type of event that occurred.
*
* @param eventType
* The type of the event.
*/
public void setEventType(String eventType) {
this.eventData.put(EVENT_TYPE, eventType);
}
/**
* Retrieve the type of the event.
*
* @return The event type.
*/
public String getEventType() {
return (String) this.eventData.get(EVENT_TYPE);
}
/**
* Add arbitrary attributes about the event.
*
* @param name
* The attribute's key.
* @param obj
* The data associated with the key.
*/
public void put(String name, Serializable obj) {
this.eventData.put(name, obj);
}
/**
* Retrieve an event attribute.
*
* @param name
* The attribute's key.
* @return The value associated with the key or null if the key is not
* present.
*/
public Serializable get(String name) {
return (Serializable) this.eventData.get(name);
}
/**
* Populate the event data from a Map.
*
* @param data
* The Map to copy.
*/
public void putAll(Map<String, Object> data) {
this.eventData.putAll(data);
}
/**
* Returns the number of attributes in the EventData.
*
* @return the number of attributes in the EventData.
*/
public int getSize() {
return this.eventData.size();
}
/**
* Returns an Iterator over all the entries in the EventData.
*
* @return an Iterator that can be used to access all the event attributes.
*/
public Iterator<Map.Entry<String, Object>> getEntrySetIterator() {
return this.eventData.entrySet().iterator();
}
/**
* Retrieve all the attributes in the EventData as a Map. Changes to this map
* will be reflected in the EventData.
*
* @return The Map of attributes in this EventData instance.
*/
public Map<String, Object> getEventMap() {
return this.eventData;
}
/**
* Convert the EventData to a String.
*
* @return The EventData as a String.
*/
@Override
public String toString() {
return toXML();
}
/**
* Compare two EventData objects for equality.
*
* @param o
* The Object to compare.
* @return true if the objects are the same instance or contain all the same
* keys and their values.
*/
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EventData || o instanceof Map)) {
return false;
}
Map<String, Object> map = (o instanceof EventData) ? ((EventData) o).getEventMap() : (Map<String, Object>) o;
return this.eventData.equals(map);
}
/**
* Compute the hashCode for this EventData instance.
*
* @return The hashcode for this EventData instance.
*/
@Override
public int hashCode() {
return this.eventData.hashCode();
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_662_0
|
crossvul-java_data_bad_590_3
|
/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import static org.hamcrest.junit.MatcherAssert.assertThat;
import static org.junit.Assume.assumeTrue;
import com.facebook.buck.apple.AppleNativeIntegrationTestUtils;
import com.facebook.buck.apple.toolchain.ApplePlatform;
import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestContext;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.NamedTemporaryFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
public class ParserCacheCommandIntegrationTest {
@Rule public TemporaryPaths tmp = new TemporaryPaths();
@Test
public void testSaveAndLoad() throws IOException {
assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp);
workspace.setUp();
// Warm the parser cache.
TestContext context = new TestContext();
ProcessResult runBuckResult =
workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)");
runBuckResult.assertSuccess();
assertThat(
runBuckResult.getStdout(),
Matchers.containsString(
"//Apps:TestAppsLibrary\n"
+ "//Libraries/Dep1:Dep1_1\n"
+ "//Libraries/Dep1:Dep1_2\n"
+ "bar//Dep2:Dep2"));
// Save the parser cache to a file.
NamedTemporaryFile tempFile = new NamedTemporaryFile("parser_data", null);
runBuckResult =
workspace.runBuckdCommand(context, "parser-cache", "--save", tempFile.get().toString());
runBuckResult.assertSuccess();
// Write an empty content to Apps/BUCK.
Path path = tmp.getRoot().resolve("Apps/BUCK");
byte[] data = {};
Files.write(path, data);
context = new TestContext();
// Load the parser cache to a new buckd context.
runBuckResult =
workspace.runBuckdCommand(context, "parser-cache", "--load", tempFile.get().toString());
runBuckResult.assertSuccess();
// Perform the query again. If we didn't load the parser cache, this call would fail because
// Apps/BUCK is empty.
runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)");
runBuckResult.assertSuccess();
assertThat(
runBuckResult.getStdout(),
Matchers.containsString(
"//Apps:TestAppsLibrary\n"
+ "//Libraries/Dep1:Dep1_1\n"
+ "//Libraries/Dep1:Dep1_2\n"
+ "bar//Dep2:Dep2"));
}
@Test
public void testInvalidate() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp);
workspace.setUp();
// Warm the parser cache.
TestContext context = new TestContext();
ProcessResult runBuckResult =
workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)");
runBuckResult.assertSuccess();
assertThat(
runBuckResult.getStdout(),
Matchers.containsString(
"//Apps:TestAppsLibrary\n"
+ "//Libraries/Dep1:Dep1_1\n"
+ "//Libraries/Dep1:Dep1_2\n"
+ "bar//Dep2:Dep2"));
// Save the parser cache to a file.
NamedTemporaryFile tempFile = new NamedTemporaryFile("parser_data", null);
runBuckResult =
workspace.runBuckdCommand(context, "parser-cache", "--save", tempFile.get().toString());
runBuckResult.assertSuccess();
// Write an empty content to Apps/BUCK.
Path path = tmp.getRoot().resolve("Apps/BUCK");
byte[] data = {};
Files.write(path, data);
// Write an empty content to Apps/BUCK.
Path invalidationJsonPath = tmp.getRoot().resolve("invalidation-data.json");
String jsonData = "[{\"path\":\"Apps/BUCK\",\"status\":\"M\"}]";
Files.write(invalidationJsonPath, jsonData.getBytes(StandardCharsets.UTF_8));
context = new TestContext();
// Load the parser cache to a new buckd context.
runBuckResult =
workspace.runBuckdCommand(
context,
"parser-cache",
"--load",
tempFile.get().toString(),
"--changes",
invalidationJsonPath.toString());
runBuckResult.assertSuccess();
// Perform the query again.
try {
workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)");
} catch (HumanReadableException e) {
assertThat(
e.getMessage(), Matchers.containsString("//Apps:TestAppsLibrary could not be found"));
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_590_3
|
crossvul-java_data_good_1893_3
|
package io.onedev.server.web.component.markdown;
import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxChannel;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.FormComponentPanel;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unbescape.javascript.JavaScriptEscape;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import io.onedev.commons.launcher.loader.AppLoader;
import io.onedev.server.OneDev;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.model.Build;
import io.onedev.server.model.Issue;
import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.User;
import io.onedev.server.util.markdown.MarkdownManager;
import io.onedev.server.util.validation.ProjectNameValidator;
import io.onedev.server.web.avatar.AvatarManager;
import io.onedev.server.web.behavior.AbstractPostAjaxBehavior;
import io.onedev.server.web.component.floating.FloatingPanel;
import io.onedev.server.web.component.link.DropdownLink;
import io.onedev.server.web.component.markdown.emoji.EmojiOnes;
import io.onedev.server.web.component.modal.ModalPanel;
import io.onedev.server.web.page.project.ProjectPage;
import io.onedev.server.web.page.project.blob.render.BlobRenderContext;
@SuppressWarnings("serial")
public class MarkdownEditor extends FormComponentPanel<String> {
protected static final int ATWHO_LIMIT = 10;
private static final Logger logger = LoggerFactory.getLogger(MarkdownEditor.class);
private final boolean compactMode;
private final boolean initialSplit;
private final BlobRenderContext blobRenderContext;
private WebMarkupContainer container;
private TextArea<String> input;
private AbstractPostAjaxBehavior actionBehavior;
private AbstractPostAjaxBehavior attachmentUploadBehavior;
/**
* @param id
* component id of the editor
* @param model
* markdown model of the editor
* @param compactMode
* editor in compact mode occupies horizontal space and is suitable
* to be used in places such as comment aside the code
*/
public MarkdownEditor(String id, IModel<String> model, boolean compactMode,
@Nullable BlobRenderContext blobRenderContext) {
super(id, model);
this.compactMode = compactMode;
String cookieKey;
if (compactMode)
cookieKey = "markdownEditor.compactMode.split";
else
cookieKey = "markdownEditor.normalMode.split";
WebRequest request = (WebRequest) RequestCycle.get().getRequest();
Cookie cookie = request.getCookie(cookieKey);
initialSplit = cookie!=null && "true".equals(cookie.getValue());
this.blobRenderContext = blobRenderContext;
}
@Override
protected void onModelChanged() {
super.onModelChanged();
input.setModelObject(getModelObject());
}
public void clearMarkdown() {
setModelObject("");
input.setConvertedInput(null);
}
private String renderInput(String input) {
if (StringUtils.isNotBlank(input)) {
// Normalize line breaks to make source position tracking information comparable
// to textarea caret position when sync edit/preview scroll bar
input = StringUtils.replace(input, "\r\n", "\n");
return renderMarkdown(input);
} else {
return "<div class='message'>Nothing to preview</div>";
}
}
protected String renderMarkdown(String markdown) {
Project project ;
if (getPage() instanceof ProjectPage)
project = ((ProjectPage) getPage()).getProject();
else
project = null;
MarkdownManager manager = OneDev.getInstance(MarkdownManager.class);
return manager.process(manager.render(markdown), project, blobRenderContext);
}
@Override
protected void onInitialize() {
super.onInitialize();
container = new WebMarkupContainer("container");
container.setOutputMarkupId(true);
add(container);
WebMarkupContainer editLink = new WebMarkupContainer("editLink");
WebMarkupContainer splitLink = new WebMarkupContainer("splitLink");
WebMarkupContainer preview = new WebMarkupContainer("preview");
WebMarkupContainer edit = new WebMarkupContainer("edit");
container.add(editLink);
container.add(splitLink);
container.add(preview);
container.add(edit);
container.add(AttributeAppender.append("class", compactMode?"compact-mode":"normal-mode"));
container.add(new DropdownLink("doReference") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new Fragment(id, "referenceMenuFrag", MarkdownEditor.this) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.setupActionMenu($('#%s'), $('#%s'));",
container.getMarkupId(), getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setOutputMarkupId(true);
}
}.setVisible(getReferenceSupport() != null));
container.add(new DropdownLink("actionMenuTrigger") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new Fragment(id, "actionMenuFrag", MarkdownEditor.this) {
@Override
protected void onInitialize() {
super.onInitialize();
add(new WebMarkupContainer("doMention").setVisible(getUserMentionSupport() != null));
if (getReferenceSupport() != null)
add(new Fragment("doReference", "referenceMenuFrag", MarkdownEditor.this));
else
add(new WebMarkupContainer("doReference").setVisible(false));
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.setupActionMenu($('#%s'), $('#%s'));",
container.getMarkupId(), getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setOutputMarkupId(true);
}
});
container.add(new WebMarkupContainer("doMention").setVisible(getUserMentionSupport() != null));
edit.add(input = new TextArea<String>("input", Model.of(getModelObject())));
for (AttributeModifier modifier: getInputModifiers())
input.add(modifier);
if (initialSplit) {
container.add(AttributeAppender.append("class", "split-mode"));
preview.add(new Label("rendered", new LoadableDetachableModel<String>() {
@Override
protected String load() {
return renderInput(input.getConvertedInput());
}
}) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format(
"onedev.server.markdown.initRendered($('#%s>.body>.preview>.markdown-rendered'));",
container.getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setEscapeModelStrings(false));
splitLink.add(AttributeAppender.append("class", "active"));
} else {
container.add(AttributeAppender.append("class", "edit-mode"));
preview.add(new WebMarkupContainer("rendered"));
editLink.add(AttributeAppender.append("class", "active"));
}
container.add(new WebMarkupContainer("canAttachFile").setVisible(getAttachmentSupport()!=null));
container.add(actionBehavior = new AbstractPostAjaxBehavior() {
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.setChannel(new AjaxChannel("markdown-preview", AjaxChannel.Type.DROP));
}
@Override
protected void respond(AjaxRequestTarget target) {
IRequestParameters params = RequestCycle.get().getRequest().getPostParameters();
String action = params.getParameterValue("action").toString("");
switch (action) {
case "render":
String markdown = params.getParameterValue("param1").toString();
String rendered = renderInput(markdown);
String script = String.format("onedev.server.markdown.onRendered('%s', '%s');",
container.getMarkupId(), JavaScriptEscape.escapeJavaScript(rendered));
target.appendJavaScript(script);
break;
case "emojiQuery":
List<String> emojiNames = new ArrayList<>();
String emojiQuery = params.getParameterValue("param1").toOptionalString();
if (StringUtils.isNotBlank(emojiQuery)) {
emojiQuery = emojiQuery.toLowerCase();
for (String emojiName: EmojiOnes.getInstance().all().keySet()) {
if (emojiName.toLowerCase().contains(emojiQuery))
emojiNames.add(emojiName);
}
emojiNames.sort((name1, name2) -> name1.length() - name2.length());
} else {
emojiNames.add("smile");
emojiNames.add("worried");
emojiNames.add("blush");
emojiNames.add("+1");
emojiNames.add("-1");
}
List<Map<String, String>> emojis = new ArrayList<>();
for (String emojiName: emojiNames) {
if (emojis.size() < ATWHO_LIMIT) {
String emojiCode = EmojiOnes.getInstance().all().get(emojiName);
CharSequence url = RequestCycle.get().urlFor(new PackageResourceReference(
EmojiOnes.class, "icon/" + emojiCode + ".png"), new PageParameters());
Map<String, String> emoji = new HashMap<>();
emoji.put("name", emojiName);
emoji.put("url", url.toString());
emojis.add(emoji);
}
}
String json;
try {
json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(emojis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoEmojiRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "loadEmojis":
emojis = new ArrayList<>();
String urlPattern = RequestCycle.get().urlFor(new PackageResourceReference(EmojiOnes.class,
"icon/FILENAME.png"), new PageParameters()).toString();
for (Map.Entry<String, String> entry: EmojiOnes.getInstance().all().entrySet()) {
Map<String, String> emoji = new HashMap<>();
emoji.put("name", entry.getKey());
emoji.put("url", urlPattern.replace("FILENAME", entry.getValue()));
emojis.add(emoji);
}
try {
json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(emojis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("onedev.server.markdown.onEmojisLoaded('%s', %s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "userQuery":
String userQuery = params.getParameterValue("param1").toOptionalString();
AvatarManager avatarManager = OneDev.getInstance(AvatarManager.class);
List<Map<String, String>> userList = new ArrayList<>();
for (User user: getUserMentionSupport().findUsers(userQuery, ATWHO_LIMIT)) {
Map<String, String> userMap = new HashMap<>();
userMap.put("name", user.getName());
if (user.getFullName() != null)
userMap.put("fullName", user.getFullName());
String noSpaceName = StringUtils.deleteWhitespace(user.getName());
if (user.getFullName() != null) {
String noSpaceFullName = StringUtils.deleteWhitespace(user.getFullName());
userMap.put("searchKey", noSpaceName + " " + noSpaceFullName);
} else {
userMap.put("searchKey", noSpaceName);
}
String avatarUrl = avatarManager.getAvatarUrl(user);
userMap.put("avatarUrl", avatarUrl);
userList.add(userMap);
}
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(userList);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoUserRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "referenceQuery":
String referenceQuery = params.getParameterValue("param1").toOptionalString();
String referenceQueryType = params.getParameterValue("param2").toOptionalString();
String referenceProjectName = params.getParameterValue("param3").toOptionalString();
List<Map<String, String>> referenceList = new ArrayList<>();
Project referenceProject;
if (StringUtils.isNotBlank(referenceProjectName))
referenceProject = OneDev.getInstance(ProjectManager.class).find(referenceProjectName);
else
referenceProject = null;
if (referenceProject != null || StringUtils.isBlank(referenceProjectName)) {
if ("issue".equals(referenceQueryType)) {
for (Issue issue: getReferenceSupport().findIssues(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "issue");
referenceMap.put("referenceNumber", String.valueOf(issue.getNumber()));
referenceMap.put("referenceTitle", issue.getTitle());
referenceMap.put("searchKey", issue.getNumber() + " " + StringUtils.deleteWhitespace(issue.getTitle()));
referenceList.add(referenceMap);
}
} else if ("pullrequest".equals(referenceQueryType)) {
for (PullRequest request: getReferenceSupport().findPullRequests(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "pull request");
referenceMap.put("referenceNumber", String.valueOf(request.getNumber()));
referenceMap.put("referenceTitle", request.getTitle());
referenceMap.put("searchKey", request.getNumber() + " " + StringUtils.deleteWhitespace(request.getTitle()));
referenceList.add(referenceMap);
}
} else if ("build".equals(referenceQueryType)) {
for (Build build: getReferenceSupport().findBuilds(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "build");
referenceMap.put("referenceNumber", String.valueOf(build.getNumber()));
String title;
if (build.getVersion() != null)
title = "(" + build.getVersion() + ") " + build.getJobName();
else
title = build.getJobName();
referenceMap.put("referenceTitle", title);
referenceMap.put("searchKey", build.getNumber() + " " + StringUtils.deleteWhitespace(title));
referenceList.add(referenceMap);
}
}
}
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(referenceList);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoReferenceRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "selectImage":
case "selectLink":
new ModalPanel(target) {
@Override
protected Component newContent(String id) {
return new InsertUrlPanel(id, MarkdownEditor.this, action.equals("selectImage")) {
@Override
protected void onClose(AjaxRequestTarget target) {
close();
}
};
}
@Override
protected void onClosed() {
super.onClosed();
AjaxRequestTarget target =
Preconditions.checkNotNull(RequestCycle.get().find(AjaxRequestTarget.class));
target.appendJavaScript(String.format("$('#%s textarea').focus();", container.getMarkupId()));
}
};
break;
case "insertUrl":
String name;
try {
name = URLDecoder.decode(params.getParameterValue("param1").toString(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String replaceMessage = params.getParameterValue("param2").toString();
String url = getAttachmentSupport().getAttachmentUrl(name);
insertUrl(target, isWebSafeImage(name), url, name, replaceMessage);
break;
default:
throw new IllegalStateException("Unknown action: " + action);
}
}
});
container.add(attachmentUploadBehavior = new AbstractPostAjaxBehavior() {
@Override
protected void respond(AjaxRequestTarget target) {
Preconditions.checkNotNull(getAttachmentSupport(), "Unexpected attachment upload request");
HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
HttpServletResponse response = (HttpServletResponse) RequestCycle.get().getResponse().getContainerResponse();
try {
String fileName = URLDecoder.decode(request.getHeader("File-Name"), StandardCharsets.UTF_8.name());
String attachmentName = getAttachmentSupport().saveAttachment(fileName, request.getInputStream());
response.getWriter().print(URLEncoder.encode(attachmentName, StandardCharsets.UTF_8.name()));
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
logger.error("Error uploading attachment.", e);
try {
if (e.getMessage() != null)
response.getWriter().print(e.getMessage());
else
response.getWriter().print("Internal server error");
} catch (IOException e2) {
throw new RuntimeException(e2);
}
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
});
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
}
@Override
public void convertInput() {
setConvertedInput(input.getConvertedInput());
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forReference(new MarkdownResourceReference()));
String actionCallback = actionBehavior.getCallbackFunction(explicit("action"), explicit("param1"), explicit("param2"),
explicit("param3")).toString();
String attachmentUploadUrl = attachmentUploadBehavior.getCallbackUrl().toString();
String autosaveKey = getAutosaveKey();
if (autosaveKey != null)
autosaveKey = "'" + JavaScriptEscape.escapeJavaScript(autosaveKey) + "'";
else
autosaveKey = "undefined";
String script = String.format("onedev.server.markdown.onDomReady('%s', %s, %d, %s, %d, %b, %b, '%s', %s);",
container.getMarkupId(),
actionCallback,
ATWHO_LIMIT,
getAttachmentSupport()!=null? "'" + attachmentUploadUrl + "'": "undefined",
getAttachmentSupport()!=null? getAttachmentSupport().getAttachmentMaxSize(): 0,
getUserMentionSupport() != null,
getReferenceSupport() != null,
JavaScriptEscape.escapeJavaScript(ProjectNameValidator.PATTERN.pattern()),
autosaveKey);
response.render(OnDomReadyHeaderItem.forScript(script));
script = String.format("onedev.server.markdown.onLoad('%s');", container.getMarkupId());
response.render(OnLoadHeaderItem.forScript(script));
}
public void insertUrl(AjaxRequestTarget target, boolean isImage, String url,
String name, @Nullable String replaceMessage) {
String script = String.format("onedev.server.markdown.insertUrl('%s', %s, '%s', '%s', %s);",
container.getMarkupId(), isImage, StringEscapeUtils.escapeEcmaScript(url),
StringEscapeUtils.escapeEcmaScript(name),
replaceMessage!=null?"'"+replaceMessage+"'":"undefined");
target.appendJavaScript(script);
}
public boolean isWebSafeImage(String fileName) {
fileName = fileName.toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
|| fileName.endsWith(".gif") || fileName.endsWith(".png");
}
@Nullable
protected AttachmentSupport getAttachmentSupport() {
return null;
}
@Nullable
protected UserMentionSupport getUserMentionSupport() {
return null;
}
@Nullable
protected AtWhoReferenceSupport getReferenceSupport() {
return null;
}
protected List<AttributeModifier> getInputModifiers() {
return new ArrayList<>();
}
@Nullable
protected String getAutosaveKey() {
return null;
}
@Nullable
public BlobRenderContext getBlobRenderContext() {
return blobRenderContext;
}
static class ReferencedEntity implements Serializable {
String entityType;
String entityTitle;
String entityNumber;
String searchKey;
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_1893_3
|
crossvul-java_data_good_42_0
|
package org.bouncycastle.pqc.crypto.gmss;
import java.security.SecureRandom;
import java.util.Vector;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.pqc.crypto.gmss.util.GMSSRandom;
import org.bouncycastle.pqc.crypto.gmss.util.WinternitzOTSVerify;
import org.bouncycastle.pqc.crypto.gmss.util.WinternitzOTSignature;
/**
* This class implements key pair generation of the generalized Merkle signature
* scheme (GMSS).
*
* @see GMSSSigner
*/
public class GMSSKeyPairGenerator
implements AsymmetricCipherKeyPairGenerator
{
/**
* The source of randomness for OTS private key generation
*/
private GMSSRandom gmssRandom;
/**
* The hash function used for the construction of the authentication trees
*/
private Digest messDigestTree;
/**
* An array of the seeds for the PRGN (for main tree, and all current
* subtrees)
*/
private byte[][] currentSeeds;
/**
* An array of seeds for the PRGN (for all subtrees after next)
*/
private byte[][] nextNextSeeds;
/**
* An array of the RootSignatures
*/
private byte[][] currentRootSigs;
/**
* Class of hash function to use
*/
private GMSSDigestProvider digestProvider;
/**
* The length of the seed for the PRNG
*/
private int mdLength;
/**
* the number of Layers
*/
private int numLayer;
/**
* Flag indicating if the class already has been initialized
*/
private boolean initialized = false;
/**
* Instance of GMSSParameterset
*/
private GMSSParameters gmssPS;
/**
* An array of the heights of the authentication trees of each layer
*/
private int[] heightOfTrees;
/**
* An array of the Winternitz parameter 'w' of each layer
*/
private int[] otsIndex;
/**
* The parameter K needed for the authentication path computation
*/
private int[] K;
private GMSSKeyGenerationParameters gmssParams;
/**
* The GMSS OID.
*/
public static final String OID = "1.3.6.1.4.1.8301.3.1.3.3";
/**
* The standard constructor tries to generate the GMSS algorithm identifier
* with the corresponding OID.
*
* @param digestProvider provider for digest implementations.
*/
public GMSSKeyPairGenerator(GMSSDigestProvider digestProvider)
{
this.digestProvider = digestProvider;
messDigestTree = digestProvider.get();
// set mdLength
this.mdLength = messDigestTree.getDigestSize();
// construct randomizer
this.gmssRandom = new GMSSRandom(messDigestTree);
}
/**
* Generates the GMSS key pair. The public key is an instance of
* JDKGMSSPublicKey, the private key is an instance of JDKGMSSPrivateKey.
*
* @return Key pair containing a JDKGMSSPublicKey and a JDKGMSSPrivateKey
*/
private AsymmetricCipherKeyPair genKeyPair()
{
if (!initialized)
{
initializeDefault();
}
// initialize authenticationPaths and treehash instances
byte[][][] currentAuthPaths = new byte[numLayer][][];
byte[][][] nextAuthPaths = new byte[numLayer - 1][][];
Treehash[][] currentTreehash = new Treehash[numLayer][];
Treehash[][] nextTreehash = new Treehash[numLayer - 1][];
Vector[] currentStack = new Vector[numLayer];
Vector[] nextStack = new Vector[numLayer - 1];
Vector[][] currentRetain = new Vector[numLayer][];
Vector[][] nextRetain = new Vector[numLayer - 1][];
for (int i = 0; i < numLayer; i++)
{
currentAuthPaths[i] = new byte[heightOfTrees[i]][mdLength];
currentTreehash[i] = new Treehash[heightOfTrees[i] - K[i]];
if (i > 0)
{
nextAuthPaths[i - 1] = new byte[heightOfTrees[i]][mdLength];
nextTreehash[i - 1] = new Treehash[heightOfTrees[i] - K[i]];
}
currentStack[i] = new Vector();
if (i > 0)
{
nextStack[i - 1] = new Vector();
}
}
// initialize roots
byte[][] currentRoots = new byte[numLayer][mdLength];
byte[][] nextRoots = new byte[numLayer - 1][mdLength];
// initialize seeds
byte[][] seeds = new byte[numLayer][mdLength];
// initialize seeds[] by copying starting-seeds of first trees of each
// layer
for (int i = 0; i < numLayer; i++)
{
System.arraycopy(currentSeeds[i], 0, seeds[i], 0, mdLength);
}
// initialize rootSigs
currentRootSigs = new byte[numLayer - 1][mdLength];
// -------------------------
// -------------------------
// --- calculation of current authpaths and current rootsigs (AUTHPATHS,
// SIG)------
// from bottom up to the root
for (int h = numLayer - 1; h >= 0; h--)
{
GMSSRootCalc tree;
// on lowest layer no lower root is available, so just call
// the method with null as first parameter
if (h == numLayer - 1)
{
tree = this.generateCurrentAuthpathAndRoot(null, currentStack[h], seeds[h], h);
}
else
// otherwise call the method with the former computed root
// value
{
tree = this.generateCurrentAuthpathAndRoot(currentRoots[h + 1], currentStack[h], seeds[h], h);
}
// set initial values needed for the private key construction
for (int i = 0; i < heightOfTrees[h]; i++)
{
System.arraycopy(tree.getAuthPath()[i], 0, currentAuthPaths[h][i], 0, mdLength);
}
currentRetain[h] = tree.getRetain();
currentTreehash[h] = tree.getTreehash();
System.arraycopy(tree.getRoot(), 0, currentRoots[h], 0, mdLength);
}
// --- calculation of next authpaths and next roots (AUTHPATHS+, ROOTS+)
// ------
for (int h = numLayer - 2; h >= 0; h--)
{
GMSSRootCalc tree = this.generateNextAuthpathAndRoot(nextStack[h], seeds[h + 1], h + 1);
// set initial values needed for the private key construction
for (int i = 0; i < heightOfTrees[h + 1]; i++)
{
System.arraycopy(tree.getAuthPath()[i], 0, nextAuthPaths[h][i], 0, mdLength);
}
nextRetain[h] = tree.getRetain();
nextTreehash[h] = tree.getTreehash();
System.arraycopy(tree.getRoot(), 0, nextRoots[h], 0, mdLength);
// create seed for the Merkle tree after next (nextNextSeeds)
// SEEDs++
System.arraycopy(seeds[h + 1], 0, this.nextNextSeeds[h], 0, mdLength);
}
// ------------
// generate JDKGMSSPublicKey
GMSSPublicKeyParameters publicKey = new GMSSPublicKeyParameters(currentRoots[0], gmssPS);
// generate the JDKGMSSPrivateKey
GMSSPrivateKeyParameters privateKey = new GMSSPrivateKeyParameters(currentSeeds, nextNextSeeds, currentAuthPaths,
nextAuthPaths, currentTreehash, nextTreehash, currentStack, nextStack, currentRetain, nextRetain, nextRoots, currentRootSigs, gmssPS, digestProvider);
// return the KeyPair
return (new AsymmetricCipherKeyPair(publicKey, privateKey));
}
/**
* calculates the authpath for tree in layer h which starts with seed[h]
* additionally computes the rootSignature of underlaying root
*
* @param currentStack stack used for the treehash instance created by this method
* @param lowerRoot stores the root of the lower tree
* @param seed starting seeds
* @param h actual layer
*/
private GMSSRootCalc generateCurrentAuthpathAndRoot(byte[] lowerRoot, Vector currentStack, byte[] seed, int h)
{
byte[] help = new byte[mdLength];
byte[] OTSseed = new byte[mdLength];
OTSseed = gmssRandom.nextSeed(seed);
WinternitzOTSignature ots;
// data structure that constructs the whole tree and stores
// the initial values for treehash, Auth and retain
GMSSRootCalc treeToConstruct = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], digestProvider);
treeToConstruct.initialize(currentStack);
// generate the first leaf
if (h == numLayer - 1)
{
ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]);
help = ots.getPublicKey();
}
else
{
// for all layers except the lowest, generate the signature of the
// underlying root
// and reuse this signature to compute the first leaf of acual layer
// more efficiently (by verifiing the signature)
ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]);
currentRootSigs[h] = ots.getSignature(lowerRoot);
WinternitzOTSVerify otsver = new WinternitzOTSVerify(digestProvider.get(), otsIndex[h]);
help = otsver.Verify(lowerRoot, currentRootSigs[h]);
}
// update the tree with the first leaf
treeToConstruct.update(help);
int seedForTreehashIndex = 3;
int count = 0;
// update the tree 2^(H) - 1 times, from the second to the last leaf
for (int i = 1; i < (1 << this.heightOfTrees[h]); i++)
{
// initialize the seeds for the leaf generation with index 3 * 2^h
if (i == seedForTreehashIndex && count < this.heightOfTrees[h] - this.K[h])
{
treeToConstruct.initializeTreehashSeed(seed, count);
seedForTreehashIndex *= 2;
count++;
}
OTSseed = gmssRandom.nextSeed(seed);
ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]);
treeToConstruct.update(ots.getPublicKey());
}
if (treeToConstruct.wasFinished())
{
return treeToConstruct;
}
System.err.println("Baum noch nicht fertig konstruiert!!!");
return null;
}
/**
* calculates the authpath and root for tree in layer h which starts with
* seed[h]
*
* @param nextStack stack used for the treehash instance created by this method
* @param seed starting seeds
* @param h actual layer
*/
private GMSSRootCalc generateNextAuthpathAndRoot(Vector nextStack, byte[] seed, int h)
{
byte[] OTSseed = new byte[numLayer];
WinternitzOTSignature ots;
// data structure that constructs the whole tree and stores
// the initial values for treehash, Auth and retain
GMSSRootCalc treeToConstruct = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], this.digestProvider);
treeToConstruct.initialize(nextStack);
int seedForTreehashIndex = 3;
int count = 0;
// update the tree 2^(H) times, from the first to the last leaf
for (int i = 0; i < (1 << this.heightOfTrees[h]); i++)
{
// initialize the seeds for the leaf generation with index 3 * 2^h
if (i == seedForTreehashIndex && count < this.heightOfTrees[h] - this.K[h])
{
treeToConstruct.initializeTreehashSeed(seed, count);
seedForTreehashIndex *= 2;
count++;
}
OTSseed = gmssRandom.nextSeed(seed);
ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]);
treeToConstruct.update(ots.getPublicKey());
}
if (treeToConstruct.wasFinished())
{
return treeToConstruct;
}
System.err.println("N�chster Baum noch nicht fertig konstruiert!!!");
return null;
}
/**
* This method initializes the GMSS KeyPairGenerator using an integer value
* <code>keySize</code> as input. It provides a simple use of the GMSS for
* testing demands.
* <p>
* A given <code>keysize</code> of less than 10 creates an amount 2^10
* signatures. A keySize between 10 and 20 creates 2^20 signatures. Given an
* integer greater than 20 the key pair generator creates 2^40 signatures.
*
* @param keySize Assigns the parameters used for the GMSS signatures. There are
* 3 choices:<br>
* 1. keysize <= 10: creates 2^10 signatures using the
* parameterset<br>
* P = (2, (5, 5), (3, 3), (3, 3))<br>
* 2. keysize > 10 and <= 20: creates 2^20 signatures using the
* parameterset<br>
* P = (2, (10, 10), (5, 4), (2, 2))<br>
* 3. keysize > 20: creates 2^40 signatures using the
* parameterset<br>
* P = (2, (10, 10, 10, 10), (9, 9, 9, 3), (2, 2, 2, 2))
* @param secureRandom not used by GMSS, the SHA1PRNG of the SUN Provider is always
* used
*/
public void initialize(int keySize, SecureRandom secureRandom)
{
KeyGenerationParameters kgp;
if (keySize <= 10)
{ // create 2^10 keys
int[] defh = {10};
int[] defw = {3};
int[] defk = {2};
// XXX sec random neede?
kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk));
}
else if (keySize <= 20)
{ // create 2^20 keys
int[] defh = {10, 10};
int[] defw = {5, 4};
int[] defk = {2, 2};
kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk));
}
else
{ // create 2^40 keys, keygen lasts around 80 seconds
int[] defh = {10, 10, 10, 10};
int[] defw = {9, 9, 9, 3};
int[] defk = {2, 2, 2, 2};
kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk));
}
// call the initializer with the chosen parameters
this.initialize(kgp);
}
/**
* Initalizes the key pair generator using a parameter set as input
*/
public void initialize(KeyGenerationParameters param)
{
this.gmssParams = (GMSSKeyGenerationParameters)param;
// generate GMSSParameterset
this.gmssPS = new GMSSParameters(gmssParams.getParameters().getNumOfLayers(), gmssParams.getParameters().getHeightOfTrees(),
gmssParams.getParameters().getWinternitzParameter(), gmssParams.getParameters().getK());
this.numLayer = gmssPS.getNumOfLayers();
this.heightOfTrees = gmssPS.getHeightOfTrees();
this.otsIndex = gmssPS.getWinternitzParameter();
this.K = gmssPS.getK();
// seeds
this.currentSeeds = new byte[numLayer][mdLength];
this.nextNextSeeds = new byte[numLayer - 1][mdLength];
// construct SecureRandom for initial seed generation
SecureRandom secRan = new SecureRandom();
// generation of initial seeds
for (int i = 0; i < numLayer; i++)
{
secRan.nextBytes(currentSeeds[i]);
gmssRandom.nextSeed(currentSeeds[i]);
}
this.initialized = true;
}
/**
* This method is called by generateKeyPair() in case that no other
* initialization method has been called by the user
*/
private void initializeDefault()
{
int[] defh = {10, 10, 10, 10};
int[] defw = {3, 3, 3, 3};
int[] defk = {2, 2, 2, 2};
KeyGenerationParameters kgp = new GMSSKeyGenerationParameters(new SecureRandom(), new GMSSParameters(defh.length, defh, defw, defk));
this.initialize(kgp);
}
public void init(KeyGenerationParameters param)
{
this.initialize(param);
}
public AsymmetricCipherKeyPair generateKeyPair()
{
return genKeyPair();
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_0
|
crossvul-java_data_bad_172_1
|
package com.fasterxml.jackson.databind.jsontype.impl;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
/**
* Helper class used to encapsulate rules that determine subtypes that
* are invalid to use, even with default typing, mostly due to security
* concerns.
* Used by <code>BeanDeserializerFacotry</code>
*
* @since 2.8.11
*/
public class SubTypeValidator
{
protected final static String PREFIX_SPRING = "org.springframework.";
protected final static String PREFIX_C3P0 = "com.mchange.v2.c3p0.";
/**
* Set of well-known "nasty classes", deserialization of which is considered dangerous
* and should (and is) prevented by default.
*/
protected final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES;
static {
Set<String> s = new HashSet<String>();
// Courtesy of [https://github.com/kantega/notsoserial]:
// (and wrt [databind#1599])
s.add("org.apache.commons.collections.functors.InvokerTransformer");
s.add("org.apache.commons.collections.functors.InstantiateTransformer");
s.add("org.apache.commons.collections4.functors.InvokerTransformer");
s.add("org.apache.commons.collections4.functors.InstantiateTransformer");
s.add("org.codehaus.groovy.runtime.ConvertedClosure");
s.add("org.codehaus.groovy.runtime.MethodClosure");
s.add("org.springframework.beans.factory.ObjectFactory");
s.add("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl");
s.add("org.apache.xalan.xsltc.trax.TemplatesImpl");
// [databind#1680]: may or may not be problem, take no chance
s.add("com.sun.rowset.JdbcRowSetImpl");
// [databind#1737]; JDK provided
s.add("java.util.logging.FileHandler");
s.add("java.rmi.server.UnicastRemoteObject");
// [databind#1737]; 3rd party
//s.add("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor"); // deprecated by [databind#1855]
s.add("org.springframework.beans.factory.config.PropertyPathFactoryBean");
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // deprecated by [databind#1931]
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // - "" -
// [databind#1855]: more 3rd party
s.add("org.apache.tomcat.dbcp.dbcp2.BasicDataSource");
s.add("com.sun.org.apache.bcel.internal.util.ClassLoader");
// [databind#2032]: more 3rd party; data exfiltration via xml parsed ext entities
s.add("org.apache.ibatis.parsing.XPathParser");
DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);
}
/**
* Set of class names of types that are never to be deserialized.
*/
protected Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES;
private final static SubTypeValidator instance = new SubTypeValidator();
protected SubTypeValidator() { }
public static SubTypeValidator instance() { return instance; }
public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
main_check:
do {
if (_cfgIllegalClassNames.contains(full)) {
break;
}
// 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
// for some Spring framework types
// 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
if (raw.isInterface()) {
;
} else if (full.startsWith(PREFIX_SPRING)) {
for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){
String name = cls.getSimpleName();
// looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
if ("AbstractPointcutAdvisor".equals(name)
// ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts
|| "AbstractApplicationContext".equals(name)) {
break main_check;
}
}
} else if (full.startsWith(PREFIX_C3P0)) {
// [databind#1737]; more 3rd party
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
// [databind#1931]; more 3rd party
// com.mchange.v2.c3p0.ComboPooledDataSource
// com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource
if (full.endsWith("DataSource")) {
break main_check;
}
}
return;
} while (false);
throw JsonMappingException.from(ctxt,
String.format("Illegal type (%s) to deserialize: prevented for security reasons", full));
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_172_1
|
crossvul-java_data_good_1894_10
|
package io.onedev.server.plugin.executor.kubernetes;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import org.apache.commons.lang.SerializationUtils;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import io.onedev.commons.utils.TarUtils;
import io.onedev.k8shelper.CacheAllocationRequest;
import io.onedev.k8shelper.CacheInstance;
import io.onedev.server.GeneralException;
import io.onedev.server.buildspec.job.Job;
import io.onedev.server.buildspec.job.JobContext;
import io.onedev.server.buildspec.job.JobManager;
@Path("/k8s")
@Consumes(MediaType.WILDCARD)
@Singleton
public class KubernetesResource {
public static final String TEST_JOB_TOKEN = UUID.randomUUID().toString();
private final JobManager jobManager;
@Context
private HttpServletRequest request;
@Inject
public KubernetesResource(JobManager jobManager) {
this.jobManager = jobManager;
}
@Path("/job-context")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET
public byte[] getJobContext() {
JobContext context = jobManager.getJobContext(getJobToken(), true);
Map<String, Object> contextMap = new HashMap<>();
contextMap.put("commands", context.getCommands());
contextMap.put("retrieveSource", context.isRetrieveSource());
contextMap.put("cloneDepth", context.getCloneDepth());
contextMap.put("projectName", context.getProjectName());
contextMap.put("cloneInfo", context.getCloneInfo());
contextMap.put("commitHash", context.getCommitId().name());
contextMap.put("collectFiles.includes", context.getCollectFiles().getIncludes());
contextMap.put("collectFiles.excludes", context.getCollectFiles().getExcludes());
return SerializationUtils.serialize((Serializable) contextMap);
}
@Path("/allocate-job-caches")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@POST
public byte[] allocateJobCaches(String cacheAllocationRequestString) {
CacheAllocationRequest cacheAllocationRequest = CacheAllocationRequest.fromString(cacheAllocationRequestString);
return SerializationUtils.serialize((Serializable) jobManager.allocateJobCaches(
getJobToken(), cacheAllocationRequest.getCurrentTime(), cacheAllocationRequest.getInstances()));
}
@Path("/report-job-caches")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@POST
public void reportJobCaches(String cacheInstancesString) {
Collection<CacheInstance> cacheInstances = new ArrayList<>();
for (String field: Splitter.on(';').omitEmptyStrings().split(cacheInstancesString))
cacheInstances.add(CacheInstance.fromString(field));
jobManager.reportJobCaches(getJobToken(), cacheInstances);
}
@Path("/download-dependencies")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET
public Response downloadDependencies() {
StreamingOutput os = new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException {
JobContext context = jobManager.getJobContext(getJobToken(), true);
TarUtils.tar(context.getServerWorkspace(), Lists.newArrayList("**"),
new ArrayList<>(), output);
output.flush();
}
};
return Response.ok(os).build();
}
@POST
@Path("/upload-outcomes")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response uploadOutcomes(InputStream is) {
JobContext context = jobManager.getJobContext(getJobToken(), true);
TarUtils.untar(is, context.getServerWorkspace());
return Response.ok().build();
}
@GET
@Path("/test")
public Response test() {
String jobToken = Job.getToken(request);
if (TEST_JOB_TOKEN.equals(jobToken))
return Response.ok().build();
else
return Response.status(400).entity("Invalid or missing job token").build();
}
private String getJobToken() {
String jobToken = Job.getToken(request);
if (jobToken != null)
return jobToken;
else
throw new GeneralException("Job token is expected");
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_1894_10
|
crossvul-java_data_good_42_8
|
package org.bouncycastle.pqc.jcajce.provider.xmss;
import java.io.IOException;
import java.security.PrivateKey;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;
import org.bouncycastle.pqc.asn1.XMSSMTKeyParams;
import org.bouncycastle.pqc.asn1.XMSSMTPrivateKey;
import org.bouncycastle.pqc.asn1.XMSSPrivateKey;
import org.bouncycastle.pqc.crypto.xmss.BDSStateMap;
import org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSMTPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;
import org.bouncycastle.pqc.jcajce.interfaces.XMSSMTKey;
import org.bouncycastle.util.Arrays;
public class BCXMSSMTPrivateKey
implements PrivateKey, XMSSMTKey
{
private final ASN1ObjectIdentifier treeDigest;
private final XMSSMTPrivateKeyParameters keyParams;
public BCXMSSMTPrivateKey(
ASN1ObjectIdentifier treeDigest,
XMSSMTPrivateKeyParameters keyParams)
{
this.treeDigest = treeDigest;
this.keyParams = keyParams;
}
public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters
.Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest)))
.withIndex(xmssMtPrivateKey.getIndex())
.withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed())
.withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF())
.withPublicSeed(xmssMtPrivateKey.getPublicSeed())
.withRoot(xmssMtPrivateKey.getRoot());
if (xmssMtPrivateKey.getBdsState() != null)
{
keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState(), BDSStateMap.class));
}
this.keyParams = keyBuilder.build();
}
catch (ClassNotFoundException e)
{
throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
}
}
public String getAlgorithm()
{
return "XMSSMT";
}
public String getFormat()
{
return "PKCS#8";
}
public byte[] getEncoded()
{
PrivateKeyInfo pki;
try
{
AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss_mt, new XMSSMTKeyParams(keyParams.getParameters().getHeight(), keyParams.getParameters().getLayers(), new AlgorithmIdentifier(treeDigest)));
pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure());
return pki.getEncoded();
}
catch (IOException e)
{
return null;
}
}
CipherParameters getKeyParams()
{
return keyParams;
}
public boolean equals(Object o)
{
if (o == this)
{
return true;
}
if (o instanceof BCXMSSMTPrivateKey)
{
BCXMSSMTPrivateKey otherKey = (BCXMSSMTPrivateKey)o;
return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.toByteArray(), otherKey.keyParams.toByteArray());
}
return false;
}
public int hashCode()
{
return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.toByteArray());
}
private XMSSMTPrivateKey createKeyStructure()
{
byte[] keyData = keyParams.toByteArray();
int n = keyParams.getParameters().getDigestSize();
int totalHeight = keyParams.getParameters().getHeight();
int indexSize = (totalHeight + 7) / 8;
int secretKeySize = n;
int secretKeyPRFSize = n;
int publicSeedSize = n;
int rootSize = n;
int position = 0;
int index = (int)XMSSUtil.bytesToXBigEndian(keyData, position, indexSize);
if (!XMSSUtil.isIndexValid(totalHeight, index))
{
throw new IllegalArgumentException("index out of bounds");
}
position += indexSize;
byte[] secretKeySeed = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeySize);
position += secretKeySize;
byte[] secretKeyPRF = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeyPRFSize);
position += secretKeyPRFSize;
byte[] publicSeed = XMSSUtil.extractBytesAtOffset(keyData, position, publicSeedSize);
position += publicSeedSize;
byte[] root = XMSSUtil.extractBytesAtOffset(keyData, position, rootSize);
position += rootSize;
/* import BDS state */
byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(keyData, position, keyData.length - position);
return new XMSSMTPrivateKey(index, secretKeySeed, secretKeyPRF, publicSeed, root, bdsStateBinary);
}
ASN1ObjectIdentifier getTreeDigestOID()
{
return treeDigest;
}
public int getHeight()
{
return keyParams.getParameters().getHeight();
}
public int getLayers()
{
return keyParams.getParameters().getLayers();
}
public String getTreeDigest()
{
return DigestUtil.getXMSSDigestName(treeDigest);
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_8
|
crossvul-java_data_bad_5761_3
|
/**
* License Agreement.
*
* Rich Faces - Natural Ajax for Java Server Faces (JSF)
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.ajax4jsf.resource;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Date;
import javax.el.ELContext;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
/**
* @author shura
*
*/
public class UserResource extends InternetResourceBase {
private String contentType;
/**
*
*/
public UserResource(boolean cacheable, boolean session, String mime) {
super();
setCacheable(cacheable);
setSessionAware(session);
setContentType(mime);
}
/**
* @return Returns the contentType.
*/
public String getContentType(ResourceContext resourceContext) {
return contentType;
}
/**
* @param contentType The contentType to set.
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#getDataToStore(javax.faces.context.FacesContext, java.lang.Object)
*/
public Object getDataToStore(FacesContext context, Object data) {
UriData dataToStore = null;
if (data instanceof ResourceComponent2) {
ResourceComponent2 resource = (ResourceComponent2) data;
dataToStore = new UriData();
dataToStore.value = resource.getValue();
dataToStore.createContent = UIComponentBase.saveAttachedState(context,resource.getCreateContentExpression());
if (data instanceof UIComponent) {
UIComponent component = (UIComponent) data;
ValueExpression expires = component.getValueExpression("expires");
if (null != expires) {
dataToStore.expires = UIComponentBase.saveAttachedState(context,expires);
}
ValueExpression lastModified = component.getValueExpression("lastModified");
if (null != lastModified) {
dataToStore.modified = UIComponentBase.saveAttachedState(context,lastModified);
}
}
}
return dataToStore;
}
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#send(org.ajax4jsf.resource.ResourceContext)
*/
public void send(ResourceContext context) throws IOException {
UriData data = (UriData) restoreData(context);
FacesContext facesContext = FacesContext.getCurrentInstance();
if (null != data && null != facesContext ) {
// Send headers
ELContext elContext = facesContext.getELContext();
// if(data.expires != null){
// ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires);
// Date expires = (Date) binding.getValue(elContext);
// context.setDateHeader("Expires",expires.getTime());
// }
// if(data.modified != null){
// ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified);
// Date modified = (Date) binding.getValue(elContext);
// context.setDateHeader("Last-Modified",modified.getTime());
// }
// Send content
OutputStream out = context.getOutputStream();
MethodExpression send = (MethodExpression) UIComponentBase.restoreAttachedState(facesContext,data.createContent);
send.invoke(elContext,new Object[]{out,data.value});
}
}
@Override
public Date getLastModified(ResourceContext resourceContext) {
UriData data = (UriData) restoreData(resourceContext);
FacesContext facesContext = FacesContext.getCurrentInstance();
if (null != data && null != facesContext ) {
// Send headers
ELContext elContext = facesContext.getELContext();
if(data.modified != null){
ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified);
Date modified = (Date) binding.getValue(elContext);
if (null != modified) {
return modified;
}
}
}
return super.getLastModified(resourceContext);
}
@Override
public long getExpired(ResourceContext resourceContext) {
UriData data = (UriData) restoreData(resourceContext);
FacesContext facesContext = FacesContext.getCurrentInstance();
if (null != data && null != facesContext ) {
// Send headers
ELContext elContext = facesContext.getELContext();
if(data.expires != null){
ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires);
Date expires = (Date) binding.getValue(elContext);
if (null != expires) {
return expires.getTime()-System.currentTimeMillis();
}
}
}
return super.getExpired(resourceContext);
}
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext()
*/
public boolean requireFacesContext() {
// TODO Auto-generated method stub
return true;
}
public static class UriData implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1258987L;
private Object value;
private Object createContent;
private Object expires;
private Object modified;
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_5761_3
|
crossvul-java_data_good_5761_0
|
/**
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
**/
package org.ajax4jsf.resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* When deserializing objects, first check that the class being deserialized is in the allowed whitelist.
*
* @author <a href="http://community.jboss.org/people/bleathem">Brian Leathem</a>
*/
public class LookAheadObjectInputStream extends ObjectInputStream {
private static final Map<String, Class<?>> PRIMITIVE_TYPES = new HashMap<String, Class<?>>(9, 1.0F);
private static Set<Class> whitelistBaseClasses = new HashSet<Class>();
private static Set<String> whitelistClassNameCache = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
static {
PRIMITIVE_TYPES.put("bool", Boolean.TYPE);
PRIMITIVE_TYPES.put("byte", Byte.TYPE);
PRIMITIVE_TYPES.put("char", Character.TYPE);
PRIMITIVE_TYPES.put("short", Short.TYPE);
PRIMITIVE_TYPES.put("int", Integer.TYPE);
PRIMITIVE_TYPES.put("long", Long.TYPE);
PRIMITIVE_TYPES.put("float", Float.TYPE);
PRIMITIVE_TYPES.put("double", Double.TYPE);
PRIMITIVE_TYPES.put("void", Void.TYPE);
whitelistClassNameCache.add(new Object[0].getClass().getName());
whitelistClassNameCache.add(new String[0].getClass().getName());
whitelistClassNameCache.add(new Boolean[0].getClass().getName());
whitelistClassNameCache.add(new Byte[0].getClass().getName());
whitelistClassNameCache.add(new Character[0].getClass().getName());
whitelistClassNameCache.add(new Short[0].getClass().getName());
whitelistClassNameCache.add(new Integer[0].getClass().getName());
whitelistClassNameCache.add(new Long[0].getClass().getName());
whitelistClassNameCache.add(new Float[0].getClass().getName());
whitelistClassNameCache.add(new Double[0].getClass().getName());
whitelistClassNameCache.add(new Void[0].getClass().getName());
whitelistBaseClasses.add(String.class);
whitelistBaseClasses.add(Boolean.class);
whitelistBaseClasses.add(Byte.class);
whitelistBaseClasses.add(Character.class);
whitelistBaseClasses.add(Number.class);
loadWhitelist();
}
public LookAheadObjectInputStream(InputStream in) throws IOException {
super(in);
}
/**
* Only deserialize primitive or whitelisted classes
*/
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
Class<?> primitiveType = PRIMITIVE_TYPES.get(desc.getName());
if (primitiveType != null) {
return primitiveType;
}
if (!isClassValid(desc.getName())) {
throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName());
}
return super.resolveClass(desc);
}
/**
* Determine if the given requestedClassName is allowed by the whitelist
*/
boolean isClassValid(String requestedClassName) {
if (whitelistClassNameCache.contains(requestedClassName)) {
return true;
}
try {
Class<?> requestedClass = Class.forName(requestedClassName);
for (Class baseClass : whitelistBaseClasses ) {
if (baseClass.isAssignableFrom(requestedClass)) {
whitelistClassNameCache.add(requestedClassName);
return true;
}
}
} catch (ClassNotFoundException e) {
return false;
}
return false;
}
/**
* Load the whitelist from the properties file
*/
static void loadWhitelist() {
Properties whitelistProperties = new Properties();
InputStream stream = null;
try {
stream = LookAheadObjectInputStream.class.getResourceAsStream("resource-serialization.properties");
whitelistProperties.load(stream);
} catch (IOException e) {
throw new RuntimeException("Error loading the ResourceBuilder.properties file", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
throw new RuntimeException("Error closing the ResourceBuilder.properties file", e);
}
}
}
for (String baseClassName : whitelistProperties.getProperty("whitelist").split(",")) {
try {
Class<?> baseClass = Class.forName(baseClassName);
whitelistBaseClasses.add(baseClass);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to load whiteList class " + baseClassName, e);
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_5761_0
|
crossvul-java_data_bad_1893_0
|
package io.onedev.server;
import java.io.Serializable;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import javax.persistence.Version;
import javax.validation.Configuration;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.guice.aop.ShiroAopModule;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.wicket.Application;
import org.apache.wicket.core.request.mapper.StalePageException;
import org.apache.wicket.protocol.http.PageExpiredException;
import org.apache.wicket.protocol.http.WicketFilter;
import org.apache.wicket.protocol.http.WicketServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.hibernate.CallbackException;
import org.hibernate.Interceptor;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleStateException;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.collection.internal.PersistentBag;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.type.Type;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.Provider;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matchers;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter;
import com.thoughtworks.xstream.converters.extended.ISO8601SqlTimestampConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.vladsch.flexmark.Extension;
import io.onedev.commons.launcher.bootstrap.Bootstrap;
import io.onedev.commons.launcher.loader.AbstractPlugin;
import io.onedev.commons.launcher.loader.AbstractPluginModule;
import io.onedev.commons.launcher.loader.ImplementationProvider;
import io.onedev.commons.utils.ExceptionUtils;
import io.onedev.commons.utils.StringUtils;
import io.onedev.server.buildspec.job.DefaultJobManager;
import io.onedev.server.buildspec.job.JobManager;
import io.onedev.server.buildspec.job.log.DefaultLogManager;
import io.onedev.server.buildspec.job.log.LogManager;
import io.onedev.server.buildspec.job.log.instruction.LogInstruction;
import io.onedev.server.entitymanager.BuildDependenceManager;
import io.onedev.server.entitymanager.BuildManager;
import io.onedev.server.entitymanager.BuildParamManager;
import io.onedev.server.entitymanager.BuildQuerySettingManager;
import io.onedev.server.entitymanager.CodeCommentManager;
import io.onedev.server.entitymanager.CodeCommentQuerySettingManager;
import io.onedev.server.entitymanager.CodeCommentReplyManager;
import io.onedev.server.entitymanager.CommitQuerySettingManager;
import io.onedev.server.entitymanager.GroupAuthorizationManager;
import io.onedev.server.entitymanager.GroupManager;
import io.onedev.server.entitymanager.IssueChangeManager;
import io.onedev.server.entitymanager.IssueCommentManager;
import io.onedev.server.entitymanager.IssueFieldManager;
import io.onedev.server.entitymanager.IssueManager;
import io.onedev.server.entitymanager.IssueQuerySettingManager;
import io.onedev.server.entitymanager.IssueVoteManager;
import io.onedev.server.entitymanager.IssueWatchManager;
import io.onedev.server.entitymanager.MembershipManager;
import io.onedev.server.entitymanager.MilestoneManager;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.entitymanager.PullRequestAssignmentManager;
import io.onedev.server.entitymanager.PullRequestChangeManager;
import io.onedev.server.entitymanager.PullRequestCommentManager;
import io.onedev.server.entitymanager.PullRequestManager;
import io.onedev.server.entitymanager.PullRequestQuerySettingManager;
import io.onedev.server.entitymanager.PullRequestReviewManager;
import io.onedev.server.entitymanager.PullRequestUpdateManager;
import io.onedev.server.entitymanager.PullRequestVerificationManager;
import io.onedev.server.entitymanager.PullRequestWatchManager;
import io.onedev.server.entitymanager.RoleManager;
import io.onedev.server.entitymanager.SettingManager;
import io.onedev.server.entitymanager.SshKeyManager;
import io.onedev.server.entitymanager.UrlManager;
import io.onedev.server.entitymanager.UserAuthorizationManager;
import io.onedev.server.entitymanager.UserManager;
import io.onedev.server.entitymanager.impl.DefaultBuildDependenceManager;
import io.onedev.server.entitymanager.impl.DefaultBuildManager;
import io.onedev.server.entitymanager.impl.DefaultBuildParamManager;
import io.onedev.server.entitymanager.impl.DefaultBuildQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultCodeCommentReplyManager;
import io.onedev.server.entitymanager.impl.DefaultCommitQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultGroupAuthorizationManager;
import io.onedev.server.entitymanager.impl.DefaultGroupManager;
import io.onedev.server.entitymanager.impl.DefaultIssueChangeManager;
import io.onedev.server.entitymanager.impl.DefaultIssueCommentManager;
import io.onedev.server.entitymanager.impl.DefaultIssueFieldManager;
import io.onedev.server.entitymanager.impl.DefaultIssueManager;
import io.onedev.server.entitymanager.impl.DefaultIssueQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultIssueVoteManager;
import io.onedev.server.entitymanager.impl.DefaultIssueWatchManager;
import io.onedev.server.entitymanager.impl.DefaultMembershipManager;
import io.onedev.server.entitymanager.impl.DefaultMilestoneManager;
import io.onedev.server.entitymanager.impl.DefaultProjectManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestAssignmentManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestChangeManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestCommentManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestQuerySettingManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestReviewManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestUpdateManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestVerificationManager;
import io.onedev.server.entitymanager.impl.DefaultPullRequestWatchManager;
import io.onedev.server.entitymanager.impl.DefaultRoleManager;
import io.onedev.server.entitymanager.impl.DefaultSettingManager;
import io.onedev.server.entitymanager.impl.DefaultSshKeyManager;
import io.onedev.server.entitymanager.impl.DefaultUserAuthorizationManager;
import io.onedev.server.entitymanager.impl.DefaultUserManager;
import io.onedev.server.git.GitFilter;
import io.onedev.server.git.GitSshCommandCreator;
import io.onedev.server.git.config.GitConfig;
import io.onedev.server.git.hookcallback.GitPostReceiveCallback;
import io.onedev.server.git.hookcallback.GitPreReceiveCallback;
import io.onedev.server.infomanager.CommitInfoManager;
import io.onedev.server.infomanager.DefaultCommitInfoManager;
import io.onedev.server.infomanager.DefaultPullRequestInfoManager;
import io.onedev.server.infomanager.DefaultUserInfoManager;
import io.onedev.server.infomanager.PullRequestInfoManager;
import io.onedev.server.infomanager.UserInfoManager;
import io.onedev.server.maintenance.ApplyDatabaseConstraints;
import io.onedev.server.maintenance.BackupDatabase;
import io.onedev.server.maintenance.CheckDataVersion;
import io.onedev.server.maintenance.CleanDatabase;
import io.onedev.server.maintenance.DataManager;
import io.onedev.server.maintenance.DefaultDataManager;
import io.onedev.server.maintenance.ResetAdminPassword;
import io.onedev.server.maintenance.RestoreDatabase;
import io.onedev.server.maintenance.Upgrade;
import io.onedev.server.model.support.administration.GroovyScript;
import io.onedev.server.model.support.administration.authenticator.Authenticator;
import io.onedev.server.model.support.administration.jobexecutor.AutoDiscoveredJobExecutor;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.notification.BuildNotificationManager;
import io.onedev.server.notification.CodeCommentNotificationManager;
import io.onedev.server.notification.CommitNotificationManager;
import io.onedev.server.notification.DefaultMailManager;
import io.onedev.server.notification.IssueNotificationManager;
import io.onedev.server.notification.MailManager;
import io.onedev.server.notification.PullRequestNotificationManager;
import io.onedev.server.notification.WebHookManager;
import io.onedev.server.persistence.DefaultIdManager;
import io.onedev.server.persistence.DefaultPersistManager;
import io.onedev.server.persistence.DefaultSessionManager;
import io.onedev.server.persistence.DefaultTransactionManager;
import io.onedev.server.persistence.HibernateInterceptor;
import io.onedev.server.persistence.IdManager;
import io.onedev.server.persistence.PersistListener;
import io.onedev.server.persistence.PersistManager;
import io.onedev.server.persistence.PrefixedNamingStrategy;
import io.onedev.server.persistence.SessionFactoryProvider;
import io.onedev.server.persistence.SessionInterceptor;
import io.onedev.server.persistence.SessionManager;
import io.onedev.server.persistence.SessionProvider;
import io.onedev.server.persistence.TransactionInterceptor;
import io.onedev.server.persistence.TransactionManager;
import io.onedev.server.persistence.annotation.Sessional;
import io.onedev.server.persistence.annotation.Transactional;
import io.onedev.server.persistence.dao.Dao;
import io.onedev.server.persistence.dao.DefaultDao;
import io.onedev.server.rest.RestConstants;
import io.onedev.server.rest.jersey.DefaultServletContainer;
import io.onedev.server.rest.jersey.JerseyConfigurator;
import io.onedev.server.rest.jersey.ResourceConfigProvider;
import io.onedev.server.search.code.DefaultIndexManager;
import io.onedev.server.search.code.DefaultSearchManager;
import io.onedev.server.search.code.IndexManager;
import io.onedev.server.search.code.SearchManager;
import io.onedev.server.security.BasicAuthenticationFilter;
import io.onedev.server.security.BearerAuthenticationFilter;
import io.onedev.server.security.CodePullAuthorizationSource;
import io.onedev.server.security.DefaultFilterChainResolver;
import io.onedev.server.security.DefaultPasswordService;
import io.onedev.server.security.DefaultRememberMeManager;
import io.onedev.server.security.DefaultWebSecurityManager;
import io.onedev.server.security.FilterChainConfigurator;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.security.realm.AbstractAuthorizingRealm;
import io.onedev.server.ssh.DefaultKeyPairProvider;
import io.onedev.server.ssh.DefaultSshAuthenticator;
import io.onedev.server.ssh.SshAuthenticator;
import io.onedev.server.ssh.SshCommandCreator;
import io.onedev.server.ssh.SshServerLauncher;
import io.onedev.server.storage.AttachmentStorageManager;
import io.onedev.server.storage.DefaultAttachmentStorageManager;
import io.onedev.server.storage.DefaultStorageManager;
import io.onedev.server.storage.StorageManager;
import io.onedev.server.util.jackson.ObjectMapperConfigurator;
import io.onedev.server.util.jackson.ObjectMapperProvider;
import io.onedev.server.util.jackson.git.GitObjectMapperConfigurator;
import io.onedev.server.util.jackson.hibernate.HibernateObjectMapperConfigurator;
import io.onedev.server.util.jetty.DefaultJettyLauncher;
import io.onedev.server.util.jetty.JettyLauncher;
import io.onedev.server.util.markdown.DefaultMarkdownManager;
import io.onedev.server.util.markdown.EntityReferenceManager;
import io.onedev.server.util.markdown.MarkdownManager;
import io.onedev.server.util.markdown.MarkdownProcessor;
import io.onedev.server.util.schedule.DefaultTaskScheduler;
import io.onedev.server.util.schedule.TaskScheduler;
import io.onedev.server.util.script.ScriptContribution;
import io.onedev.server.util.validation.DefaultEntityValidator;
import io.onedev.server.util.validation.EntityValidator;
import io.onedev.server.util.validation.ValidatorProvider;
import io.onedev.server.util.work.BatchWorkManager;
import io.onedev.server.util.work.DefaultBatchWorkManager;
import io.onedev.server.util.work.DefaultWorkExecutor;
import io.onedev.server.util.work.WorkExecutor;
import io.onedev.server.util.xstream.CollectionConverter;
import io.onedev.server.util.xstream.HibernateProxyConverter;
import io.onedev.server.util.xstream.MapConverter;
import io.onedev.server.util.xstream.ReflectionConverter;
import io.onedev.server.util.xstream.StringConverter;
import io.onedev.server.util.xstream.VersionedDocumentConverter;
import io.onedev.server.web.DefaultUrlManager;
import io.onedev.server.web.DefaultWicketFilter;
import io.onedev.server.web.DefaultWicketServlet;
import io.onedev.server.web.ExpectedExceptionContribution;
import io.onedev.server.web.ResourcePackScopeContribution;
import io.onedev.server.web.WebApplication;
import io.onedev.server.web.WebApplicationConfigurator;
import io.onedev.server.web.avatar.AvatarManager;
import io.onedev.server.web.avatar.DefaultAvatarManager;
import io.onedev.server.web.component.diff.DiffRenderer;
import io.onedev.server.web.component.markdown.AttachmentUploadServlet;
import io.onedev.server.web.component.markdown.SourcePositionTrackExtension;
import io.onedev.server.web.component.markdown.emoji.EmojiExtension;
import io.onedev.server.web.component.taskbutton.TaskButton;
import io.onedev.server.web.editable.DefaultEditSupportRegistry;
import io.onedev.server.web.editable.EditSupport;
import io.onedev.server.web.editable.EditSupportLocator;
import io.onedev.server.web.editable.EditSupportRegistry;
import io.onedev.server.web.mapper.DynamicPathPageMapper;
import io.onedev.server.web.page.layout.DefaultUICustomization;
import io.onedev.server.web.page.layout.UICustomization;
import io.onedev.server.web.page.project.blob.render.BlobRendererContribution;
import io.onedev.server.web.page.test.TestPage;
import io.onedev.server.web.websocket.BuildEventBroadcaster;
import io.onedev.server.web.websocket.CodeCommentEventBroadcaster;
import io.onedev.server.web.websocket.CommitIndexedBroadcaster;
import io.onedev.server.web.websocket.DefaultWebSocketManager;
import io.onedev.server.web.websocket.IssueEventBroadcaster;
import io.onedev.server.web.websocket.PullRequestEventBroadcaster;
import io.onedev.server.web.websocket.WebSocketManager;
import io.onedev.server.web.websocket.WebSocketPolicyProvider;
/**
* NOTE: Do not forget to rename moduleClass property defined in the pom if you've renamed this class.
*
*/
public class CoreModule extends AbstractPluginModule {
@Override
protected void configure() {
super.configure();
bind(JettyLauncher.class).to(DefaultJettyLauncher.class);
bind(ServletContextHandler.class).toProvider(DefaultJettyLauncher.class);
bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class).in(Singleton.class);
bind(ValidatorFactory.class).toProvider(new com.google.inject.Provider<ValidatorFactory>() {
@Override
public ValidatorFactory get() {
Configuration<?> configuration = Validation
.byDefaultProvider()
.configure()
.messageInterpolator(new ParameterMessageInterpolator());
return configuration.buildValidatorFactory();
}
}).in(Singleton.class);
bind(Validator.class).toProvider(ValidatorProvider.class).in(Singleton.class);
configurePersistence();
configureSecurity();
configureRestServices();
configureWeb();
configureSsh();
configureGit();
configureBuild();
/*
* Declare bindings explicitly instead of using ImplementedBy annotation as
* HK2 to guice bridge can only search in explicit bindings in Guice
*/
bind(MarkdownManager.class).to(DefaultMarkdownManager.class);
bind(StorageManager.class).to(DefaultStorageManager.class);
bind(SettingManager.class).to(DefaultSettingManager.class);
bind(DataManager.class).to(DefaultDataManager.class);
bind(TaskScheduler.class).to(DefaultTaskScheduler.class);
bind(PullRequestCommentManager.class).to(DefaultPullRequestCommentManager.class);
bind(CodeCommentManager.class).to(DefaultCodeCommentManager.class);
bind(PullRequestManager.class).to(DefaultPullRequestManager.class);
bind(PullRequestUpdateManager.class).to(DefaultPullRequestUpdateManager.class);
bind(ProjectManager.class).to(DefaultProjectManager.class);
bind(UserManager.class).to(DefaultUserManager.class);
bind(PullRequestReviewManager.class).to(DefaultPullRequestReviewManager.class);
bind(BuildManager.class).to(DefaultBuildManager.class);
bind(BuildDependenceManager.class).to(DefaultBuildDependenceManager.class);
bind(JobManager.class).to(DefaultJobManager.class);
bind(LogManager.class).to(DefaultLogManager.class);
bind(PullRequestVerificationManager.class).to(DefaultPullRequestVerificationManager.class);
bind(MailManager.class).to(DefaultMailManager.class);
bind(IssueManager.class).to(DefaultIssueManager.class);
bind(IssueFieldManager.class).to(DefaultIssueFieldManager.class);
bind(BuildParamManager.class).to(DefaultBuildParamManager.class);
bind(UserAuthorizationManager.class).to(DefaultUserAuthorizationManager.class);
bind(GroupAuthorizationManager.class).to(DefaultGroupAuthorizationManager.class);
bind(PullRequestWatchManager.class).to(DefaultPullRequestWatchManager.class);
bind(RoleManager.class).to(DefaultRoleManager.class);
bind(CommitInfoManager.class).to(DefaultCommitInfoManager.class);
bind(UserInfoManager.class).to(DefaultUserInfoManager.class);
bind(BatchWorkManager.class).to(DefaultBatchWorkManager.class);
bind(GroupManager.class).to(DefaultGroupManager.class);
bind(MembershipManager.class).to(DefaultMembershipManager.class);
bind(PullRequestChangeManager.class).to(DefaultPullRequestChangeManager.class);
bind(CodeCommentReplyManager.class).to(DefaultCodeCommentReplyManager.class);
bind(AttachmentStorageManager.class).to(DefaultAttachmentStorageManager.class);
bind(PullRequestInfoManager.class).to(DefaultPullRequestInfoManager.class);
bind(WorkExecutor.class).to(DefaultWorkExecutor.class);
bind(PullRequestNotificationManager.class);
bind(CommitNotificationManager.class);
bind(BuildNotificationManager.class);
bind(IssueNotificationManager.class);
bind(EntityReferenceManager.class);
bind(CodeCommentNotificationManager.class);
bind(CodeCommentManager.class).to(DefaultCodeCommentManager.class);
bind(IssueWatchManager.class).to(DefaultIssueWatchManager.class);
bind(IssueChangeManager.class).to(DefaultIssueChangeManager.class);
bind(IssueVoteManager.class).to(DefaultIssueVoteManager.class);
bind(MilestoneManager.class).to(DefaultMilestoneManager.class);
bind(Session.class).toProvider(SessionProvider.class);
bind(EntityManager.class).toProvider(SessionProvider.class);
bind(SessionFactory.class).toProvider(SessionFactoryProvider.class);
bind(EntityManagerFactory.class).toProvider(SessionFactoryProvider.class);
bind(IssueCommentManager.class).to(DefaultIssueCommentManager.class);
bind(IssueQuerySettingManager.class).to(DefaultIssueQuerySettingManager.class);
bind(PullRequestQuerySettingManager.class).to(DefaultPullRequestQuerySettingManager.class);
bind(CodeCommentQuerySettingManager.class).to(DefaultCodeCommentQuerySettingManager.class);
bind(CommitQuerySettingManager.class).to(DefaultCommitQuerySettingManager.class);
bind(BuildQuerySettingManager.class).to(DefaultBuildQuerySettingManager.class);
bind(PullRequestAssignmentManager.class).to(DefaultPullRequestAssignmentManager.class);
bind(SshKeyManager.class).to(DefaultSshKeyManager.class);
bind(WebHookManager.class);
contribute(ImplementationProvider.class, new ImplementationProvider() {
@Override
public Class<?> getAbstractClass() {
return JobExecutor.class;
}
@Override
public Collection<Class<?>> getImplementations() {
return Sets.newHashSet(AutoDiscoveredJobExecutor.class);
}
});
contribute(CodePullAuthorizationSource.class, DefaultJobManager.class);
bind(IndexManager.class).to(DefaultIndexManager.class);
bind(SearchManager.class).to(DefaultSearchManager.class);
bind(EntityValidator.class).to(DefaultEntityValidator.class);
bind(ExecutorService.class).toProvider(new Provider<ExecutorService>() {
@Override
public ExecutorService get() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>()) {
@Override
public void execute(Runnable command) {
try {
super.execute(SecurityUtils.inheritSubject(command));
} catch (RejectedExecutionException e) {
if (!isShutdown())
throw ExceptionUtils.unchecked(e);
}
}
};
}
}).in(Singleton.class);
bind(ForkJoinPool.class).toInstance(new ForkJoinPool() {
@Override
public ForkJoinTask<?> submit(Runnable task) {
return super.submit(SecurityUtils.inheritSubject(task));
}
@Override
public void execute(Runnable task) {
super.execute(SecurityUtils.inheritSubject(task));
}
@Override
public <T> ForkJoinTask<T> submit(Callable<T> task) {
return super.submit(SecurityUtils.inheritSubject(task));
}
@Override
public <T> ForkJoinTask<T> submit(Runnable task, T result) {
return super.submit(SecurityUtils.inheritSubject(task), result);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return super.invokeAny(SecurityUtils.inheritSubject(tasks));
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return super.invokeAny(SecurityUtils.inheritSubject(tasks), timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit) throws InterruptedException {
return super.invokeAll(SecurityUtils.inheritSubject(tasks), timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
return super.invokeAll(SecurityUtils.inheritSubject(tasks));
}
});
}
private void configureSsh() {
bind(KeyPairProvider.class).to(DefaultKeyPairProvider.class);
bind(SshAuthenticator.class).to(DefaultSshAuthenticator.class);
bind(SshServerLauncher.class);
}
private void configureSecurity() {
contributeFromPackage(Realm.class, AbstractAuthorizingRealm.class);
bind(RememberMeManager.class).to(DefaultRememberMeManager.class);
bind(WebSecurityManager.class).to(DefaultWebSecurityManager.class);
bind(FilterChainResolver.class).to(DefaultFilterChainResolver.class);
bind(BasicAuthenticationFilter.class);
bind(BearerAuthenticationFilter.class);
bind(PasswordService.class).to(DefaultPasswordService.class);
bind(ShiroFilter.class);
install(new ShiroAopModule());
contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {
@Override
public void configure(FilterChainManager filterChainManager) {
filterChainManager.createChain("/**/info/refs", "noSessionCreation, authcBasic, authcBearer");
filterChainManager.createChain("/**/git-upload-pack", "noSessionCreation, authcBasic, authcBearer");
filterChainManager.createChain("/**/git-receive-pack", "noSessionCreation, authcBasic, authcBearer");
}
});
contributeFromPackage(Authenticator.class, Authenticator.class);
}
private void configureGit() {
contribute(ObjectMapperConfigurator.class, GitObjectMapperConfigurator.class);
bind(GitConfig.class).toProvider(GitConfigProvider.class);
bind(GitFilter.class);
bind(GitPreReceiveCallback.class);
bind(GitPostReceiveCallback.class);
contribute(SshCommandCreator.class, GitSshCommandCreator.class);
}
private void configureRestServices() {
bind(ResourceConfig.class).toProvider(ResourceConfigProvider.class).in(Singleton.class);
bind(ServletContainer.class).to(DefaultServletContainer.class);
contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {
@Override
public void configure(FilterChainManager filterChainManager) {
filterChainManager.createChain("/rest/**", "noSessionCreation, authcBasic");
}
});
contribute(JerseyConfigurator.class, new JerseyConfigurator() {
@Override
public void configure(ResourceConfig resourceConfig) {
resourceConfig.packages(RestConstants.class.getPackage().getName());
}
});
}
private void configureWeb() {
bind(WicketServlet.class).to(DefaultWicketServlet.class);
bind(WicketFilter.class).to(DefaultWicketFilter.class);
bind(WebSocketPolicy.class).toProvider(WebSocketPolicyProvider.class);
bind(EditSupportRegistry.class).to(DefaultEditSupportRegistry.class);
bind(WebSocketManager.class).to(DefaultWebSocketManager.class);
bind(AttachmentUploadServlet.class);
contributeFromPackage(EditSupport.class, EditSupport.class);
bind(org.apache.wicket.protocol.http.WebApplication.class).to(WebApplication.class);
bind(Application.class).to(WebApplication.class);
bind(AvatarManager.class).to(DefaultAvatarManager.class);
bind(WebSocketManager.class).to(DefaultWebSocketManager.class);
contributeFromPackage(EditSupport.class, EditSupportLocator.class);
contribute(WebApplicationConfigurator.class, new WebApplicationConfigurator() {
@Override
public void configure(org.apache.wicket.protocol.http.WebApplication application) {
application.mount(new DynamicPathPageMapper("/test", TestPage.class));
}
});
bind(CommitIndexedBroadcaster.class);
contributeFromPackage(DiffRenderer.class, DiffRenderer.class);
contributeFromPackage(BlobRendererContribution.class, BlobRendererContribution.class);
contribute(Extension.class, new EmojiExtension());
contribute(Extension.class, new SourcePositionTrackExtension());
contributeFromPackage(MarkdownProcessor.class, MarkdownProcessor.class);
contribute(ResourcePackScopeContribution.class, new ResourcePackScopeContribution() {
@Override
public Collection<Class<?>> getResourcePackScopes() {
return Lists.newArrayList(WebApplication.class);
}
});
contribute(ExpectedExceptionContribution.class, new ExpectedExceptionContribution() {
@SuppressWarnings("unchecked")
@Override
public Collection<Class<? extends Exception>> getExpectedExceptionClasses() {
return Sets.newHashSet(ConstraintViolationException.class, EntityNotFoundException.class,
ObjectNotFoundException.class, StaleStateException.class, UnauthorizedException.class,
GeneralException.class, PageExpiredException.class, StalePageException.class);
}
});
bind(UrlManager.class).to(DefaultUrlManager.class);
bind(CodeCommentEventBroadcaster.class);
bind(PullRequestEventBroadcaster.class);
bind(IssueEventBroadcaster.class);
bind(BuildEventBroadcaster.class);
bind(TaskButton.TaskFutureManager.class);
bind(UICustomization.class).toInstance(new DefaultUICustomization());
}
private void configureBuild() {
contribute(ScriptContribution.class, new ScriptContribution() {
@Override
public GroovyScript getScript() {
GroovyScript script = new GroovyScript();
script.setName("determine-build-failure-investigator");
script.setContent(Lists.newArrayList("io.onedev.server.util.script.ScriptContribution.determineBuildFailureInvestigator()"));
return script;
}
});
contribute(ScriptContribution.class, new ScriptContribution() {
@Override
public GroovyScript getScript() {
GroovyScript script = new GroovyScript();
script.setName("get-build-number");
script.setContent(Lists.newArrayList("io.onedev.server.util.script.ScriptContribution.getBuildNumber()"));
return script;
}
});
}
private void configurePersistence() {
contribute(ObjectMapperConfigurator.class, HibernateObjectMapperConfigurator.class);
// Use an optional binding here in case our client does not like to
// start persist service provided by this plugin
bind(Interceptor.class).to(HibernateInterceptor.class);
bind(PhysicalNamingStrategy.class).toInstance(new PrefixedNamingStrategy("o_"));
bind(SessionManager.class).to(DefaultSessionManager.class);
bind(TransactionManager.class).to(DefaultTransactionManager.class);
bind(IdManager.class).to(DefaultIdManager.class);
bind(Dao.class).to(DefaultDao.class);
TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
requestInjection(transactionInterceptor);
bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {
@Override
public boolean matches(AnnotatedElement element) {
return element.isAnnotationPresent(Transactional.class) && !((Method) element).isSynthetic();
}
}, transactionInterceptor);
SessionInterceptor sessionInterceptor = new SessionInterceptor();
requestInjection(sessionInterceptor);
bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() {
@Override
public boolean matches(AnnotatedElement element) {
return element.isAnnotationPresent(Sessional.class) && !((Method) element).isSynthetic();
}
}, sessionInterceptor);
contributeFromPackage(LogInstruction.class, LogInstruction.class);
contribute(PersistListener.class, new PersistListener() {
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return false;
}
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return false;
}
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types) throws CallbackException {
return false;
}
@Override
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
}
});
bind(XStream.class).toProvider(new com.google.inject.Provider<XStream>() {
@SuppressWarnings("rawtypes")
@Override
public XStream get() {
ReflectionProvider reflectionProvider = JVM.newReflectionProvider();
XStream xstream = new XStream(reflectionProvider) {
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
@Override
public boolean shouldSerializeMember(Class definedIn, String fieldName) {
Field field = reflectionProvider.getField(definedIn, fieldName);
return field.getAnnotation(XStreamOmitField.class) == null &&
field.getAnnotation(Transient.class) == null &&
field.getAnnotation(OneToMany.class) == null &&
field.getAnnotation(Version.class) == null;
}
@Override
public String serializedClass(Class type) {
if (type == null)
return super.serializedClass(type);
else if (type == PersistentBag.class)
return super.serializedClass(ArrayList.class);
else if (type.getName().contains("$HibernateProxy$"))
return StringUtils.substringBefore(type.getName(), "$HibernateProxy$");
else
return super.serializedClass(type);
}
};
}
};
XStream.setupDefaultSecurity(xstream);
xstream.allowTypesByWildcard(new String[] {"io.onedev.**"});
// register NullConverter as highest; otherwise NPE when unmarshal a map
// containing an entry with value set to null.
xstream.registerConverter(new NullConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new StringConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new VersionedDocumentConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new HibernateProxyConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new CollectionConverter(xstream.getMapper()), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new MapConverter(xstream.getMapper()), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ISO8601DateConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ISO8601SqlTimestampConverter(), XStream.PRIORITY_VERY_HIGH);
xstream.registerConverter(new ReflectionConverter(xstream.getMapper(), xstream.getReflectionProvider()),
XStream.PRIORITY_VERY_LOW);
xstream.autodetectAnnotations(true);
return xstream;
}
}).in(Singleton.class);
if (Bootstrap.command != null) {
if (RestoreDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(RestoreDatabase.class);
else if (ApplyDatabaseConstraints.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(ApplyDatabaseConstraints.class);
else if (BackupDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(BackupDatabase.class);
else if (CheckDataVersion.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(CheckDataVersion.class);
else if (Upgrade.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(Upgrade.class);
else if (CleanDatabase.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(CleanDatabase.class);
else if (ResetAdminPassword.COMMAND.equals(Bootstrap.command.getName()))
bind(PersistManager.class).to(ResetAdminPassword.class);
else
throw new RuntimeException("Unrecognized command: " + Bootstrap.command.getName());
} else {
bind(PersistManager.class).to(DefaultPersistManager.class);
}
}
@Override
protected Class<? extends AbstractPlugin> getPluginClass() {
return OneDev.class;
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_1893_0
|
crossvul-java_data_good_42_9
|
package org.bouncycastle.pqc.jcajce.provider.xmss;
import java.io.IOException;
import java.security.PrivateKey;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;
import org.bouncycastle.pqc.asn1.XMSSKeyParams;
import org.bouncycastle.pqc.asn1.XMSSPrivateKey;
import org.bouncycastle.pqc.crypto.xmss.BDS;
import org.bouncycastle.pqc.crypto.xmss.XMSSParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;
import org.bouncycastle.pqc.jcajce.interfaces.XMSSKey;
import org.bouncycastle.util.Arrays;
public class BCXMSSPrivateKey
implements PrivateKey, XMSSKey
{
private final XMSSPrivateKeyParameters keyParams;
private final ASN1ObjectIdentifier treeDigest;
public BCXMSSPrivateKey(
ASN1ObjectIdentifier treeDigest,
XMSSPrivateKeyParameters keyParams)
{
this.treeDigest = treeDigest;
this.keyParams = keyParams;
}
public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
.Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))
.withIndex(xmssPrivateKey.getIndex())
.withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
.withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
.withPublicSeed(xmssPrivateKey.getPublicSeed())
.withRoot(xmssPrivateKey.getRoot());
if (xmssPrivateKey.getBdsState() != null)
{
keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState(), BDS.class));
}
this.keyParams = keyBuilder.build();
}
catch (ClassNotFoundException e)
{
throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
}
}
public String getAlgorithm()
{
return "XMSS";
}
public String getFormat()
{
return "PKCS#8";
}
public byte[] getEncoded()
{
PrivateKeyInfo pki;
try
{
AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss, new XMSSKeyParams(keyParams.getParameters().getHeight(), new AlgorithmIdentifier(treeDigest)));
pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure());
return pki.getEncoded();
}
catch (IOException e)
{
return null;
}
}
public boolean equals(Object o)
{
if (o == this)
{
return true;
}
if (o instanceof BCXMSSPrivateKey)
{
BCXMSSPrivateKey otherKey = (BCXMSSPrivateKey)o;
return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.toByteArray(), otherKey.keyParams.toByteArray());
}
return false;
}
public int hashCode()
{
return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.toByteArray());
}
CipherParameters getKeyParams()
{
return keyParams;
}
private XMSSPrivateKey createKeyStructure()
{
byte[] keyData = keyParams.toByteArray();
int n = keyParams.getParameters().getDigestSize();
int totalHeight = keyParams.getParameters().getHeight();
int indexSize = 4;
int secretKeySize = n;
int secretKeyPRFSize = n;
int publicSeedSize = n;
int rootSize = n;
int position = 0;
int index = (int)XMSSUtil.bytesToXBigEndian(keyData, position, indexSize);
if (!XMSSUtil.isIndexValid(totalHeight, index))
{
throw new IllegalArgumentException("index out of bounds");
}
position += indexSize;
byte[] secretKeySeed = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeySize);
position += secretKeySize;
byte[] secretKeyPRF = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeyPRFSize);
position += secretKeyPRFSize;
byte[] publicSeed = XMSSUtil.extractBytesAtOffset(keyData, position, publicSeedSize);
position += publicSeedSize;
byte[] root = XMSSUtil.extractBytesAtOffset(keyData, position, rootSize);
position += rootSize;
/* import BDS state */
byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(keyData, position, keyData.length - position);
return new XMSSPrivateKey(index, secretKeySeed, secretKeyPRF, publicSeed, root, bdsStateBinary);
}
ASN1ObjectIdentifier getTreeDigestOID()
{
return treeDigest;
}
public int getHeight()
{
return keyParams.getParameters().getHeight();
}
public String getTreeDigest()
{
return DigestUtil.getXMSSDigestName(treeDigest);
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_9
|
crossvul-java_data_good_43_0
|
package org.bouncycastle.pqc.crypto.xmss;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.util.HashSet;
import java.util.Set;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;
/**
* Utils for XMSS implementation.
*/
public class XMSSUtil
{
/**
* Calculates the logarithm base 2 for a given Integer.
*
* @param n Number.
* @return Logarithm to base 2 of {@code n}.
*/
public static int log2(int n)
{
int log = 0;
while ((n >>= 1) != 0)
{
log++;
}
return log;
}
/**
* Convert int/long to n-byte array.
*
* @param value int/long value.
* @param sizeInByte Size of byte array in byte.
* @return int/long as big-endian byte array of size {@code sizeInByte}.
*/
public static byte[] toBytesBigEndian(long value, int sizeInByte)
{
byte[] out = new byte[sizeInByte];
for (int i = (sizeInByte - 1); i >= 0; i--)
{
out[i] = (byte)value;
value >>>= 8;
}
return out;
}
/*
* Copy long to byte array in big-endian at specific offset.
*/
public static void longToBigEndian(long value, byte[] in, int offset)
{
if (in == null)
{
throw new NullPointerException("in == null");
}
if ((in.length - offset) < 8)
{
throw new IllegalArgumentException("not enough space in array");
}
in[offset] = (byte)((value >> 56) & 0xff);
in[offset + 1] = (byte)((value >> 48) & 0xff);
in[offset + 2] = (byte)((value >> 40) & 0xff);
in[offset + 3] = (byte)((value >> 32) & 0xff);
in[offset + 4] = (byte)((value >> 24) & 0xff);
in[offset + 5] = (byte)((value >> 16) & 0xff);
in[offset + 6] = (byte)((value >> 8) & 0xff);
in[offset + 7] = (byte)((value) & 0xff);
}
/*
* Generic convert from big endian byte array to long.
*/
public static long bytesToXBigEndian(byte[] in, int offset, int size)
{
if (in == null)
{
throw new NullPointerException("in == null");
}
long res = 0;
for (int i = offset; i < (offset + size); i++)
{
res = (res << 8) | (in[i] & 0xff);
}
return res;
}
/**
* Clone a byte array.
*
* @param in byte array.
* @return Copy of byte array.
*/
public static byte[] cloneArray(byte[] in)
{
if (in == null)
{
throw new NullPointerException("in == null");
}
byte[] out = new byte[in.length];
for (int i = 0; i < in.length; i++)
{
out[i] = in[i];
}
return out;
}
/**
* Clone a 2d byte array.
*
* @param in 2d byte array.
* @return Copy of 2d byte array.
*/
public static byte[][] cloneArray(byte[][] in)
{
if (hasNullPointer(in))
{
throw new NullPointerException("in has null pointers");
}
byte[][] out = new byte[in.length][];
for (int i = 0; i < in.length; i++)
{
out[i] = new byte[in[i].length];
for (int j = 0; j < in[i].length; j++)
{
out[i][j] = in[i][j];
}
}
return out;
}
/**
* Compares two 2d-byte arrays.
*
* @param a 2d-byte array 1.
* @param b 2d-byte array 2.
* @return true if all values in 2d-byte array are equal false else.
*/
public static boolean areEqual(byte[][] a, byte[][] b)
{
if (hasNullPointer(a) || hasNullPointer(b))
{
throw new NullPointerException("a or b == null");
}
for (int i = 0; i < a.length; i++)
{
if (!Arrays.areEqual(a[i], b[i]))
{
return false;
}
}
return true;
}
/**
* Dump content of 2d byte array.
*
* @param x byte array.
*/
public static void dumpByteArray(byte[][] x)
{
if (hasNullPointer(x))
{
throw new NullPointerException("x has null pointers");
}
for (int i = 0; i < x.length; i++)
{
System.out.println(Hex.toHexString(x[i]));
}
}
/**
* Checks whether 2d byte array has null pointers.
*
* @param in 2d byte array.
* @return true if at least one null pointer is found false else.
*/
public static boolean hasNullPointer(byte[][] in)
{
if (in == null)
{
return true;
}
for (int i = 0; i < in.length; i++)
{
if (in[i] == null)
{
return true;
}
}
return false;
}
/**
* Copy src byte array to dst byte array at offset.
*
* @param dst Destination.
* @param src Source.
* @param offset Destination offset.
*/
public static void copyBytesAtOffset(byte[] dst, byte[] src, int offset)
{
if (dst == null)
{
throw new NullPointerException("dst == null");
}
if (src == null)
{
throw new NullPointerException("src == null");
}
if (offset < 0)
{
throw new IllegalArgumentException("offset hast to be >= 0");
}
if ((src.length + offset) > dst.length)
{
throw new IllegalArgumentException("src length + offset must not be greater than size of destination");
}
for (int i = 0; i < src.length; i++)
{
dst[offset + i] = src[i];
}
}
/**
* Copy length bytes at position offset from src.
*
* @param src Source byte array.
* @param offset Offset in source byte array.
* @param length Length of bytes to copy.
* @return New byte array.
*/
public static byte[] extractBytesAtOffset(byte[] src, int offset, int length)
{
if (src == null)
{
throw new NullPointerException("src == null");
}
if (offset < 0)
{
throw new IllegalArgumentException("offset hast to be >= 0");
}
if (length < 0)
{
throw new IllegalArgumentException("length hast to be >= 0");
}
if ((offset + length) > src.length)
{
throw new IllegalArgumentException("offset + length must not be greater then size of source array");
}
byte[] out = new byte[length];
for (int i = 0; i < out.length; i++)
{
out[i] = src[offset + i];
}
return out;
}
/**
* Check whether an index is valid or not.
*
* @param height Height of binary tree.
* @param index Index to validate.
* @return true if index is valid false else.
*/
public static boolean isIndexValid(int height, long index)
{
if (index < 0)
{
throw new IllegalStateException("index must not be negative");
}
return index < (1L << height);
}
/**
* Determine digest size of digest.
*
* @param digest Digest.
* @return Digest size.
*/
public static int getDigestSize(Digest digest)
{
if (digest == null)
{
throw new NullPointerException("digest == null");
}
String algorithmName = digest.getAlgorithmName();
if (algorithmName.equals("SHAKE128"))
{
return 32;
}
if (algorithmName.equals("SHAKE256"))
{
return 64;
}
return digest.getDigestSize();
}
public static long getTreeIndex(long index, int xmssTreeHeight)
{
return index >> xmssTreeHeight;
}
public static int getLeafIndex(long index, int xmssTreeHeight)
{
return (int)(index & ((1L << xmssTreeHeight) - 1L));
}
public static byte[] serialize(Object obj)
throws IOException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(obj);
oos.flush();
return out.toByteArray();
}
public static Object deserialize(byte[] data, final Class clazz)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new CheckingStream(clazz, in);
Object obj = is.readObject();
if (is.available() != 0)
{
throw new IOException("unexpected data found at end of ObjectInputStream");
}
// you'd hope this would always succeed!
if (clazz.isInstance(obj))
{
return obj;
}
else
{
throw new IOException("unexpected class found in ObjectInputStream");
}
}
public static int calculateTau(int index, int height)
{
int tau = 0;
for (int i = 0; i < height; i++)
{
if (((index >> i) & 1) == 0)
{
tau = i;
break;
}
}
return tau;
}
public static boolean isNewBDSInitNeeded(long globalIndex, int xmssHeight, int layer)
{
if (globalIndex == 0)
{
return false;
}
return (globalIndex % (long)Math.pow((1 << xmssHeight), layer + 1) == 0) ? true : false;
}
public static boolean isNewAuthenticationPathNeeded(long globalIndex, int xmssHeight, int layer)
{
if (globalIndex == 0)
{
return false;
}
return ((globalIndex + 1) % (long)Math.pow((1 << xmssHeight), layer) == 0) ? true : false;
}
private static class CheckingStream
extends ObjectInputStream
{
private static final Set<String> components = new HashSet<>();
static
{
components.add("java.util.TreeMap");
components.add("java.lang.Integer");
components.add("java.lang.Number");
components.add("org.bouncycastle.pqc.crypto.xmss.BDS");
components.add("java.util.ArrayList");
components.add("org.bouncycastle.pqc.crypto.xmss.XMSSNode");
components.add("[B");
components.add("java.util.LinkedList");
components.add("java.util.Stack");
components.add("java.util.Vector");
components.add("[Ljava.lang.Object;");
components.add("org.bouncycastle.pqc.crypto.xmss.BDSTreeHash");
}
private final Class mainClass;
private boolean found = false;
CheckingStream(Class mainClass, InputStream in)
throws IOException
{
super(in);
this.mainClass = mainClass;
}
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException,
ClassNotFoundException
{
if (!found)
{
if (!desc.getName().equals(mainClass.getName()))
{
throw new InvalidClassException(
"unexpected class: ", desc.getName());
}
else
{
found = true;
}
}
else
{
if (!components.contains(desc.getName()))
{
throw new InvalidClassException(
"unexpected class: ", desc.getName());
}
}
return super.resolveClass(desc);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_43_0
|
crossvul-java_data_bad_1893_1
|
package io.onedev.server.web;
import org.apache.wicket.core.request.mapper.ResourceMapper;
import org.apache.wicket.markup.html.pages.BrowserInfoPage;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.IRequestMapper;
import org.apache.wicket.request.mapper.CompoundRequestMapper;
import io.onedev.server.GeneralException;
import io.onedev.server.web.asset.icon.IconScope;
import io.onedev.server.web.mapper.BaseResourceMapper;
import io.onedev.server.web.mapper.DynamicPathPageMapper;
import io.onedev.server.web.mapper.DynamicPathResourceMapper;
import io.onedev.server.web.page.admin.authenticator.AuthenticatorPage;
import io.onedev.server.web.page.admin.databasebackup.DatabaseBackupPage;
import io.onedev.server.web.page.admin.generalsecuritysetting.GeneralSecuritySettingPage;
import io.onedev.server.web.page.admin.groovyscript.GroovyScriptListPage;
import io.onedev.server.web.page.admin.group.GroupListPage;
import io.onedev.server.web.page.admin.group.authorization.GroupAuthorizationsPage;
import io.onedev.server.web.page.admin.group.create.NewGroupPage;
import io.onedev.server.web.page.admin.group.membership.GroupMembershipsPage;
import io.onedev.server.web.page.admin.group.profile.GroupProfilePage;
import io.onedev.server.web.page.admin.issuesetting.defaultboard.DefaultBoardListPage;
import io.onedev.server.web.page.admin.issuesetting.fieldspec.IssueFieldListPage;
import io.onedev.server.web.page.admin.issuesetting.issuetemplate.IssueTemplateListPage;
import io.onedev.server.web.page.admin.issuesetting.statespec.IssueStateListPage;
import io.onedev.server.web.page.admin.issuesetting.transitionspec.StateTransitionListPage;
import io.onedev.server.web.page.admin.jobexecutor.JobExecutorsPage;
import io.onedev.server.web.page.admin.mailsetting.MailSettingPage;
import io.onedev.server.web.page.admin.role.NewRolePage;
import io.onedev.server.web.page.admin.role.RoleDetailPage;
import io.onedev.server.web.page.admin.role.RoleListPage;
import io.onedev.server.web.page.admin.serverinformation.ServerInformationPage;
import io.onedev.server.web.page.admin.serverlog.ServerLogPage;
import io.onedev.server.web.page.admin.ssh.SshSettingPage;
import io.onedev.server.web.page.admin.sso.SsoConnectorListPage;
import io.onedev.server.web.page.admin.sso.SsoProcessPage;
import io.onedev.server.web.page.admin.systemsetting.SystemSettingPage;
import io.onedev.server.web.page.admin.user.UserListPage;
import io.onedev.server.web.page.admin.user.accesstoken.UserAccessTokenPage;
import io.onedev.server.web.page.admin.user.authorization.UserAuthorizationsPage;
import io.onedev.server.web.page.admin.user.avatar.UserAvatarPage;
import io.onedev.server.web.page.admin.user.create.NewUserPage;
import io.onedev.server.web.page.admin.user.membership.UserMembershipsPage;
import io.onedev.server.web.page.admin.user.password.UserPasswordPage;
import io.onedev.server.web.page.admin.user.profile.UserProfilePage;
import io.onedev.server.web.page.admin.user.ssh.UserSshKeysPage;
import io.onedev.server.web.page.builds.BuildListPage;
import io.onedev.server.web.page.issues.IssueListPage;
import io.onedev.server.web.page.my.accesstoken.MyAccessTokenPage;
import io.onedev.server.web.page.my.avatar.MyAvatarPage;
import io.onedev.server.web.page.my.password.MyPasswordPage;
import io.onedev.server.web.page.my.profile.MyProfilePage;
import io.onedev.server.web.page.my.sshkeys.MySshKeysPage;
import io.onedev.server.web.page.project.NewProjectPage;
import io.onedev.server.web.page.project.ProjectListPage;
import io.onedev.server.web.page.project.blob.ProjectBlobPage;
import io.onedev.server.web.page.project.branches.ProjectBranchesPage;
import io.onedev.server.web.page.project.builds.ProjectBuildsPage;
import io.onedev.server.web.page.project.builds.detail.InvalidBuildPage;
import io.onedev.server.web.page.project.builds.detail.artifacts.BuildArtifactsPage;
import io.onedev.server.web.page.project.builds.detail.changes.BuildChangesPage;
import io.onedev.server.web.page.project.builds.detail.dashboard.BuildDashboardPage;
import io.onedev.server.web.page.project.builds.detail.issues.FixedIssuesPage;
import io.onedev.server.web.page.project.builds.detail.log.BuildLogPage;
import io.onedev.server.web.page.project.codecomments.InvalidCodeCommentPage;
import io.onedev.server.web.page.project.codecomments.ProjectCodeCommentsPage;
import io.onedev.server.web.page.project.commits.CommitDetailPage;
import io.onedev.server.web.page.project.commits.ProjectCommitsPage;
import io.onedev.server.web.page.project.compare.RevisionComparePage;
import io.onedev.server.web.page.project.dashboard.ProjectDashboardPage;
import io.onedev.server.web.page.project.issues.boards.IssueBoardsPage;
import io.onedev.server.web.page.project.issues.create.NewIssuePage;
import io.onedev.server.web.page.project.issues.detail.IssueActivitiesPage;
import io.onedev.server.web.page.project.issues.detail.IssueBuildsPage;
import io.onedev.server.web.page.project.issues.detail.IssueCommitsPage;
import io.onedev.server.web.page.project.issues.detail.IssuePullRequestsPage;
import io.onedev.server.web.page.project.issues.list.ProjectIssueListPage;
import io.onedev.server.web.page.project.issues.milestones.MilestoneDetailPage;
import io.onedev.server.web.page.project.issues.milestones.MilestoneEditPage;
import io.onedev.server.web.page.project.issues.milestones.MilestoneListPage;
import io.onedev.server.web.page.project.issues.milestones.NewMilestonePage;
import io.onedev.server.web.page.project.pullrequests.InvalidPullRequestPage;
import io.onedev.server.web.page.project.pullrequests.ProjectPullRequestsPage;
import io.onedev.server.web.page.project.pullrequests.create.NewPullRequestPage;
import io.onedev.server.web.page.project.pullrequests.detail.activities.PullRequestActivitiesPage;
import io.onedev.server.web.page.project.pullrequests.detail.changes.PullRequestChangesPage;
import io.onedev.server.web.page.project.pullrequests.detail.codecomments.PullRequestCodeCommentsPage;
import io.onedev.server.web.page.project.pullrequests.detail.mergepreview.MergePreviewPage;
import io.onedev.server.web.page.project.setting.authorization.ProjectAuthorizationsPage;
import io.onedev.server.web.page.project.setting.avatar.AvatarEditPage;
import io.onedev.server.web.page.project.setting.branchprotection.BranchProtectionsPage;
import io.onedev.server.web.page.project.setting.build.ActionAuthorizationsPage;
import io.onedev.server.web.page.project.setting.build.BuildPreservationsPage;
import io.onedev.server.web.page.project.setting.build.JobSecretsPage;
import io.onedev.server.web.page.project.setting.tagprotection.TagProtectionsPage;
import io.onedev.server.web.page.project.setting.webhook.WebHooksPage;
import io.onedev.server.web.page.project.stats.ProjectContribsPage;
import io.onedev.server.web.page.project.stats.SourceLinesPage;
import io.onedev.server.web.page.project.tags.ProjectTagsPage;
import io.onedev.server.web.page.pullrequests.PullRequestListPage;
import io.onedev.server.web.page.simple.error.PageNotFoundErrorPage;
import io.onedev.server.web.page.simple.security.LoginPage;
import io.onedev.server.web.page.simple.security.LogoutPage;
import io.onedev.server.web.page.simple.security.PasswordResetPage;
import io.onedev.server.web.page.simple.security.SignUpPage;
import io.onedev.server.web.page.simple.serverinit.ServerInitPage;
import io.onedev.server.web.resource.ArchiveResourceReference;
import io.onedev.server.web.resource.ArtifactResourceReference;
import io.onedev.server.web.resource.AttachmentResourceReference;
import io.onedev.server.web.resource.BuildLogResourceReference;
import io.onedev.server.web.resource.RawBlobResourceReference;
import io.onedev.server.web.resource.ServerLogResourceReference;
import io.onedev.server.web.resource.SvgSpriteResourceReference;
public class BaseUrlMapper extends CompoundRequestMapper {
@Override
public CompoundRequestMapper add(IRequestMapper mapper) {
if (mapper instanceof ResourceMapper && !(mapper instanceof BaseResourceMapper))
throw new GeneralException("Base resource mapper should be used");
return super.add(mapper);
}
public BaseUrlMapper(WebApplication app) {
add(new DynamicPathPageMapper("init", ServerInitPage.class));
add(new DynamicPathPageMapper("loading", BrowserInfoPage.class));
add(new DynamicPathPageMapper("issues", IssueListPage.class));
add(new DynamicPathPageMapper("pull-requests", PullRequestListPage.class));
add(new DynamicPathPageMapper("builds", BuildListPage.class));
addProjectPages();
addMyPages();
addAdministrationPages();
addSecurityPages();
addResources();
addErrorPages();
}
private void addMyPages() {
add(new DynamicPathPageMapper("my/profile", MyProfilePage.class));
add(new DynamicPathPageMapper("my/avatar", MyAvatarPage.class));
add(new DynamicPathPageMapper("my/password", MyPasswordPage.class));
add(new DynamicPathPageMapper("my/ssh-keys", MySshKeysPage.class));
add(new DynamicPathPageMapper("my/access-token", MyAccessTokenPage.class));
}
private void addResources() {
add(new BaseResourceMapper("downloads/server-log", new ServerLogResourceReference()));
add(new BaseResourceMapper("downloads/projects/${project}/builds/${build}/log", new BuildLogResourceReference()));
add(new BaseResourceMapper("projects/${project}/archive/${revision}", new ArchiveResourceReference()));
add(new DynamicPathResourceMapper("projects/${project}/raw/${revision}/${path}", new RawBlobResourceReference()));
add(new BaseResourceMapper("projects/${project}/attachment/${uuid}/${attachment}", new AttachmentResourceReference()));
add(new DynamicPathResourceMapper("downloads/projects/${project}/builds/${build}/artifacts/${path}",
new ArtifactResourceReference()));
add(new BaseResourceMapper(SvgSpriteResourceReference.DEFAULT_MOUNT_PATH, new SvgSpriteResourceReference(IconScope.class)));
}
private void addErrorPages() {
add(new DynamicPathPageMapper("/errors/404", PageNotFoundErrorPage.class));
}
private void addSecurityPages() {
add(new DynamicPathPageMapper("login", LoginPage.class));
add(new DynamicPathPageMapper("logout", LogoutPage.class));
add(new DynamicPathPageMapper("signup", SignUpPage.class));
add(new DynamicPathPageMapper("reset-password", PasswordResetPage.class));
add(new DynamicPathPageMapper(SsoProcessPage.MOUNT_PATH + "/${stage}/${connector}", SsoProcessPage.class));
}
private void addAdministrationPages() {
add(new DynamicPathPageMapper("administration", UserListPage.class));
add(new DynamicPathPageMapper("administration/users", UserListPage.class));
add(new DynamicPathPageMapper("administration/users/new", NewUserPage.class));
add(new DynamicPathPageMapper("administration/users/${user}/profile", UserProfilePage.class));
add(new DynamicPathPageMapper("administration/users/${user}/groups", UserMembershipsPage.class));
add(new DynamicPathPageMapper("administration/users/${user}/authorizations", UserAuthorizationsPage.class));
add(new DynamicPathPageMapper("administration/users/${user}/avatar", UserAvatarPage.class));
add(new DynamicPathPageMapper("administration/users/${user}/password", UserPasswordPage.class));
add(new DynamicPathPageMapper("administration/users/${user}/ssh-keys", UserSshKeysPage.class));
add(new DynamicPathPageMapper("administration/users/${user}/access-token", UserAccessTokenPage.class));
add(new DynamicPathPageMapper("administration/roles", RoleListPage.class));
add(new DynamicPathPageMapper("administration/roles/new", NewRolePage.class));
add(new DynamicPathPageMapper("administration/roles/${role}", RoleDetailPage.class));
add(new DynamicPathPageMapper("administration/groups", GroupListPage.class));
add(new DynamicPathPageMapper("administration/groups/new", NewGroupPage.class));
add(new DynamicPathPageMapper("administration/groups/${group}/profile", GroupProfilePage.class));
add(new DynamicPathPageMapper("administration/groups/${group}/members", GroupMembershipsPage.class));
add(new DynamicPathPageMapper("administration/groups/${group}/authorizations", GroupAuthorizationsPage.class));
add(new DynamicPathPageMapper("administration/settings/system", SystemSettingPage.class));
add(new DynamicPathPageMapper("administration/settings/mail", MailSettingPage.class));
add(new DynamicPathPageMapper("administration/settings/backup", DatabaseBackupPage.class));
add(new DynamicPathPageMapper("administration/settings/security", GeneralSecuritySettingPage.class));
add(new DynamicPathPageMapper("administration/settings/authenticator", AuthenticatorPage.class));
add(new DynamicPathPageMapper("administration/settings/sso-connectors", SsoConnectorListPage.class));
add(new DynamicPathPageMapper("administration/settings/ssh", SshSettingPage.class));
add(new DynamicPathPageMapper("administration/settings/job-executors", JobExecutorsPage.class));
add(new DynamicPathPageMapper("administration/settings/groovy-scripts", GroovyScriptListPage.class));
add(new DynamicPathPageMapper("administration/settings/issue-fields", IssueFieldListPage.class));
add(new DynamicPathPageMapper("administration/settings/issue-states", IssueStateListPage.class));
add(new DynamicPathPageMapper("administration/settings/state-transitions", StateTransitionListPage.class));
add(new DynamicPathPageMapper("administration/settings/issue-boards", DefaultBoardListPage.class));
add(new DynamicPathPageMapper("administration/settings/issue-templates", IssueTemplateListPage.class));
add(new DynamicPathPageMapper("administration/server-log", ServerLogPage.class));
add(new DynamicPathPageMapper("administration/server-information", ServerInformationPage.class));
}
private void addProjectPages() {
add(new DynamicPathPageMapper("projects", ProjectListPage.class));
add(new DynamicPathPageMapper("projects/new", NewProjectPage.class));
add(new DynamicPathPageMapper("projects/${project}", ProjectDashboardPage.class));
add(new DynamicPathPageMapper("projects/${project}/blob/#{revision}/#{path}", ProjectBlobPage.class));
add(new DynamicPathPageMapper("projects/${project}/commits", ProjectCommitsPage.class));
add(new DynamicPathPageMapper("projects/${project}/commits/${revision}", CommitDetailPage.class));
add(new DynamicPathPageMapper("projects/${project}/compare", RevisionComparePage.class));
add(new DynamicPathPageMapper("projects/${project}/stats/contribs", ProjectContribsPage.class));
add(new DynamicPathPageMapper("projects/${project}/stats/lines", SourceLinesPage.class));
add(new DynamicPathPageMapper("projects/${project}/branches", ProjectBranchesPage.class));
add(new DynamicPathPageMapper("projects/${project}/tags", ProjectTagsPage.class));
add(new DynamicPathPageMapper("projects/${project}/code-comments", ProjectCodeCommentsPage.class));
add(new DynamicPathPageMapper("projects/${project}/code-comments/${code-comment}/invalid", InvalidCodeCommentPage.class));
add(new DynamicPathPageMapper("projects/${project}/pulls", ProjectPullRequestsPage.class));
add(new DynamicPathPageMapper("projects/${project}/pulls/new", NewPullRequestPage.class));
add(new DynamicPathPageMapper("projects/${project}/pulls/${request}", PullRequestActivitiesPage.class));
add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/activities", PullRequestActivitiesPage.class));
add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/code-comments", PullRequestCodeCommentsPage.class));
add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/changes", PullRequestChangesPage.class));
add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/merge-preview", MergePreviewPage.class));
add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/invalid", InvalidPullRequestPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/boards", IssueBoardsPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/boards/${board}", IssueBoardsPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/list", ProjectIssueListPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/${issue}", IssueActivitiesPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/${issue}/activities", IssueActivitiesPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/${issue}/commits", IssueCommitsPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/${issue}/pull-requests", IssuePullRequestsPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/${issue}/builds", IssueBuildsPage.class));
add(new DynamicPathPageMapper("projects/${project}/issues/new", NewIssuePage.class));
add(new DynamicPathPageMapper("projects/${project}/milestones", MilestoneListPage.class));
add(new DynamicPathPageMapper("projects/${project}/milestones/${milestone}", MilestoneDetailPage.class));
add(new DynamicPathPageMapper("projects/${project}/milestones/${milestone}/edit", MilestoneEditPage.class));
add(new DynamicPathPageMapper("projects/${project}/milestones/new", NewMilestonePage.class));
add(new DynamicPathPageMapper("projects/${project}/builds", ProjectBuildsPage.class));
add(new DynamicPathPageMapper("projects/${project}/builds/${build}", BuildDashboardPage.class));
add(new DynamicPathPageMapper("projects/${project}/builds/${build}/log", BuildLogPage.class));
add(new DynamicPathPageMapper("projects/${project}/builds/${build}/changes", BuildChangesPage.class));
add(new DynamicPathPageMapper("projects/${project}/builds/${build}/fixed-issues", FixedIssuesPage.class));
add(new DynamicPathPageMapper("projects/${project}/builds/${build}/artifacts", BuildArtifactsPage.class));
add(new DynamicPathPageMapper("projects/${project}/builds/${build}/invalid", InvalidBuildPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/general", GeneralSecuritySettingPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/authorizations", ProjectAuthorizationsPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/avatar-edit", AvatarEditPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/branch-protection", BranchProtectionsPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/tag-protection", TagProtectionsPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/build/job-secrets", JobSecretsPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/build/action-authorizations", ActionAuthorizationsPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/build/build-preserve-rules", BuildPreservationsPage.class));
add(new DynamicPathPageMapper("projects/${project}/settings/web-hooks", WebHooksPage.class));
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_1893_1
|
crossvul-java_data_bad_1893_2
|
package io.onedev.server.web.component.markdown;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.wicket.util.crypt.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.onedev.server.persistence.annotation.Sessional;
@SuppressWarnings("serial")
@Singleton
public class AttachmentUploadServlet extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(AttachmentUploadServlet.class);
@Sessional
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileName = URLDecoder.decode(request.getHeader("File-Name"), StandardCharsets.UTF_8.name());
AttachmentSupport attachmentSuppport = (AttachmentSupport) SerializationUtils
.deserialize(Base64.decodeBase64(request.getHeader("Attachment-Support")));
try {
String attachmentName = attachmentSuppport.saveAttachment(fileName, request.getInputStream());
response.getWriter().print(URLEncoder.encode(attachmentName, StandardCharsets.UTF_8.name()));
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
logger.error("Error uploading attachment.", e);
if (e.getMessage() != null)
response.getWriter().print(e.getMessage());
else
response.getWriter().print("Internal server error");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_1893_2
|
crossvul-java_data_bad_1894_10
|
package io.onedev.server.plugin.executor.kubernetes;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import org.apache.commons.lang.SerializationUtils;
import com.google.common.collect.Lists;
import io.onedev.commons.utils.TarUtils;
import io.onedev.k8shelper.CacheAllocationRequest;
import io.onedev.k8shelper.CacheInstance;
import io.onedev.server.GeneralException;
import io.onedev.server.buildspec.job.Job;
import io.onedev.server.buildspec.job.JobContext;
import io.onedev.server.buildspec.job.JobManager;
@Path("/k8s")
@Consumes(MediaType.WILDCARD)
@Singleton
public class KubernetesResource {
public static final String TEST_JOB_TOKEN = UUID.randomUUID().toString();
private final JobManager jobManager;
@Context
private HttpServletRequest request;
@Inject
public KubernetesResource(JobManager jobManager) {
this.jobManager = jobManager;
}
@Path("/job-context")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET
public byte[] getJobContext() {
JobContext context = jobManager.getJobContext(getJobToken(), true);
Map<String, Object> contextMap = new HashMap<>();
contextMap.put("commands", context.getCommands());
contextMap.put("retrieveSource", context.isRetrieveSource());
contextMap.put("cloneDepth", context.getCloneDepth());
contextMap.put("projectName", context.getProjectName());
contextMap.put("cloneInfo", context.getCloneInfo());
contextMap.put("commitHash", context.getCommitId().name());
contextMap.put("collectFiles.includes", context.getCollectFiles().getIncludes());
contextMap.put("collectFiles.excludes", context.getCollectFiles().getExcludes());
return SerializationUtils.serialize((Serializable) contextMap);
}
@Path("/allocate-job-caches")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@POST
public byte[] allocateJobCaches(byte[] cacheAllocationRequestBytes) {
CacheAllocationRequest allocationRequest = (CacheAllocationRequest) SerializationUtils
.deserialize(cacheAllocationRequestBytes);
return SerializationUtils.serialize((Serializable) jobManager.allocateJobCaches(
getJobToken(), allocationRequest.getCurrentTime(), allocationRequest.getInstances()));
}
@Path("/report-job-caches")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@POST
public void reportJobCaches(byte[] cacheInstanceBytes) {
@SuppressWarnings("unchecked")
Collection<CacheInstance> cacheInstances = (Collection<CacheInstance>) SerializationUtils
.deserialize(cacheInstanceBytes);
jobManager.reportJobCaches(getJobToken(), cacheInstances);
}
@Path("/download-dependencies")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET
public Response downloadDependencies() {
StreamingOutput os = new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException {
JobContext context = jobManager.getJobContext(getJobToken(), true);
TarUtils.tar(context.getServerWorkspace(), Lists.newArrayList("**"),
new ArrayList<>(), output);
output.flush();
}
};
return Response.ok(os).build();
}
@POST
@Path("/upload-outcomes")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response uploadOutcomes(InputStream is) {
JobContext context = jobManager.getJobContext(getJobToken(), true);
TarUtils.untar(is, context.getServerWorkspace());
return Response.ok().build();
}
@GET
@Path("/test")
public Response test() {
String jobToken = Job.getToken(request);
if (TEST_JOB_TOKEN.equals(jobToken))
return Response.ok().build();
else
return Response.status(400).entity("Invalid or missing job token").build();
}
private String getJobToken() {
String jobToken = Job.getToken(request);
if (jobToken != null)
return jobToken;
else
throw new GeneralException("Job token is expected");
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_1894_10
|
crossvul-java_data_good_42_3
|
package org.bouncycastle.pqc.crypto.xmss;
import java.io.IOException;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Pack;
/**
* XMSS Private Key.
*/
public final class XMSSPrivateKeyParameters
extends AsymmetricKeyParameter
implements XMSSStoreableObjectInterface
{
/**
* XMSS parameters object.
*/
private final XMSSParameters params;
/**
* Secret for the derivation of WOTS+ secret keys.
*/
private final byte[] secretKeySeed;
/**
* Secret for the randomization of message digests during signature
* creation.
*/
private final byte[] secretKeyPRF;
/**
* Public seed for the randomization of hashes.
*/
private final byte[] publicSeed;
/**
* Public root of binary tree.
*/
private final byte[] root;
/**
* BDS state.
*/
private final BDS bdsState;
private XMSSPrivateKeyParameters(Builder builder)
{
super(true);
params = builder.params;
if (params == null)
{
throw new NullPointerException("params == null");
}
int n = params.getDigestSize();
byte[] privateKey = builder.privateKey;
if (privateKey != null)
{
if (builder.xmss == null)
{
throw new NullPointerException("xmss == null");
}
/* import */
int height = params.getHeight();
int indexSize = 4;
int secretKeySize = n;
int secretKeyPRFSize = n;
int publicSeedSize = n;
int rootSize = n;
/*
int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;
if (privateKey.length != totalSize) {
throw new ParseException("private key has wrong size", 0);
}
*/
int position = 0;
int index = Pack.bigEndianToInt(privateKey, position);
if (!XMSSUtil.isIndexValid(height, index))
{
throw new IllegalArgumentException("index out of bounds");
}
position += indexSize;
secretKeySeed = XMSSUtil.extractBytesAtOffset(privateKey, position, secretKeySize);
position += secretKeySize;
secretKeyPRF = XMSSUtil.extractBytesAtOffset(privateKey, position, secretKeyPRFSize);
position += secretKeyPRFSize;
publicSeed = XMSSUtil.extractBytesAtOffset(privateKey, position, publicSeedSize);
position += publicSeedSize;
root = XMSSUtil.extractBytesAtOffset(privateKey, position, rootSize);
position += rootSize;
/* import BDS state */
byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(privateKey, position, privateKey.length - position);
try
{
BDS bdsImport = (BDS)XMSSUtil.deserialize(bdsStateBinary, BDS.class);
bdsImport.setXMSS(builder.xmss);
bdsImport.validate();
if (bdsImport.getIndex() != index)
{
throw new IllegalStateException("serialized BDS has wrong index");
}
bdsState = bdsImport;
}
catch (IOException e)
{
throw new IllegalArgumentException(e.getMessage(), e);
}
catch (ClassNotFoundException e)
{
throw new IllegalArgumentException(e.getMessage(), e);
}
}
else
{
/* set */
byte[] tmpSecretKeySeed = builder.secretKeySeed;
if (tmpSecretKeySeed != null)
{
if (tmpSecretKeySeed.length != n)
{
throw new IllegalArgumentException("size of secretKeySeed needs to be equal size of digest");
}
secretKeySeed = tmpSecretKeySeed;
}
else
{
secretKeySeed = new byte[n];
}
byte[] tmpSecretKeyPRF = builder.secretKeyPRF;
if (tmpSecretKeyPRF != null)
{
if (tmpSecretKeyPRF.length != n)
{
throw new IllegalArgumentException("size of secretKeyPRF needs to be equal size of digest");
}
secretKeyPRF = tmpSecretKeyPRF;
}
else
{
secretKeyPRF = new byte[n];
}
byte[] tmpPublicSeed = builder.publicSeed;
if (tmpPublicSeed != null)
{
if (tmpPublicSeed.length != n)
{
throw new IllegalArgumentException("size of publicSeed needs to be equal size of digest");
}
publicSeed = tmpPublicSeed;
}
else
{
publicSeed = new byte[n];
}
byte[] tmpRoot = builder.root;
if (tmpRoot != null)
{
if (tmpRoot.length != n)
{
throw new IllegalArgumentException("size of root needs to be equal size of digest");
}
root = tmpRoot;
}
else
{
root = new byte[n];
}
BDS tmpBDSState = builder.bdsState;
if (tmpBDSState != null)
{
bdsState = tmpBDSState;
}
else
{
if (builder.index < ((1 << params.getHeight()) - 2) && tmpPublicSeed != null && tmpSecretKeySeed != null)
{
bdsState = new BDS(params, tmpPublicSeed, tmpSecretKeySeed, (OTSHashAddress)new OTSHashAddress.Builder().build(), builder.index);
}
else
{
bdsState = new BDS(params, builder.index);
}
}
}
}
public static class Builder
{
/* mandatory */
private final XMSSParameters params;
/* optional */
private int index = 0;
private byte[] secretKeySeed = null;
private byte[] secretKeyPRF = null;
private byte[] publicSeed = null;
private byte[] root = null;
private BDS bdsState = null;
private byte[] privateKey = null;
private XMSSParameters xmss = null;
public Builder(XMSSParameters params)
{
super();
this.params = params;
}
public Builder withIndex(int val)
{
index = val;
return this;
}
public Builder withSecretKeySeed(byte[] val)
{
secretKeySeed = XMSSUtil.cloneArray(val);
return this;
}
public Builder withSecretKeyPRF(byte[] val)
{
secretKeyPRF = XMSSUtil.cloneArray(val);
return this;
}
public Builder withPublicSeed(byte[] val)
{
publicSeed = XMSSUtil.cloneArray(val);
return this;
}
public Builder withRoot(byte[] val)
{
root = XMSSUtil.cloneArray(val);
return this;
}
public Builder withBDSState(BDS valBDS)
{
bdsState = valBDS;
return this;
}
public Builder withPrivateKey(byte[] privateKeyVal, XMSSParameters xmssParameters)
{
privateKey = XMSSUtil.cloneArray(privateKeyVal);
xmss = xmssParameters;
return this;
}
public XMSSPrivateKeyParameters build()
{
return new XMSSPrivateKeyParameters(this);
}
}
public byte[] toByteArray()
{
/* index || secretKeySeed || secretKeyPRF || publicSeed || root */
int n = params.getDigestSize();
int indexSize = 4;
int secretKeySize = n;
int secretKeyPRFSize = n;
int publicSeedSize = n;
int rootSize = n;
int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;
byte[] out = new byte[totalSize];
int position = 0;
/* copy index */
Pack.intToBigEndian(bdsState.getIndex(), out, position);
position += indexSize;
/* copy secretKeySeed */
XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position);
position += secretKeySize;
/* copy secretKeyPRF */
XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position);
position += secretKeyPRFSize;
/* copy publicSeed */
XMSSUtil.copyBytesAtOffset(out, publicSeed, position);
position += publicSeedSize;
/* copy root */
XMSSUtil.copyBytesAtOffset(out, root, position);
/* concatenate bdsState */
byte[] bdsStateOut = null;
try
{
bdsStateOut = XMSSUtil.serialize(bdsState);
}
catch (IOException e)
{
throw new RuntimeException("error serializing bds state: " + e.getMessage());
}
return Arrays.concatenate(out, bdsStateOut);
}
public int getIndex()
{
return bdsState.getIndex();
}
public byte[] getSecretKeySeed()
{
return XMSSUtil.cloneArray(secretKeySeed);
}
public byte[] getSecretKeyPRF()
{
return XMSSUtil.cloneArray(secretKeyPRF);
}
public byte[] getPublicSeed()
{
return XMSSUtil.cloneArray(publicSeed);
}
public byte[] getRoot()
{
return XMSSUtil.cloneArray(root);
}
BDS getBDSState()
{
return bdsState;
}
public XMSSParameters getParameters()
{
return params;
}
public XMSSPrivateKeyParameters getNextKey()
{
/* prepare authentication path for next leaf */
int treeHeight = this.params.getHeight();
if (this.getIndex() < ((1 << treeHeight) - 1))
{
return new XMSSPrivateKeyParameters.Builder(params)
.withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF)
.withPublicSeed(publicSeed).withRoot(root)
.withBDSState(bdsState.getNextState(publicSeed, secretKeySeed, (OTSHashAddress)new OTSHashAddress.Builder().build())).build();
}
else
{
return new XMSSPrivateKeyParameters.Builder(params)
.withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF)
.withPublicSeed(publicSeed).withRoot(root)
.withBDSState(new BDS(params, getIndex() + 1)).build(); // no more nodes left.
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_3
|
crossvul-java_data_bad_42_5
|
package org.bouncycastle.pqc.math.linearalgebra;
import java.security.SecureRandom;
import java.util.Vector;
/**
* This abstract class defines the finite field <i>GF(2<sup>n</sup>)</i>. It
* holds the extension degree <i>n</i>, the characteristic, the irreducible
* fieldpolynomial and conversion matrices. GF2nField is implemented by the
* classes GF2nPolynomialField and GF2nONBField.
*
* @see GF2nONBField
* @see GF2nPolynomialField
*/
public abstract class GF2nField
{
protected final SecureRandom random;
/**
* the degree of this field
*/
protected int mDegree;
/**
* the irreducible fieldPolynomial stored in normal order (also for ONB)
*/
protected GF2Polynomial fieldPolynomial;
/**
* holds a list of GF2nFields to which elements have been converted and thus
* a COB-Matrix exists
*/
protected Vector fields;
/**
* the COB matrices
*/
protected Vector matrices;
protected GF2nField(SecureRandom random)
{
this.random = random;
}
/**
* Returns the degree <i>n</i> of this field.
*
* @return the degree <i>n</i> of this field
*/
public final int getDegree()
{
return mDegree;
}
/**
* Returns the fieldpolynomial as a new Bitstring.
*
* @return a copy of the fieldpolynomial as a new Bitstring
*/
public final GF2Polynomial getFieldPolynomial()
{
if (fieldPolynomial == null)
{
computeFieldPolynomial();
}
return new GF2Polynomial(fieldPolynomial);
}
/**
* Decides whether the given object <tt>other</tt> is the same as this
* field.
*
* @param other another object
* @return (this == other)
*/
public final boolean equals(Object other)
{
if (other == null || !(other instanceof GF2nField))
{
return false;
}
GF2nField otherField = (GF2nField)other;
if (otherField.mDegree != mDegree)
{
return false;
}
if (!fieldPolynomial.equals(otherField.fieldPolynomial))
{
return false;
}
if ((this instanceof GF2nPolynomialField)
&& !(otherField instanceof GF2nPolynomialField))
{
return false;
}
if ((this instanceof GF2nONBField)
&& !(otherField instanceof GF2nONBField))
{
return false;
}
return true;
}
/**
* @return the hash code of this field
*/
public int hashCode()
{
return mDegree + fieldPolynomial.hashCode();
}
/**
* Computes a random root from the given irreducible fieldpolynomial
* according to IEEE 1363 algorithm A.5.6. This cal take very long for big
* degrees.
*
* @param B0FieldPolynomial the fieldpolynomial if the other basis as a Bitstring
* @return a random root of BOFieldPolynomial in representation according to
* this field
* @see "P1363 A.5.6, p103f"
*/
protected abstract GF2nElement getRandomRoot(GF2Polynomial B0FieldPolynomial);
/**
* Computes the change-of-basis matrix for basis conversion according to
* 1363. The result is stored in the lists fields and matrices.
*
* @param B1 the GF2nField to convert to
* @see "P1363 A.7.3, p111ff"
*/
protected abstract void computeCOBMatrix(GF2nField B1);
/**
* Computes the fieldpolynomial. This can take a long time for big degrees.
*/
protected abstract void computeFieldPolynomial();
/**
* Inverts the given matrix represented as bitstrings.
*
* @param matrix the matrix to invert as a Bitstring[]
* @return matrix^(-1)
*/
protected final GF2Polynomial[] invertMatrix(GF2Polynomial[] matrix)
{
GF2Polynomial[] a = new GF2Polynomial[matrix.length];
GF2Polynomial[] inv = new GF2Polynomial[matrix.length];
GF2Polynomial dummy;
int i, j;
// initialize a as a copy of matrix and inv as E(inheitsmatrix)
for (i = 0; i < mDegree; i++)
{
try
{
a[i] = new GF2Polynomial(matrix[i]);
inv[i] = new GF2Polynomial(mDegree);
inv[i].setBit(mDegree - 1 - i);
}
catch (RuntimeException BDNEExc)
{
BDNEExc.printStackTrace();
}
}
// construct triangle matrix so that for each a[i] the first i bits are
// zero
for (i = 0; i < mDegree - 1; i++)
{
// find column where bit i is set
j = i;
while ((j < mDegree) && !a[j].testBit(mDegree - 1 - i))
{
j++;
}
if (j >= mDegree)
{
throw new RuntimeException(
"GF2nField.invertMatrix: Matrix cannot be inverted!");
}
if (i != j)
{ // swap a[i]/a[j] and inv[i]/inv[j]
dummy = a[i];
a[i] = a[j];
a[j] = dummy;
dummy = inv[i];
inv[i] = inv[j];
inv[j] = dummy;
}
for (j = i + 1; j < mDegree; j++)
{ // add column i to all columns>i
// having their i-th bit set
if (a[j].testBit(mDegree - 1 - i))
{
a[j].addToThis(a[i]);
inv[j].addToThis(inv[i]);
}
}
}
// construct Einheitsmatrix from a
for (i = mDegree - 1; i > 0; i--)
{
for (j = i - 1; j >= 0; j--)
{ // eliminate the i-th bit in all
// columns < i
if (a[j].testBit(mDegree - 1 - i))
{
a[j].addToThis(a[i]);
inv[j].addToThis(inv[i]);
}
}
}
return inv;
}
/**
* Converts the given element in representation according to this field to a
* new element in representation according to B1 using the change-of-basis
* matrix calculated by computeCOBMatrix.
*
* @param elem the GF2nElement to convert
* @param basis the basis to convert <tt>elem</tt> to
* @return <tt>elem</tt> converted to a new element representation
* according to <tt>basis</tt>
* @see GF2nField#computeCOBMatrix
* @see GF2nField#getRandomRoot
* @see GF2nPolynomial
* @see "P1363 A.7 p109ff"
*/
public final GF2nElement convert(GF2nElement elem, GF2nField basis)
throws RuntimeException
{
if (basis == this)
{
return (GF2nElement)elem.clone();
}
if (fieldPolynomial.equals(basis.fieldPolynomial))
{
return (GF2nElement)elem.clone();
}
if (mDegree != basis.mDegree)
{
throw new RuntimeException("GF2nField.convert: B1 has a"
+ " different degree and thus cannot be coverted to!");
}
int i;
GF2Polynomial[] COBMatrix;
i = fields.indexOf(basis);
if (i == -1)
{
computeCOBMatrix(basis);
i = fields.indexOf(basis);
}
COBMatrix = (GF2Polynomial[])matrices.elementAt(i);
GF2nElement elemCopy = (GF2nElement)elem.clone();
if (elemCopy instanceof GF2nONBElement)
{
// remember: ONB treats its bits in reverse order
((GF2nONBElement)elemCopy).reverseOrder();
}
GF2Polynomial bs = new GF2Polynomial(mDegree, elemCopy.toFlexiBigInt());
bs.expandN(mDegree);
GF2Polynomial result = new GF2Polynomial(mDegree);
for (i = 0; i < mDegree; i++)
{
if (bs.vectorMult(COBMatrix[i]))
{
result.setBit(mDegree - 1 - i);
}
}
if (basis instanceof GF2nPolynomialField)
{
return new GF2nPolynomialElement((GF2nPolynomialField)basis,
result);
}
else if (basis instanceof GF2nONBField)
{
GF2nONBElement res = new GF2nONBElement((GF2nONBField)basis,
result.toFlexiBigInt());
// TODO Remember: ONB treats its Bits in reverse order !!!
res.reverseOrder();
return res;
}
else
{
throw new RuntimeException(
"GF2nField.convert: B1 must be an instance of "
+ "GF2nPolynomialField or GF2nONBField!");
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_5
|
crossvul-java_data_good_590_0
|
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import com.facebook.buck.parser.ParserConfig;
import com.facebook.buck.parser.ParserStateObjectInputStream;
import com.facebook.buck.parser.thrift.RemoteDaemonicParserState;
import com.facebook.buck.util.ExitCode;
import com.facebook.buck.util.json.ObjectMappers;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Preconditions;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.annotation.Nullable;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
/** A command for inspecting the artifact cache. */
public class ParserCacheCommand extends AbstractCommand {
@Argument private List<String> arguments = new ArrayList<>();
@Option(name = "--save", usage = "Save the parser cache state to the given file.")
@Nullable
private String saveFilename = null;
@Option(name = "--load", usage = "Load the given parser cache from the given file.")
@Nullable
private String loadFilename = null;
@Option(
name = "--changes",
usage =
"File containing a JSON formatted list of changed files "
+ "that might invalidate the parser cache. The format of the file is an array of "
+ "objects with two keys: \"path\" and \"status\". "
+ "The path is relative to the root cell. "
+ "The status is the same as the one reported by \"hg status\" or \"git status\". "
+ "For example: \"A\", \"?\", \"R\", \"!\" or \"M\"."
)
@Nullable
private String changesPath = null;
@Override
public ExitCode runWithoutHelp(CommandRunnerParams params)
throws IOException, InterruptedException {
if (saveFilename != null && loadFilename != null) {
params.getConsole().printErrorText("Can't use both --load and --save");
return ExitCode.COMMANDLINE_ERROR;
}
if (saveFilename != null) {
invalidateChanges(params);
RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell());
try (FileOutputStream fos = new FileOutputStream(saveFilename);
ZipOutputStream zipos = new ZipOutputStream(fos)) {
zipos.putNextEntry(new ZipEntry("parser_data"));
try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) {
oos.writeObject(state);
}
}
} else if (loadFilename != null) {
try (FileInputStream fis = new FileInputStream(loadFilename);
ZipInputStream zipis = new ZipInputStream(fis)) {
ZipEntry entry = zipis.getNextEntry();
Preconditions.checkState(entry.getName().equals("parser_data"));
try (ObjectInputStream ois = new ParserStateObjectInputStream(zipis)) {
RemoteDaemonicParserState state;
try {
state = (RemoteDaemonicParserState) ois.readObject();
} catch (ClassNotFoundException e) {
params.getConsole().printErrorText("Invalid file format");
return ExitCode.COMMANDLINE_ERROR;
}
params.getParser().restoreParserState(state, params.getCell());
}
}
invalidateChanges(params);
ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class);
if (configView.isParserCacheMutationWarningEnabled()) {
params
.getConsole()
.printErrorText(
params
.getConsole()
.getAnsi()
.asWarningText(
"WARNING: Buck injected a parser state that may not match the local state."));
}
}
return ExitCode.SUCCESS;
}
private void invalidateChanges(CommandRunnerParams params) throws IOException {
if (changesPath == null) {
return;
}
try (FileInputStream is = new FileInputStream(changesPath)) {
JsonNode responseNode = ObjectMappers.READER.readTree(is);
Iterator<JsonNode> iterator = responseNode.elements();
while (iterator.hasNext()) {
JsonNode item = iterator.next();
String path = item.get("path").asText();
String status = item.get("status").asText();
boolean isAdded = false;
boolean isRemoved = false;
if (status.equals("A") || status.equals("?")) {
isAdded = true;
} else if (status.equals("R") || status.equals("!")) {
isRemoved = true;
}
Path fullPath = params.getCell().getRoot().resolve(path).normalize();
params.getParser().invalidateBasedOnPath(fullPath, isAdded || isRemoved);
}
}
}
@Override
public String getShortDescription() {
return "Load and save state of the parser cache";
}
@Override
public boolean isReadOnly() {
return false;
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_590_0
|
crossvul-java_data_bad_42_9
|
package org.bouncycastle.pqc.jcajce.provider.xmss;
import java.io.IOException;
import java.security.PrivateKey;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;
import org.bouncycastle.pqc.asn1.XMSSKeyParams;
import org.bouncycastle.pqc.asn1.XMSSPrivateKey;
import org.bouncycastle.pqc.crypto.xmss.BDS;
import org.bouncycastle.pqc.crypto.xmss.XMSSParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSPrivateKeyParameters;
import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;
import org.bouncycastle.pqc.jcajce.interfaces.XMSSKey;
import org.bouncycastle.util.Arrays;
public class BCXMSSPrivateKey
implements PrivateKey, XMSSKey
{
private final XMSSPrivateKeyParameters keyParams;
private final ASN1ObjectIdentifier treeDigest;
public BCXMSSPrivateKey(
ASN1ObjectIdentifier treeDigest,
XMSSPrivateKeyParameters keyParams)
{
this.treeDigest = treeDigest;
this.keyParams = keyParams;
}
public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
.Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))
.withIndex(xmssPrivateKey.getIndex())
.withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
.withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
.withPublicSeed(xmssPrivateKey.getPublicSeed())
.withRoot(xmssPrivateKey.getRoot());
if (xmssPrivateKey.getBdsState() != null)
{
keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));
}
this.keyParams = keyBuilder.build();
}
catch (ClassNotFoundException e)
{
throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
}
}
public String getAlgorithm()
{
return "XMSS";
}
public String getFormat()
{
return "PKCS#8";
}
public byte[] getEncoded()
{
PrivateKeyInfo pki;
try
{
AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss, new XMSSKeyParams(keyParams.getParameters().getHeight(), new AlgorithmIdentifier(treeDigest)));
pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure());
return pki.getEncoded();
}
catch (IOException e)
{
return null;
}
}
public boolean equals(Object o)
{
if (o == this)
{
return true;
}
if (o instanceof BCXMSSPrivateKey)
{
BCXMSSPrivateKey otherKey = (BCXMSSPrivateKey)o;
return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.toByteArray(), otherKey.keyParams.toByteArray());
}
return false;
}
public int hashCode()
{
return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.toByteArray());
}
CipherParameters getKeyParams()
{
return keyParams;
}
private XMSSPrivateKey createKeyStructure()
{
byte[] keyData = keyParams.toByteArray();
int n = keyParams.getParameters().getDigestSize();
int totalHeight = keyParams.getParameters().getHeight();
int indexSize = 4;
int secretKeySize = n;
int secretKeyPRFSize = n;
int publicSeedSize = n;
int rootSize = n;
int position = 0;
int index = (int)XMSSUtil.bytesToXBigEndian(keyData, position, indexSize);
if (!XMSSUtil.isIndexValid(totalHeight, index))
{
throw new IllegalArgumentException("index out of bounds");
}
position += indexSize;
byte[] secretKeySeed = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeySize);
position += secretKeySize;
byte[] secretKeyPRF = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeyPRFSize);
position += secretKeyPRFSize;
byte[] publicSeed = XMSSUtil.extractBytesAtOffset(keyData, position, publicSeedSize);
position += publicSeedSize;
byte[] root = XMSSUtil.extractBytesAtOffset(keyData, position, rootSize);
position += rootSize;
/* import BDS state */
byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(keyData, position, keyData.length - position);
return new XMSSPrivateKey(index, secretKeySeed, secretKeyPRF, publicSeed, root, bdsStateBinary);
}
ASN1ObjectIdentifier getTreeDigestOID()
{
return treeDigest;
}
public int getHeight()
{
return keyParams.getParameters().getHeight();
}
public String getTreeDigest()
{
return DigestUtil.getXMSSDigestName(treeDigest);
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_9
|
crossvul-java_data_bad_5761_1
|
/**
* License Agreement.
*
* Rich Faces - Natural Ajax for Java Server Faces (JSF)
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.ajax4jsf.resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import org.ajax4jsf.Messages;
import org.ajax4jsf.resource.util.URLToStreamHelper;
import org.ajax4jsf.util.base64.Codec;
import org.ajax4jsf.webapp.WebXml;
import org.apache.commons.digester.Digester;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Produce instances of InternetResource's for any types - jar resource, dynamic
* created image, component-incapsulated etc. Realised as singleton class to
* support cache, configuration etc.
*
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:56:58 $
*
*/
public class ResourceBuilderImpl extends InternetResourceBuilder {
private static final Log log = LogFactory.getLog(ResourceBuilderImpl.class);
private static final String DATA_SEPARATOR = "/DATA/";
private static final String DATA_BYTES_SEPARATOR = "/DATB/";
private static final Pattern DATA_SEPARATOR_PATTERN = Pattern
.compile("/DAT(A|B)/");
private static final ResourceRenderer defaultRenderer = new MimeRenderer(null);
private Map<String, ResourceRenderer> renderers;
/**
* keep resources instances . TODO - put this map to application-scope
* attribute, for support clastering environment.
*/
private Map<String, InternetResource> resources = Collections.synchronizedMap(new HashMap<String, InternetResource>());
private long _startTime;
private Codec codec;
private static final ResourceRenderer scriptRenderer = new ScriptRenderer();
private static final ResourceRenderer styleRenderer = new StyleRenderer();
static {
// renderers.put(".htc",new BehaviorRenderer());
// set in-memory caching ImageIO
Thread thread = Thread.currentThread();
ClassLoader initialTCCL = thread.getContextClassLoader();
try {
ClassLoader systemCL = ClassLoader.getSystemClassLoader();
thread.setContextClassLoader(systemCL);
ImageIO.setUseCache(false);
} finally {
thread.setContextClassLoader(initialTCCL);
}
}
public WebXml getWebXml(FacesContext context) {
WebXml webXml = WebXml.getInstance(context);
if (null == webXml) {
throw new FacesException(
"Resources framework is not initialised, check web.xml for Filter configuration");
}
return webXml;
}
public ResourceBuilderImpl() {
super();
_startTime = System.currentTimeMillis();
codec = new Codec();
renderers = new HashMap<String, ResourceRenderer>();
// append known renderers for extentions.
renderers.put(".gif", new GifRenderer());
ResourceRenderer renderer = new JpegRenderer();
renderers.put(".jpeg", renderer);
renderers.put(".jpg", renderer);
renderers.put(".png", new PngRenderer());
renderers.put(".js", getScriptRenderer());
renderers.put(".css", getStyleRenderer());
renderers.put(".log", new LogfileRenderer());
renderers.put(".html", new HTMLRenderer());
renderers.put(".xhtml", new MimeRenderer("application/xhtml+xml"));
renderers.put(".xml", new MimeRenderer("text/xml"));
renderers.put(".xcss", new TemplateCSSRenderer());
renderers.put(".swf", new MimeRenderer("application/x-shockwave-flash"));
}
/**
* @throws FacesException
*/
protected void registerResources() throws FacesException {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> e = loader
.getResources("META-INF/resources-config.xml");
while (e.hasMoreElements()) {
URL resource = e.nextElement();
registerConfig(resource);
}
} catch (IOException e) {
throw new FacesException(e);
}
}
private void registerConfig(URL resourceConfig) {
try {
if (log.isDebugEnabled()) {
log.debug("Process resources configuration file "
+ resourceConfig.toExternalForm());
}
InputStream in = URLToStreamHelper.urlToStream(resourceConfig);
try {
Digester digester = new Digester();
digester.setValidating(false);
digester.setEntityResolver(new EntityResolver() {
// Dummi resolver - alvays do nothing
public InputSource resolveEntity(String publicId,
String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
digester.setNamespaceAware(false);
digester.setUseContextClassLoader(true);
digester.push(this);
digester.addObjectCreate("resource-config/resource", "class",
JarResource.class);
digester.addObjectCreate("resource-config/resource/renderer",
"class", HTMLRenderer.class);
digester.addCallMethod(
"resource-config/resource/renderer/content-type",
"setContentType", 0);
digester.addSetNext("resource-config/resource/renderer",
"setRenderer", ResourceRenderer.class.getName());
digester.addCallMethod("resource-config/resource/name",
"setKey", 0);
digester.addCallMethod("resource-config/resource/path",
"setPath", 0);
digester.addCallMethod("resource-config/resource/cacheable",
"setCacheable", 0);
digester.addCallMethod(
"resource-config/resource/session-aware",
"setSessionAware", 0);
digester.addCallMethod("resource-config/resource/property",
"setProperty", 2);
digester.addCallParam("resource-config/resource/property/name",
0);
digester.addCallParam(
"resource-config/resource/property/value", 1);
digester.addCallMethod("resource-config/resource/content-type",
"setContentType", 0);
digester.addSetNext("resource-config/resource", "addResource",
InternetResource.class.getName());
digester.parse(in);
} finally {
in.close();
}
} catch (IOException e) {
throw new FacesException(e);
} catch (SAXException e) {
throw new FacesException(e);
}
}
/**
*/
public void init() throws FacesException {
// TODO - mace codec configurable.
registerResources();
}
/**
* Base point for creating resource. Must detect type and build appropriate
* instance. Currently - make static resource for ordinary request, or
* instance of class.
*
* @param base
* base object for resource ( resourcess in classpath will be get
* relative to it package )
* @param path
* key - path to resource, resource class name etc.
* @return
* @throws FacesException
*/
public InternetResource createResource(Object base, String path)
throws FacesException {
// TODO - detect type of resource ( for example, resources location path
// in Skin
try {
return getResource(path);
} catch (ResourceNotFoundException e) {
try {
return getResource(buildKey(base, path));
} catch (ResourceNotFoundException e1) {
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_INFO,
path));
}
}
}
// path - is class name ?
InternetResource res;
try {
Class<?> resourceClass = Class.forName(path);
res = createDynamicResource(path, resourceClass);
} catch (Exception e) {
try {
res = createJarResource(base, path);
} catch (ResourceNotFoundException ex) {
res = createStaticResource(path);
}
// TODO - if resource not found, create static ?
}
return res;
}
private String buildKey(Object base, String path) {
if (path.startsWith("/")) {
return path.substring(1);
}
if (null == base) {
return path;
}
StringBuffer packageName = new StringBuffer(base.getClass()
.getPackage().getName().replace('.', '/'));
return packageName.append("/").append(path).toString();
}
public String getUri(InternetResource resource, FacesContext context,
Object storeData) {
StringBuffer uri = new StringBuffer();// ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
uri.append(resource.getKey());
// append serialized data as Base-64 encoded request string.
if (storeData != null) {
try {
byte[] objectData;
if (storeData instanceof byte[]) {
objectData = (byte[]) storeData;
uri.append(DATA_BYTES_SEPARATOR);
} else {
ByteArrayOutputStream dataSteram = new ByteArrayOutputStream(
1024);
ObjectOutputStream objStream = new ObjectOutputStream(
dataSteram);
objStream.writeObject(storeData);
objStream.flush();
objStream.close();
dataSteram.close();
objectData = dataSteram.toByteArray();
uri.append(DATA_SEPARATOR);
}
byte[] dataArray = encrypt(objectData);
uri.append(new String(dataArray, "ISO-8859-1"));
// / byte[] objectData = dataSteram.toByteArray();
// / uri.append("?").append(new
// String(Base64.encodeBase64(objectData),
// / "ISO-8859-1"));
} catch (Exception e) {
// Ignore errors, log it
log.error(Messages
.getMessage(Messages.QUERY_STRING_BUILDING_ERROR), e);
}
}
boolean isGlobal = !resource.isSessionAware();
String resourceURL = getWebXml(context).getFacesResourceURL(context,
uri.toString(), isGlobal);// context.getApplication().getViewHandler().getResourceURL(context,uri.toString());
if (!isGlobal) {
resourceURL = context.getExternalContext().encodeResourceURL(
resourceURL);
}
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
resource.getKey(), resourceURL));
}
return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
}
/**
* @param key
* @return
*/
public InternetResource getResourceForKey(String key)
throws ResourceNotFoundException {
Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key);
if (matcher.find()) {
int data = matcher.start();
key = key.substring(0, data);
}
return getResource(key);
}
public Object getResourceDataForKey(String key) {
Object data = null;
String dataString = null;
Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key);
if (matcher.find()) {
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage(
Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key,
dataString));
}
int dataStart = matcher.end();
dataString = key.substring(dataStart);
byte[] objectArray = null;
byte[] dataArray;
try {
dataArray = dataString.getBytes("ISO-8859-1");
objectArray = decrypt(dataArray);
} catch (UnsupportedEncodingException e1) {
// default encoding always presented.
}
if ("B".equals(matcher.group(1))) {
data = objectArray;
} else {
try {
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(objectArray));
data = in.readObject();
} catch (StreamCorruptedException e) {
log.error(Messages
.getMessage(Messages.STREAM_CORRUPTED_ERROR), e);
} catch (IOException e) {
log.error(Messages
.getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR),
e);
} catch (ClassNotFoundException e) {
log
.error(
Messages
.getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR),
e);
}
}
}
return data;
}
public InternetResource getResource(String path)
throws ResourceNotFoundException {
InternetResource internetResource = (InternetResource) resources
.get(path);
if (null == internetResource) {
throw new ResourceNotFoundException("Resource not registered : "
+ path);
} else {
return internetResource;
}
}
public void addResource(InternetResource resource) {
resources.put(resource.getKey(), resource);
ResourceRenderer renderer = resource.getRenderer(null);
if (renderer == null) {
setRenderer(resource, resource.getKey());
}
}
public void addResource(String key, InternetResource resource) {
resources.put(key, resource);
resource.setKey(key);
// TODO - set renderer ?
}
// public String getFacesResourceKey(HttpServletRequest request) {
// return getWebXml(context).getFacesResourceKey(request);
// }
public String getFacesResourceURL(FacesContext context, String Url, boolean isGlobal) {
return getWebXml(context).getFacesResourceURL(context, Url, isGlobal);
}
/**
* Build resource for link to static context in webapp.
*
* @param path
* @return
* @throws FacesException
*/
protected InternetResource createStaticResource(String path)
throws ResourceNotFoundException, FacesException {
FacesContext context = FacesContext.getCurrentInstance();
if (null != context) {
if (context.getExternalContext().getContext() instanceof ServletContext) {
ServletContext servletContext = (ServletContext) context
.getExternalContext().getContext();
InputStream in = servletContext.getResourceAsStream(path);
if (null != in) {
InternetResourceBase res = new StaticResource(path);
setRenderer(res, path);
res.setLastModified(new Date(getStartTime()));
addResource(path, res);
try {
in.close();
} catch (IOException e) {
}
return res;
}
}
}
throw new ResourceNotFoundException(Messages.getMessage(
Messages.STATIC_RESOURCE_NOT_FOUND_ERROR, path));
}
private void setRenderer(InternetResource res, String path)
throws FacesException {
int lastPoint = path.lastIndexOf('.');
if (lastPoint > 0) {
String ext = path.substring(lastPoint);
ResourceRenderer resourceRenderer = getRendererByExtension(ext);
if (null != resourceRenderer) {
res.setRenderer(resourceRenderer);
} else {
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage(
Messages.NO_RESOURCE_REGISTERED_ERROR_2, path,
renderers.keySet()));
}
// String mimeType = servletContext.getMimeType(path);
res.setRenderer(defaultRenderer);
}
}
}
/**
* @param ext
* @return
*/
protected ResourceRenderer getRendererByExtension(String ext) {
return renderers
.get(ext);
}
/**
* Create resurce to send from classpath relative to base class.
*
* @param base
* @param path
* @return
* @throws FacesException
*/
protected InternetResource createJarResource(Object base, String path)
throws ResourceNotFoundException, FacesException {
String key = buildKey(base, path);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (null != loader.getResource(key)) {
JarResource res = new JarResource(key);
setRenderer(res, path);
res.setLastModified(new Date(getStartTime()));
addResource(key, res);
return res;
} else {
throw new ResourceNotFoundException(Messages.getMessage(
Messages.NO_RESOURCE_EXISTS_ERROR, key));
}
}
/**
* Create resource by instatiate given class.
*
* @param path
* @param instatiate
* @return
*/
protected InternetResource createDynamicResource(String path,
Class<?> instatiate) throws ResourceNotFoundException {
if (InternetResource.class.isAssignableFrom(instatiate)) {
InternetResource resource;
try {
resource = (InternetResource) instatiate.newInstance();
addResource(path, resource);
} catch (Exception e) {
String message = Messages.getMessage(
Messages.INSTANTIATE_RESOURCE_ERROR, instatiate
.toString());
log.error(message, e);
throw new ResourceNotFoundException(message, e);
}
return resource;
}
throw new FacesException(Messages
.getMessage(Messages.INSTANTIATE_CLASS_ERROR));
}
/**
* Create resource by instatiate {@link UserResource} class with given
* properties ( or got from cache ).
*
* @param cacheable
* @param session
* @param mime
* @return
* @throws FacesException
*/
public InternetResource createUserResource(boolean cacheable,
boolean session, String mime) throws FacesException {
String path = getUserResourceKey(cacheable, session, mime);
InternetResource userResource;
try {
userResource = getResource(path);
} catch (ResourceNotFoundException e) {
userResource = new UserResource(cacheable, session, mime);
addResource(path, userResource);
}
return userResource;
}
/**
* Generate resource key for user-generated resource with given properties.
*
* @param cacheable
* @param session
* @param mime
* @return
*/
private String getUserResourceKey(boolean cacheable, boolean session,
String mime) {
StringBuffer pathBuffer = new StringBuffer(UserResource.class.getName());
pathBuffer.append(cacheable ? "/c" : "/n");
pathBuffer.append(session ? "/s" : "/n");
if (null != mime) {
pathBuffer.append('/').append(mime.hashCode());
}
String path = pathBuffer.toString();
return path;
}
/**
* @return Returns the startTime for application.
*/
public long getStartTime() {
return _startTime;
}
protected byte[] encrypt(byte[] src) {
try {
Deflater compressor = new Deflater(Deflater.BEST_SPEED);
byte[] compressed = new byte[src.length + 100];
compressor.setInput(src);
compressor.finish();
int totalOut = compressor.deflate(compressed);
byte[] zipsrc = new byte[totalOut];
System.arraycopy(compressed, 0, zipsrc, 0, totalOut);
compressor.end();
return codec.encode(zipsrc);
} catch (Exception e) {
throw new FacesException("Error encode resource data", e);
}
}
protected byte[] decrypt(byte[] src) {
try {
byte[] zipsrc = codec.decode(src);
Inflater decompressor = new Inflater();
byte[] uncompressed = new byte[zipsrc.length * 5];
decompressor.setInput(zipsrc);
int totalOut = decompressor.inflate(uncompressed);
byte[] out = new byte[totalOut];
System.arraycopy(uncompressed, 0, out, 0, totalOut);
decompressor.end();
return out;
} catch (Exception e) {
throw new FacesException("Error decode resource data", e);
}
}
@Override
public ResourceRenderer getScriptRenderer() {
return scriptRenderer;
}
@Override
public ResourceRenderer getStyleRenderer() {
return styleRenderer;
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_5761_1
|
crossvul-java_data_bad_590_0
|
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import com.facebook.buck.parser.ParserConfig;
import com.facebook.buck.parser.thrift.RemoteDaemonicParserState;
import com.facebook.buck.util.ExitCode;
import com.facebook.buck.util.json.ObjectMappers;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Preconditions;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.annotation.Nullable;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
/** A command for inspecting the artifact cache. */
public class ParserCacheCommand extends AbstractCommand {
@Argument private List<String> arguments = new ArrayList<>();
@Option(name = "--save", usage = "Save the parser cache state to the given file.")
@Nullable
private String saveFilename = null;
@Option(name = "--load", usage = "Load the given parser cache from the given file.")
@Nullable
private String loadFilename = null;
@Option(
name = "--changes",
usage =
"File containing a JSON formatted list of changed files "
+ "that might invalidate the parser cache. The format of the file is an array of "
+ "objects with two keys: \"path\" and \"status\". "
+ "The path is relative to the root cell. "
+ "The status is the same as the one reported by \"hg status\" or \"git status\". "
+ "For example: \"A\", \"?\", \"R\", \"!\" or \"M\"."
)
@Nullable
private String changesPath = null;
@Override
public ExitCode runWithoutHelp(CommandRunnerParams params)
throws IOException, InterruptedException {
if (saveFilename != null && loadFilename != null) {
params.getConsole().printErrorText("Can't use both --load and --save");
return ExitCode.COMMANDLINE_ERROR;
}
if (saveFilename != null) {
invalidateChanges(params);
RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell());
try (FileOutputStream fos = new FileOutputStream(saveFilename);
ZipOutputStream zipos = new ZipOutputStream(fos)) {
zipos.putNextEntry(new ZipEntry("parser_data"));
try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) {
oos.writeObject(state);
}
}
} else if (loadFilename != null) {
try (FileInputStream fis = new FileInputStream(loadFilename);
ZipInputStream zipis = new ZipInputStream(fis)) {
ZipEntry entry = zipis.getNextEntry();
Preconditions.checkState(entry.getName().equals("parser_data"));
try (ObjectInputStream ois = new ObjectInputStream(zipis)) {
RemoteDaemonicParserState state;
try {
state = (RemoteDaemonicParserState) ois.readObject();
} catch (ClassNotFoundException e) {
params.getConsole().printErrorText("Invalid file format");
return ExitCode.COMMANDLINE_ERROR;
}
params.getParser().restoreParserState(state, params.getCell());
}
}
invalidateChanges(params);
ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class);
if (configView.isParserCacheMutationWarningEnabled()) {
params
.getConsole()
.printErrorText(
params
.getConsole()
.getAnsi()
.asWarningText(
"WARNING: Buck injected a parser state that may not match the local state."));
}
}
return ExitCode.SUCCESS;
}
private void invalidateChanges(CommandRunnerParams params) throws IOException {
if (changesPath == null) {
return;
}
try (FileInputStream is = new FileInputStream(changesPath)) {
JsonNode responseNode = ObjectMappers.READER.readTree(is);
Iterator<JsonNode> iterator = responseNode.elements();
while (iterator.hasNext()) {
JsonNode item = iterator.next();
String path = item.get("path").asText();
String status = item.get("status").asText();
boolean isAdded = false;
boolean isRemoved = false;
if (status.equals("A") || status.equals("?")) {
isAdded = true;
} else if (status.equals("R") || status.equals("!")) {
isRemoved = true;
}
Path fullPath = params.getCell().getRoot().resolve(path).normalize();
params.getParser().invalidateBasedOnPath(fullPath, isAdded || isRemoved);
}
}
}
@Override
public String getShortDescription() {
return "Load and save state of the parser cache";
}
@Override
public boolean isReadOnly() {
return false;
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_590_0
|
crossvul-java_data_bad_1893_3
|
package io.onedev.server.web.component.markdown;
import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxChannel;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.FormComponentPanel;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.apache.wicket.util.crypt.Base64;
import org.unbescape.javascript.JavaScriptEscape;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import io.onedev.commons.launcher.loader.AppLoader;
import io.onedev.server.OneDev;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.model.Build;
import io.onedev.server.model.Issue;
import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.User;
import io.onedev.server.util.markdown.MarkdownManager;
import io.onedev.server.util.validation.ProjectNameValidator;
import io.onedev.server.web.avatar.AvatarManager;
import io.onedev.server.web.behavior.AbstractPostAjaxBehavior;
import io.onedev.server.web.component.floating.FloatingPanel;
import io.onedev.server.web.component.link.DropdownLink;
import io.onedev.server.web.component.markdown.emoji.EmojiOnes;
import io.onedev.server.web.component.modal.ModalPanel;
import io.onedev.server.web.page.project.ProjectPage;
import io.onedev.server.web.page.project.blob.render.BlobRenderContext;
@SuppressWarnings("serial")
public class MarkdownEditor extends FormComponentPanel<String> {
protected static final int ATWHO_LIMIT = 10;
private final boolean compactMode;
private final boolean initialSplit;
private final BlobRenderContext blobRenderContext;
private WebMarkupContainer container;
private TextArea<String> input;
private AbstractPostAjaxBehavior ajaxBehavior;
/**
* @param id
* component id of the editor
* @param model
* markdown model of the editor
* @param compactMode
* editor in compact mode occupies horizontal space and is suitable
* to be used in places such as comment aside the code
*/
public MarkdownEditor(String id, IModel<String> model, boolean compactMode,
@Nullable BlobRenderContext blobRenderContext) {
super(id, model);
this.compactMode = compactMode;
String cookieKey;
if (compactMode)
cookieKey = "markdownEditor.compactMode.split";
else
cookieKey = "markdownEditor.normalMode.split";
WebRequest request = (WebRequest) RequestCycle.get().getRequest();
Cookie cookie = request.getCookie(cookieKey);
initialSplit = cookie!=null && "true".equals(cookie.getValue());
this.blobRenderContext = blobRenderContext;
}
@Override
protected void onModelChanged() {
super.onModelChanged();
input.setModelObject(getModelObject());
}
public void clearMarkdown() {
setModelObject("");
input.setConvertedInput(null);
}
private String renderInput(String input) {
if (StringUtils.isNotBlank(input)) {
// Normalize line breaks to make source position tracking information comparable
// to textarea caret position when sync edit/preview scroll bar
input = StringUtils.replace(input, "\r\n", "\n");
return renderMarkdown(input);
} else {
return "<div class='message'>Nothing to preview</div>";
}
}
protected String renderMarkdown(String markdown) {
Project project ;
if (getPage() instanceof ProjectPage)
project = ((ProjectPage) getPage()).getProject();
else
project = null;
MarkdownManager manager = OneDev.getInstance(MarkdownManager.class);
return manager.process(manager.render(markdown), project, blobRenderContext);
}
@Override
protected void onInitialize() {
super.onInitialize();
container = new WebMarkupContainer("container");
container.setOutputMarkupId(true);
add(container);
WebMarkupContainer editLink = new WebMarkupContainer("editLink");
WebMarkupContainer splitLink = new WebMarkupContainer("splitLink");
WebMarkupContainer preview = new WebMarkupContainer("preview");
WebMarkupContainer edit = new WebMarkupContainer("edit");
container.add(editLink);
container.add(splitLink);
container.add(preview);
container.add(edit);
container.add(AttributeAppender.append("class", compactMode?"compact-mode":"normal-mode"));
container.add(new DropdownLink("doReference") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new Fragment(id, "referenceMenuFrag", MarkdownEditor.this) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.setupActionMenu($('#%s'), $('#%s'));",
container.getMarkupId(), getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setOutputMarkupId(true);
}
}.setVisible(getReferenceSupport() != null));
container.add(new DropdownLink("actionMenuTrigger") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new Fragment(id, "actionMenuFrag", MarkdownEditor.this) {
@Override
protected void onInitialize() {
super.onInitialize();
add(new WebMarkupContainer("doMention").setVisible(getUserMentionSupport() != null));
if (getReferenceSupport() != null)
add(new Fragment("doReference", "referenceMenuFrag", MarkdownEditor.this));
else
add(new WebMarkupContainer("doReference").setVisible(false));
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format("onedev.server.markdown.setupActionMenu($('#%s'), $('#%s'));",
container.getMarkupId(), getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setOutputMarkupId(true);
}
});
container.add(new WebMarkupContainer("doMention").setVisible(getUserMentionSupport() != null));
edit.add(input = new TextArea<String>("input", Model.of(getModelObject())));
for (AttributeModifier modifier: getInputModifiers())
input.add(modifier);
if (initialSplit) {
container.add(AttributeAppender.append("class", "split-mode"));
preview.add(new Label("rendered", new LoadableDetachableModel<String>() {
@Override
protected String load() {
return renderInput(input.getConvertedInput());
}
}) {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String script = String.format(
"onedev.server.markdown.initRendered($('#%s>.body>.preview>.markdown-rendered'));",
container.getMarkupId());
response.render(OnDomReadyHeaderItem.forScript(script));
}
}.setEscapeModelStrings(false));
splitLink.add(AttributeAppender.append("class", "active"));
} else {
container.add(AttributeAppender.append("class", "edit-mode"));
preview.add(new WebMarkupContainer("rendered"));
editLink.add(AttributeAppender.append("class", "active"));
}
container.add(new WebMarkupContainer("canAttachFile").setVisible(getAttachmentSupport()!=null));
container.add(ajaxBehavior = new AbstractPostAjaxBehavior() {
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.setChannel(new AjaxChannel("markdown-preview", AjaxChannel.Type.DROP));
}
@Override
protected void respond(AjaxRequestTarget target) {
IRequestParameters params = RequestCycle.get().getRequest().getPostParameters();
String action = params.getParameterValue("action").toString("");
switch (action) {
case "render":
String markdown = params.getParameterValue("param1").toString();
String rendered = renderInput(markdown);
String script = String.format("onedev.server.markdown.onRendered('%s', '%s');",
container.getMarkupId(), JavaScriptEscape.escapeJavaScript(rendered));
target.appendJavaScript(script);
break;
case "emojiQuery":
List<String> emojiNames = new ArrayList<>();
String emojiQuery = params.getParameterValue("param1").toOptionalString();
if (StringUtils.isNotBlank(emojiQuery)) {
emojiQuery = emojiQuery.toLowerCase();
for (String emojiName: EmojiOnes.getInstance().all().keySet()) {
if (emojiName.toLowerCase().contains(emojiQuery))
emojiNames.add(emojiName);
}
emojiNames.sort((name1, name2) -> name1.length() - name2.length());
} else {
emojiNames.add("smile");
emojiNames.add("worried");
emojiNames.add("blush");
emojiNames.add("+1");
emojiNames.add("-1");
}
List<Map<String, String>> emojis = new ArrayList<>();
for (String emojiName: emojiNames) {
if (emojis.size() < ATWHO_LIMIT) {
String emojiCode = EmojiOnes.getInstance().all().get(emojiName);
CharSequence url = RequestCycle.get().urlFor(new PackageResourceReference(
EmojiOnes.class, "icon/" + emojiCode + ".png"), new PageParameters());
Map<String, String> emoji = new HashMap<>();
emoji.put("name", emojiName);
emoji.put("url", url.toString());
emojis.add(emoji);
}
}
String json;
try {
json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(emojis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoEmojiRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "loadEmojis":
emojis = new ArrayList<>();
String urlPattern = RequestCycle.get().urlFor(new PackageResourceReference(EmojiOnes.class,
"icon/FILENAME.png"), new PageParameters()).toString();
for (Map.Entry<String, String> entry: EmojiOnes.getInstance().all().entrySet()) {
Map<String, String> emoji = new HashMap<>();
emoji.put("name", entry.getKey());
emoji.put("url", urlPattern.replace("FILENAME", entry.getValue()));
emojis.add(emoji);
}
try {
json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(emojis);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("onedev.server.markdown.onEmojisLoaded('%s', %s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "userQuery":
String userQuery = params.getParameterValue("param1").toOptionalString();
AvatarManager avatarManager = OneDev.getInstance(AvatarManager.class);
List<Map<String, String>> userList = new ArrayList<>();
for (User user: getUserMentionSupport().findUsers(userQuery, ATWHO_LIMIT)) {
Map<String, String> userMap = new HashMap<>();
userMap.put("name", user.getName());
if (user.getFullName() != null)
userMap.put("fullName", user.getFullName());
String noSpaceName = StringUtils.deleteWhitespace(user.getName());
if (user.getFullName() != null) {
String noSpaceFullName = StringUtils.deleteWhitespace(user.getFullName());
userMap.put("searchKey", noSpaceName + " " + noSpaceFullName);
} else {
userMap.put("searchKey", noSpaceName);
}
String avatarUrl = avatarManager.getAvatarUrl(user);
userMap.put("avatarUrl", avatarUrl);
userList.add(userMap);
}
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(userList);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoUserRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "referenceQuery":
String referenceQuery = params.getParameterValue("param1").toOptionalString();
String referenceQueryType = params.getParameterValue("param2").toOptionalString();
String referenceProjectName = params.getParameterValue("param3").toOptionalString();
List<Map<String, String>> referenceList = new ArrayList<>();
Project referenceProject;
if (StringUtils.isNotBlank(referenceProjectName))
referenceProject = OneDev.getInstance(ProjectManager.class).find(referenceProjectName);
else
referenceProject = null;
if (referenceProject != null || StringUtils.isBlank(referenceProjectName)) {
if ("issue".equals(referenceQueryType)) {
for (Issue issue: getReferenceSupport().findIssues(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "issue");
referenceMap.put("referenceNumber", String.valueOf(issue.getNumber()));
referenceMap.put("referenceTitle", issue.getTitle());
referenceMap.put("searchKey", issue.getNumber() + " " + StringUtils.deleteWhitespace(issue.getTitle()));
referenceList.add(referenceMap);
}
} else if ("pullrequest".equals(referenceQueryType)) {
for (PullRequest request: getReferenceSupport().findPullRequests(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "pull request");
referenceMap.put("referenceNumber", String.valueOf(request.getNumber()));
referenceMap.put("referenceTitle", request.getTitle());
referenceMap.put("searchKey", request.getNumber() + " " + StringUtils.deleteWhitespace(request.getTitle()));
referenceList.add(referenceMap);
}
} else if ("build".equals(referenceQueryType)) {
for (Build build: getReferenceSupport().findBuilds(referenceProject, referenceQuery, ATWHO_LIMIT)) {
Map<String, String> referenceMap = new HashMap<>();
referenceMap.put("referenceType", "build");
referenceMap.put("referenceNumber", String.valueOf(build.getNumber()));
String title;
if (build.getVersion() != null)
title = "(" + build.getVersion() + ") " + build.getJobName();
else
title = build.getJobName();
referenceMap.put("referenceTitle", title);
referenceMap.put("searchKey", build.getNumber() + " " + StringUtils.deleteWhitespace(title));
referenceList.add(referenceMap);
}
}
}
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(referenceList);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
script = String.format("$('#%s').data('atWhoReferenceRenderCallback')(%s);", container.getMarkupId(), json);
target.appendJavaScript(script);
break;
case "selectImage":
case "selectLink":
new ModalPanel(target) {
@Override
protected Component newContent(String id) {
return new InsertUrlPanel(id, MarkdownEditor.this, action.equals("selectImage")) {
@Override
protected void onClose(AjaxRequestTarget target) {
close();
}
};
}
@Override
protected void onClosed() {
super.onClosed();
AjaxRequestTarget target =
Preconditions.checkNotNull(RequestCycle.get().find(AjaxRequestTarget.class));
target.appendJavaScript(String.format("$('#%s textarea').focus();", container.getMarkupId()));
}
};
break;
case "insertUrl":
String name;
try {
name = URLDecoder.decode(params.getParameterValue("param1").toString(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String replaceMessage = params.getParameterValue("param2").toString();
String url = getAttachmentSupport().getAttachmentUrl(name);
insertUrl(target, isWebSafeImage(name), url, name, replaceMessage);
break;
default:
throw new IllegalStateException("Unknown action: " + action);
}
}
});
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
}
@Override
public void convertInput() {
setConvertedInput(input.getConvertedInput());
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forReference(new MarkdownResourceReference()));
String encodedAttachmentSupport;
if (getAttachmentSupport() != null) {
encodedAttachmentSupport = Base64.encodeBase64String(SerializationUtils.serialize(getAttachmentSupport()));
encodedAttachmentSupport = StringUtils.deleteWhitespace(encodedAttachmentSupport);
encodedAttachmentSupport = StringEscapeUtils.escapeEcmaScript(encodedAttachmentSupport);
encodedAttachmentSupport = "'" + encodedAttachmentSupport + "'";
} else {
encodedAttachmentSupport = "undefined";
}
String callback = ajaxBehavior.getCallbackFunction(explicit("action"), explicit("param1"), explicit("param2"),
explicit("param3")).toString();
String autosaveKey = getAutosaveKey();
if (autosaveKey != null)
autosaveKey = "'" + JavaScriptEscape.escapeJavaScript(autosaveKey) + "'";
else
autosaveKey = "undefined";
String script = String.format("onedev.server.markdown.onDomReady('%s', %s, %d, %s, %d, %b, %b, '%s', %s);",
container.getMarkupId(),
callback,
ATWHO_LIMIT,
encodedAttachmentSupport,
getAttachmentSupport()!=null?getAttachmentSupport().getAttachmentMaxSize():0,
getUserMentionSupport() != null,
getReferenceSupport() != null,
JavaScriptEscape.escapeJavaScript(ProjectNameValidator.PATTERN.pattern()),
autosaveKey);
response.render(OnDomReadyHeaderItem.forScript(script));
script = String.format("onedev.server.markdown.onLoad('%s');", container.getMarkupId());
response.render(OnLoadHeaderItem.forScript(script));
}
public void insertUrl(AjaxRequestTarget target, boolean isImage, String url,
String name, @Nullable String replaceMessage) {
String script = String.format("onedev.server.markdown.insertUrl('%s', %s, '%s', '%s', %s);",
container.getMarkupId(), isImage, StringEscapeUtils.escapeEcmaScript(url),
StringEscapeUtils.escapeEcmaScript(name),
replaceMessage!=null?"'"+replaceMessage+"'":"undefined");
target.appendJavaScript(script);
}
public boolean isWebSafeImage(String fileName) {
fileName = fileName.toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
|| fileName.endsWith(".gif") || fileName.endsWith(".png");
}
@Nullable
protected AttachmentSupport getAttachmentSupport() {
return null;
}
@Nullable
protected UserMentionSupport getUserMentionSupport() {
return null;
}
@Nullable
protected AtWhoReferenceSupport getReferenceSupport() {
return null;
}
protected List<AttributeModifier> getInputModifiers() {
return new ArrayList<>();
}
@Nullable
protected String getAutosaveKey() {
return null;
}
@Nullable
public BlobRenderContext getBlobRenderContext() {
return blobRenderContext;
}
static class ReferencedEntity implements Serializable {
String entityType;
String entityTitle;
String entityNumber;
String searchKey;
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_1893_3
|
crossvul-java_data_bad_280_1
|
package com.fasterxml.jackson.databind.deser;
import java.lang.reflect.Type;
import java.util.*;
import com.fasterxml.jackson.annotation.ObjectIdGenerator;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.annotation.ObjectIdResolver;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig;
import com.fasterxml.jackson.databind.deser.impl.*;
import com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer;
import com.fasterxml.jackson.databind.introspect.*;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.util.ArrayBuilders;
import com.fasterxml.jackson.databind.util.ClassUtil;
import com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition;
/**
* Concrete deserializer factory class that adds full Bean deserializer
* construction logic using class introspection.
* Note that factories specifically do not implement any form of caching:
* aside from configuration they are stateless; caching is implemented
* by other components.
*<p>
* Instances of this class are fully immutable as all configuration is
* done by using "fluent factories" (methods that construct new factory
* instances with different configuration, instead of modifying instance).
*/
public class BeanDeserializerFactory
extends BasicDeserializerFactory
implements java.io.Serializable // since 2.1
{
private static final long serialVersionUID = 1;
/**
* Signature of <b>Throwable.initCause</b> method.
*/
private final static Class<?>[] INIT_CAUSE_PARAMS = new Class<?>[] { Throwable.class };
private final static Class<?>[] NO_VIEWS = new Class<?>[0];
/**
* Set of well-known "nasty classes", deserialization of which is considered dangerous
* and should (and is) prevented by default.
*/
private final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES;
static {
Set<String> s = new HashSet<String>();
// Courtesy of [https://github.com/kantega/notsoserial]:
// (and wrt [databind#1599])
s.add("org.apache.commons.collections.functors.InvokerTransformer");
s.add("org.apache.commons.collections.functors.InstantiateTransformer");
s.add("org.apache.commons.collections4.functors.InvokerTransformer");
s.add("org.apache.commons.collections4.functors.InstantiateTransformer");
s.add("org.codehaus.groovy.runtime.ConvertedClosure");
s.add("org.codehaus.groovy.runtime.MethodClosure");
s.add("org.springframework.beans.factory.ObjectFactory");
s.add("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl");
// [databind#1737]; JDK provided
s.add("java.util.logging.FileHandler");
s.add("java.rmi.server.UnicastRemoteObject");
// [databind#1737]; 3rd party
s.add("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor");
s.add("org.springframework.beans.factory.config.PropertyPathFactoryBean");
s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);
}
/**
* Set of class names of types that are never to be deserialized.
*/
private Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
/**
* Globally shareable thread-safe instance which has no additional custom deserializers
* registered
*/
public final static BeanDeserializerFactory instance = new BeanDeserializerFactory(
new DeserializerFactoryConfig());
public BeanDeserializerFactory(DeserializerFactoryConfig config) {
super(config);
}
/**
* Method used by module registration functionality, to construct a new bean
* deserializer factory
* with different configuration settings.
*/
@Override
public DeserializerFactory withConfig(DeserializerFactoryConfig config)
{
if (_factoryConfig == config) {
return this;
}
/* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor;
* and we pretty much have to here either choose between losing subtype instance
* when registering additional deserializers, or losing deserializers.
* Instead, let's actually just throw an error if this method is called when subtype
* has not properly overridden this method; this to indicate problem as soon as possible.
*/
if (getClass() != BeanDeserializerFactory.class) {
throw new IllegalStateException("Subtype of BeanDeserializerFactory ("+getClass().getName()
+") has not properly overridden method 'withAdditionalDeserializers': can not instantiate subtype with "
+"additional deserializer definitions");
}
return new BeanDeserializerFactory(config);
}
/*
/**********************************************************
/* DeserializerFactory API implementation
/**********************************************************
*/
/**
* Method that {@link DeserializerCache}s call to create a new
* deserializer for types other than Collections, Maps, arrays and
* enums.
*/
@Override
public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt,
JavaType type, BeanDescription beanDesc)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
// We may also have custom overrides:
JsonDeserializer<Object> custom = _findCustomBeanDeserializer(type, config, beanDesc);
if (custom != null) {
return custom;
}
/* One more thing to check: do we have an exception type
* (Throwable or its sub-classes)? If so, need slightly
* different handling.
*/
if (type.isThrowable()) {
return buildThrowableDeserializer(ctxt, type, beanDesc);
}
/* Or, for abstract types, may have alternate means for resolution
* (defaulting, materialization)
*/
if (type.isAbstract()) {
// [JACKSON-41] (v1.6): Let's make it possible to materialize abstract types.
JavaType concreteType = materializeAbstractType(ctxt, type, beanDesc);
if (concreteType != null) {
/* important: introspect actual implementation (abstract class or
* interface doesn't have constructors, for one)
*/
beanDesc = config.introspect(concreteType);
return buildBeanDeserializer(ctxt, concreteType, beanDesc);
}
}
// Otherwise, may want to check handlers for standard types, from superclass:
@SuppressWarnings("unchecked")
JsonDeserializer<Object> deser = (JsonDeserializer<Object>) findStdDeserializer(ctxt, type, beanDesc);
if (deser != null) {
return deser;
}
// Otherwise: could the class be a Bean class? If not, bail out
if (!isPotentialBeanType(type.getRawClass())) {
return null;
}
// For checks like [databind#1599]
checkIllegalTypes(ctxt, type, beanDesc);
// Use generic bean introspection to build deserializer
return buildBeanDeserializer(ctxt, type, beanDesc);
}
@Override
public JsonDeserializer<Object> createBuilderBasedDeserializer(
DeserializationContext ctxt, JavaType valueType, BeanDescription beanDesc,
Class<?> builderClass)
throws JsonMappingException
{
// First: need a BeanDescription for builder class
JavaType builderType = ctxt.constructType(builderClass);
BeanDescription builderDesc = ctxt.getConfig().introspectForBuilder(builderType);
return buildBuilderBasedDeserializer(ctxt, valueType, builderDesc);
}
/**
* Method called by {@link BeanDeserializerFactory} to see if there might be a standard
* deserializer registered for given type.
*/
protected JsonDeserializer<?> findStdDeserializer(DeserializationContext ctxt,
JavaType type, BeanDescription beanDesc)
throws JsonMappingException
{
// note: we do NOT check for custom deserializers here, caller has already
// done that
JsonDeserializer<?> deser = findDefaultDeserializer(ctxt, type, beanDesc);
// Also: better ensure these are post-processable?
if (deser != null) {
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyDeserializer(ctxt.getConfig(), beanDesc, deser);
}
}
}
return deser;
}
protected JavaType materializeAbstractType(DeserializationContext ctxt,
JavaType type, BeanDescription beanDesc)
throws JsonMappingException
{
final JavaType abstractType = beanDesc.getType();
// [JACKSON-502]: Now it is possible to have multiple resolvers too,
// as they are registered via module interface.
for (AbstractTypeResolver r : _factoryConfig.abstractTypeResolvers()) {
JavaType concrete = r.resolveAbstractType(ctxt.getConfig(), abstractType);
if (concrete != null) {
return concrete;
}
}
return null;
}
/*
/**********************************************************
/* Public construction method beyond DeserializerFactory API:
/* can be called from outside as well as overridden by
/* sub-classes
/**********************************************************
*/
/**
* Method that is to actually build a bean deserializer instance.
* All basic sanity checks have been done to know that what we have
* may be a valid bean type, and that there are no default simple
* deserializers.
*/
@SuppressWarnings("unchecked")
public JsonDeserializer<Object> buildBeanDeserializer(DeserializationContext ctxt,
JavaType type, BeanDescription beanDesc)
throws JsonMappingException
{
// First: check what creators we can use, if any
ValueInstantiator valueInstantiator;
/* 04-Jun-2015, tatu: To work around [databind#636], need to catch the
* issue, defer; this seems like a reasonable good place for now.
* Note, however, that for non-Bean types (Collections, Maps) this
* probably won't work and needs to be added elsewhere.
*/
try {
valueInstantiator = findValueInstantiator(ctxt, beanDesc);
} catch (NoClassDefFoundError error) {
return new NoClassDefFoundDeserializer<Object>(error);
}
BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);
builder.setValueInstantiator(valueInstantiator);
// And then setters for deserializing from JSON Object
addBeanProps(ctxt, beanDesc, builder);
addObjectIdReader(ctxt, beanDesc, builder);
// managed/back reference fields/setters need special handling... first part
addReferenceProperties(ctxt, beanDesc, builder);
addInjectables(ctxt, beanDesc, builder);
final DeserializationConfig config = ctxt.getConfig();
// [JACKSON-440]: update builder now that all information is in?
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
builder = mod.updateBuilder(config, beanDesc, builder);
}
}
JsonDeserializer<?> deserializer;
/* 19-Mar-2012, tatu: This check used to be done earlier; but we have to defer
* it a bit to collect information on ObjectIdReader, for example.
*/
if (type.isAbstract() && !valueInstantiator.canInstantiate()) {
deserializer = builder.buildAbstract();
} else {
deserializer = builder.build();
}
// [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);
}
}
return (JsonDeserializer<Object>) deserializer;
}
/**
* Method for constructing a bean deserializer that uses specified
* intermediate Builder for binding data, and construction of the
* value instance.
* Note that implementation is mostly copied from the regular
* BeanDeserializer build method.
*/
@SuppressWarnings("unchecked")
protected JsonDeserializer<Object> buildBuilderBasedDeserializer(
DeserializationContext ctxt, JavaType valueType, BeanDescription builderDesc)
throws JsonMappingException
{
// Creators, anyone? (to create builder itself)
ValueInstantiator valueInstantiator = findValueInstantiator(ctxt, builderDesc);
final DeserializationConfig config = ctxt.getConfig();
BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, builderDesc);
builder.setValueInstantiator(valueInstantiator);
// And then "with methods" for deserializing from JSON Object
addBeanProps(ctxt, builderDesc, builder);
addObjectIdReader(ctxt, builderDesc, builder);
// managed/back reference fields/setters need special handling... first part
addReferenceProperties(ctxt, builderDesc, builder);
addInjectables(ctxt, builderDesc, builder);
JsonPOJOBuilder.Value builderConfig = builderDesc.findPOJOBuilderConfig();
final String buildMethodName = (builderConfig == null) ?
"build" : builderConfig.buildMethodName;
// and lastly, find build method to use:
AnnotatedMethod buildMethod = builderDesc.findMethod(buildMethodName, null);
if (buildMethod != null) { // note: can't yet throw error; may be given build method
if (config.canOverrideAccessModifiers()) {
ClassUtil.checkAndFixAccess(buildMethod.getMember());
}
}
builder.setPOJOBuilder(buildMethod, builderConfig);
// this may give us more information...
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
builder = mod.updateBuilder(config, builderDesc, builder);
}
}
JsonDeserializer<?> deserializer = builder.buildBuilderBased(
valueType, buildMethodName);
// [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deserializer = mod.modifyDeserializer(config, builderDesc, deserializer);
}
}
return (JsonDeserializer<Object>) deserializer;
}
protected void addObjectIdReader(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
ObjectIdInfo objectIdInfo = beanDesc.getObjectIdInfo();
if (objectIdInfo == null) {
return;
}
Class<?> implClass = objectIdInfo.getGeneratorType();
JavaType idType;
SettableBeanProperty idProp;
ObjectIdGenerator<?> gen;
ObjectIdResolver resolver = ctxt.objectIdResolverInstance(beanDesc.getClassInfo(), objectIdInfo);
// Just one special case: Property-based generator is trickier
if (implClass == ObjectIdGenerators.PropertyGenerator.class) { // most special one, needs extra work
PropertyName propName = objectIdInfo.getPropertyName();
idProp = builder.findProperty(propName);
if (idProp == null) {
throw new IllegalArgumentException("Invalid Object Id definition for "
+beanDesc.getBeanClass().getName()+": can not find property with name '"+propName+"'");
}
idType = idProp.getType();
gen = new PropertyBasedObjectIdGenerator(objectIdInfo.getScope());
} else {
JavaType type = ctxt.constructType(implClass);
idType = ctxt.getTypeFactory().findTypeParameters(type, ObjectIdGenerator.class)[0];
idProp = null;
gen = ctxt.objectIdGeneratorInstance(beanDesc.getClassInfo(), objectIdInfo);
}
// also: unlike with value deserializers, let's just resolve one we need here
JsonDeserializer<?> deser = ctxt.findRootValueDeserializer(idType);
builder.setObjectIdReader(ObjectIdReader.construct(idType,
objectIdInfo.getPropertyName(), gen, deser, idProp, resolver));
}
@SuppressWarnings("unchecked")
public JsonDeserializer<Object> buildThrowableDeserializer(DeserializationContext ctxt,
JavaType type, BeanDescription beanDesc)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
// first: construct like a regular bean deserializer...
BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);
builder.setValueInstantiator(findValueInstantiator(ctxt, beanDesc));
addBeanProps(ctxt, beanDesc, builder);
// (and assume there won't be any back references)
// But then let's decorate things a bit
/* To resolve [JACKSON-95], need to add "initCause" as setter
* for exceptions (sub-classes of Throwable).
*/
AnnotatedMethod am = beanDesc.findMethod("initCause", INIT_CAUSE_PARAMS);
if (am != null) { // should never be null
SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(ctxt.getConfig(), am,
new PropertyName("cause"));
SettableBeanProperty prop = constructSettableProperty(ctxt, beanDesc, propDef,
am.getGenericParameterType(0));
if (prop != null) {
/* 21-Aug-2011, tatus: We may actually have found 'cause' property
* to set (with new 1.9 code)... but let's replace it just in case,
* otherwise can end up with odd errors.
*/
builder.addOrReplaceProperty(prop, true);
}
}
// And also need to ignore "localizedMessage"
builder.addIgnorable("localizedMessage");
// [JACKSON-794]: JDK 7 also added "getSuppressed", skip if we have such data:
builder.addIgnorable("suppressed");
/* As well as "message": it will be passed via constructor,
* as there's no 'setMessage()' method
*/
builder.addIgnorable("message");
// [JACKSON-440]: update builder now that all information is in?
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
builder = mod.updateBuilder(config, beanDesc, builder);
}
}
JsonDeserializer<?> deserializer = builder.build();
/* At this point it ought to be a BeanDeserializer; if not, must assume
* it's some other thing that can handle deserialization ok...
*/
if (deserializer instanceof BeanDeserializer) {
deserializer = new ThrowableDeserializer((BeanDeserializer) deserializer);
}
// [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);
}
}
return (JsonDeserializer<Object>) deserializer;
}
/*
/**********************************************************
/* Helper methods for Bean deserializer construction,
/* overridable by sub-classes
/**********************************************************
*/
/**
* Overridable method that constructs a {@link BeanDeserializerBuilder}
* which is used to accumulate information needed to create deserializer
* instance.
*/
protected BeanDeserializerBuilder constructBeanDeserializerBuilder(DeserializationContext ctxt,
BeanDescription beanDesc) {
return new BeanDeserializerBuilder(beanDesc, ctxt.getConfig());
}
/**
* Method called to figure out settable properties for the
* bean deserializer to use.
*<p>
* Note: designed to be overridable, and effort is made to keep interface
* similar between versions.
*/
protected void addBeanProps(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
final SettableBeanProperty[] creatorProps =
builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig());
final boolean isConcrete = !beanDesc.getType().isAbstract();
// Things specified as "ok to ignore"? [JACKSON-77]
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
boolean ignoreAny = false;
{
Boolean B = intr.findIgnoreUnknownProperties(beanDesc.getClassInfo());
if (B != null) {
ignoreAny = B.booleanValue();
builder.setIgnoreUnknownProperties(ignoreAny);
}
}
// Or explicit/implicit definitions?
Set<String> ignored = ArrayBuilders.arrayToSet(intr.findPropertiesToIgnore(beanDesc.getClassInfo(), false));
for (String propName : ignored) {
builder.addIgnorable(propName);
}
// Also, do we have a fallback "any" setter?
AnnotatedMethod anySetter = beanDesc.findAnySetter();
if (anySetter != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetter));
}
// NOTE: we do NOT add @JsonIgnore'd properties into blocked ones if there's any-setter
// Implicit ones via @JsonIgnore and equivalent?
if (anySetter == null) {
Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames();
if (ignored2 != null) {
for (String propName : ignored2) {
// allow ignoral of similarly named JSON property, but do not force;
// latter means NOT adding this to 'ignored':
builder.addIgnorable(propName);
}
}
}
final boolean useGettersAsSetters = (ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)
&& ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
// Ok: let's then filter out property definitions
List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt,
beanDesc, builder, beanDesc.findProperties(), ignored);
// After which we can let custom code change the set
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);
}
}
// At which point we still have all kinds of properties; not all with mutators:
for (BeanPropertyDefinition propDef : propDefs) {
SettableBeanProperty prop = null;
/* 18-Oct-2013, tatu: Although constructor parameters have highest precedence,
* we need to do linkage (as per [Issue#318]), and so need to start with
* other types, and only then create constructor parameter, if any.
*/
if (propDef.hasSetter()) {
Type propertyType = propDef.getSetter().getGenericParameterType(0);
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (propDef.hasField()) {
Type propertyType = propDef.getField().getGenericType();
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (useGettersAsSetters && propDef.hasGetter()) {
/* As per [JACKSON-88], may also need to consider getters
* for Map/Collection properties; but with lowest precedence
*/
AnnotatedMethod getter = propDef.getGetter();
// should only consider Collections and Maps, for now?
Class<?> rawPropertyType = getter.getRawType();
if (Collection.class.isAssignableFrom(rawPropertyType)
|| Map.class.isAssignableFrom(rawPropertyType)) {
prop = constructSetterlessProperty(ctxt, beanDesc, propDef);
}
}
// 25-Sep-2014, tatu: No point in finding constructor parameters for abstract types
// (since they are never used anyway)
if (isConcrete && propDef.hasConstructorParameter()) {
/* [JACKSON-700] If property is passed via constructor parameter, we must
* handle things in special way. Not sure what is the most optimal way...
* for now, let's just call a (new) method in builder, which does nothing.
*/
// but let's call a method just to allow custom builders to be aware...
final String name = propDef.getName();
CreatorProperty cprop = null;
if (creatorProps != null) {
for (SettableBeanProperty cp : creatorProps) {
if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {
cprop = (CreatorProperty) cp;
break;
}
}
}
if (cprop == null) {
throw ctxt.mappingException("Could not find creator property with name '%s' (in class %s)",
name, beanDesc.getBeanClass().getName());
}
if (prop != null) {
cprop.setFallbackSetter(prop);
}
prop = cprop;
builder.addCreatorProperty(cprop);
continue;
}
if (prop != null) {
Class<?>[] views = propDef.findViews();
if (views == null) {
// one more twist: if default inclusion disabled, need to force empty set of views
if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {
views = NO_VIEWS;
}
}
// one more thing before adding to builder: copy any metadata
prop.setViews(views);
builder.addProperty(prop);
}
}
}
/**
* Helper method called to filter out explicit ignored properties,
* as well as properties that have "ignorable types".
* Note that this will not remove properties that have no
* setters.
*/
protected List<BeanPropertyDefinition> filterBeanProps(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder,
List<BeanPropertyDefinition> propDefsIn,
Set<String> ignored)
throws JsonMappingException
{
ArrayList<BeanPropertyDefinition> result = new ArrayList<BeanPropertyDefinition>(
Math.max(4, propDefsIn.size()));
HashMap<Class<?>,Boolean> ignoredTypes = new HashMap<Class<?>,Boolean>();
// These are all valid setters, but we do need to introspect bit more
for (BeanPropertyDefinition property : propDefsIn) {
String name = property.getName();
if (ignored.contains(name)) { // explicit ignoral using @JsonIgnoreProperties needs to block entries
continue;
}
if (!property.hasConstructorParameter()) { // never skip constructor params
Class<?> rawPropertyType = null;
if (property.hasSetter()) {
rawPropertyType = property.getSetter().getRawParameterType(0);
} else if (property.hasField()) {
rawPropertyType = property.getField().getRawType();
}
// [JACKSON-429] Some types are declared as ignorable as well
if ((rawPropertyType != null)
&& (isIgnorableType(ctxt.getConfig(), beanDesc, rawPropertyType, ignoredTypes))) {
// important: make ignorable, to avoid errors if value is actually seen
builder.addIgnorable(name);
continue;
}
}
result.add(property);
}
return result;
}
/**
* Method that will find if bean has any managed- or back-reference properties,
* and if so add them to bean, to be linked during resolution phase.
*/
protected void addReferenceProperties(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
// and then back references, not necessarily found as regular properties
Map<String,AnnotatedMember> refs = beanDesc.findBackReferenceProperties();
if (refs != null) {
for (Map.Entry<String, AnnotatedMember> en : refs.entrySet()) {
String name = en.getKey();
AnnotatedMember m = en.getValue();
Type genericType;
if (m instanceof AnnotatedMethod) {
genericType = ((AnnotatedMethod) m).getGenericParameterType(0);
} else {
genericType = m.getRawType();
}
SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(
ctxt.getConfig(), m);
builder.addBackReferenceProperty(name, constructSettableProperty(
ctxt, beanDesc, propDef, genericType));
}
}
}
/**
* Method called locate all members used for value injection (if any),
* constructor {@link com.fasterxml.jackson.databind.deser.impl.ValueInjector} instances, and add them to builder.
*/
protected void addInjectables(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
Map<Object, AnnotatedMember> raw = beanDesc.findInjectables();
if (raw != null) {
boolean fixAccess = ctxt.canOverrideAccessModifiers();
for (Map.Entry<Object, AnnotatedMember> entry : raw.entrySet()) {
AnnotatedMember m = entry.getValue();
if (fixAccess) {
m.fixAccess(); // to ensure we can call it
}
builder.addInjectable(PropertyName.construct(m.getName()),
beanDesc.resolveType(m.getGenericType()),
beanDesc.getClassAnnotations(), m, entry.getKey());
}
}
}
/**
* Method called to construct fallback {@link SettableAnyProperty}
* for handling unknown bean properties, given a method that
* has been designated as such setter.
*/
protected SettableAnyProperty constructAnySetter(DeserializationContext ctxt,
BeanDescription beanDesc, AnnotatedMethod setter)
throws JsonMappingException
{
if (ctxt.canOverrideAccessModifiers()) {
setter.fixAccess(); // to ensure we can call it
}
// we know it's a 2-arg method, second arg is the value
JavaType type = beanDesc.bindingsForBeanType().resolveType(setter.getGenericParameterType(1));
BeanProperty.Std property = new BeanProperty.Std(PropertyName.construct(setter.getName()),
type, null, beanDesc.getClassAnnotations(), setter,
PropertyMetadata.STD_OPTIONAL);
type = resolveType(ctxt, beanDesc, type, setter);
/* AnySetter can be annotated with @JsonClass (etc) just like a
* regular setter... so let's see if those are used.
* Returns null if no annotations, in which case binding will
* be done at a later point.
*/
JsonDeserializer<Object> deser = findDeserializerFromAnnotation(ctxt, setter);
/* Otherwise, method may specify more specific (sub-)class for
* value (no need to check if explicit deser was specified):
*/
type = modifyTypeByAnnotation(ctxt, setter, type);
if (deser == null) {
deser = type.getValueHandler();
}
TypeDeserializer typeDeser = type.getTypeHandler();
return new SettableAnyProperty(property, setter, type,
deser, typeDeser);
}
/**
* Method that will construct a regular bean property setter using
* the given setter method.
*
* @return Property constructed, if any; or null to indicate that
* there should be no property based on given definitions.
*/
protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,
BeanDescription beanDesc, BeanPropertyDefinition propDef,
Type jdkType)
throws JsonMappingException
{
// need to ensure method is callable (for non-public)
AnnotatedMember mutator = propDef.getNonConstructorMutator();
if (ctxt.canOverrideAccessModifiers()) {
mutator.fixAccess();
}
// note: this works since we know there's exactly one argument for methods
JavaType t0 = beanDesc.resolveType(jdkType);
BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),
t0, propDef.getWrapperName(),
beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());
JavaType type = resolveType(ctxt, beanDesc, t0, mutator);
// did type change?
if (type != t0) {
property = property.withType(type);
}
/* First: does the Method specify the deserializer to use?
* If so, let's use it.
*/
JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, mutator);
type = modifyTypeByAnnotation(ctxt, mutator, type);
TypeDeserializer typeDeser = type.getTypeHandler();
SettableBeanProperty prop;
if (mutator instanceof AnnotatedMethod) {
prop = new MethodProperty(propDef, type, typeDeser,
beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);
} else {
prop = new FieldProperty(propDef, type, typeDeser,
beanDesc.getClassAnnotations(), (AnnotatedField) mutator);
}
if (propDeser != null) {
prop = prop.withValueDeserializer(propDeser);
}
// [JACKSON-235]: need to retain name of managed forward references:
AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();
if (ref != null && ref.isManagedReference()) {
prop.setManagedReferenceName(ref.getName());
}
ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();
if(objectIdInfo != null){
prop.setObjectIdInfo(objectIdInfo);
}
return prop;
}
/**
* Method that will construct a regular bean property setter using
* the given setter method.
*/
protected SettableBeanProperty constructSetterlessProperty(DeserializationContext ctxt,
BeanDescription beanDesc, BeanPropertyDefinition propDef)
throws JsonMappingException
{
final AnnotatedMethod getter = propDef.getGetter();
// need to ensure it is callable now:
if (ctxt.canOverrideAccessModifiers()) {
getter.fixAccess();
}
/* 26-Jan-2012, tatu: Alas, this complication is still needed to handle
* (or at least work around) local type declarations...
*/
JavaType type = getter.getType(beanDesc.bindingsForBeanType());
/* First: does the Method specify the deserializer to use?
* If so, let's use it.
*/
JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, getter);
type = modifyTypeByAnnotation(ctxt, getter, type);
// As per [Issue#501], need full resolution:
type = resolveType(ctxt, beanDesc, type, getter);
TypeDeserializer typeDeser = type.getTypeHandler();
SettableBeanProperty prop = new SetterlessProperty(propDef, type, typeDeser,
beanDesc.getClassAnnotations(), getter);
if (propDeser != null) {
prop = prop.withValueDeserializer(propDeser);
}
return prop;
}
/*
/**********************************************************
/* Helper methods for Bean deserializer, other
/**********************************************************
*/
/**
* Helper method used to skip processing for types that we know
* can not be (i.e. are never consider to be) beans:
* things like primitives, Arrays, Enums, and proxy types.
*<p>
* Note that usually we shouldn't really be getting these sort of
* types anyway; but better safe than sorry.
*/
protected boolean isPotentialBeanType(Class<?> type)
{
String typeStr = ClassUtil.canBeABeanType(type);
if (typeStr != null) {
throw new IllegalArgumentException("Can not deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean");
}
if (ClassUtil.isProxyType(type)) {
throw new IllegalArgumentException("Can not deserialize Proxy class "+type.getName()+" as a Bean");
}
/* also: can't deserialize some local classes: static are ok; in-method not;
* and with [JACKSON-594], other non-static inner classes are ok
*/
typeStr = ClassUtil.isLocalType(type, true);
if (typeStr != null) {
throw new IllegalArgumentException("Can not deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean");
}
return true;
}
/**
* Helper method that will check whether given raw type is marked as always ignorable
* (for purpose of ignoring properties with type)
*/
protected boolean isIgnorableType(DeserializationConfig config, BeanDescription beanDesc,
Class<?> type, Map<Class<?>,Boolean> ignoredTypes)
{
Boolean status = ignoredTypes.get(type);
if (status != null) {
return status.booleanValue();
}
BeanDescription desc = config.introspectClassAnnotations(type);
status = config.getAnnotationIntrospector().isIgnorableType(desc.getClassInfo());
// We default to 'false', i.e. not ignorable
return (status == null) ? false : status.booleanValue();
}
private void checkIllegalTypes(DeserializationContext ctxt, JavaType type,
BeanDescription beanDesc)
throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
String full = type.getRawClass().getName();
if (_cfgIllegalClassNames.contains(full)) {
String message = String.format("Illegal type (%s) to deserialize: prevented for security reasons",
full);
throw ctxt.mappingException("Invalid type definition for type %s: %s",
beanDesc, message);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/bad_280_1
|
crossvul-java_data_good_5761_7
|
/**
* License Agreement.
*
* JBoss RichFaces - Ajax4jsf Component Library
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.richfaces.renderkit.html;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.el.MethodBinding;
import org.ajax4jsf.resource.GifRenderer;
import org.ajax4jsf.resource.ImageRenderer;
import org.ajax4jsf.resource.InternetResourceBase;
import org.ajax4jsf.resource.JpegRenderer;
import org.ajax4jsf.resource.PngRenderer;
import org.ajax4jsf.resource.ResourceContext;
import org.ajax4jsf.resource.ResourceRenderer;
import org.ajax4jsf.resource.SerializableResource;
import org.ajax4jsf.util.HtmlColor;
import org.richfaces.component.UIPaint2D;
/**
* Resource for create image by managed bean method
* @author asmirnov@exadel.com (latest modification by $Author: aizobov $)
* @version $Revision: 1.4 $ $Date: 2007/02/28 10:35:23 $
*
*/
public class Paint2DResource extends InternetResourceBase {
private static final ImageRenderer[] _renderers= {new GifRenderer(), new JpegRenderer(), new PngRenderer()};
// private static final ThreadLocal<String> threadLocalContentType = new ThreadLocal<String>();
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#getRenderer()
*/
public ResourceRenderer getRenderer() {
return _renderers[0];
}
public ResourceRenderer getRenderer(ResourceContext context) {
ImageData data = null;
if (context != null) {
data = (ImageData) restoreData(context);
}
ImageRenderer renderer = _renderers[null==data?0:data._format];
return renderer;
}
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#isCacheable()
*/
public boolean isCacheable() {
return false;
}
public boolean isCacheable(ResourceContext resourceContext) {
ImageData data = (ImageData) restoreData(resourceContext);
return data.cacheable;
}
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext()
*/
public boolean requireFacesContext() {
// work in context
return true;
}
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#getDataToStore(javax.faces.context.FacesContext, java.lang.Object)
*/
protected Object getDataToStore(FacesContext context, Object data) {
if (data instanceof UIPaint2D) {
UIPaint2D paint2D = (UIPaint2D) data;
ImageData dataToStore = new ImageData();
dataToStore._width = paint2D.getWidth();
dataToStore._height = paint2D.getHeight();
dataToStore._data = paint2D.getData();
dataToStore._paint = UIComponentBase.saveAttachedState(context, paint2D.getPaint());
String format = paint2D.getFormat();
if("jpeg".equalsIgnoreCase(format)) {
dataToStore._format = 1;
} else if("png".equalsIgnoreCase(format)) {
dataToStore._format = 2;
}
String bgColor = paint2D.getBgcolor();
try {
dataToStore._bgColor = HtmlColor.decode(bgColor).getRGB();
} catch (Exception e) {}
dataToStore.cacheable = paint2D.isCacheable();
return dataToStore;
} else {
throw new FacesException("Data for painting image resource not instance of UIPaint2D");
}
}
private static final class ImageData implements SerializableResource {
private static final long serialVersionUID = 4452040100045367728L;
int _width=1;
int _height = 1;
Object _data;
int _format = 0;
Object _paint;
boolean cacheable = false;
/*
* init color with transparent by default
*/
int _bgColor = 0;
}
/**
* Primary calculation of image dimensions - used when HTML code is generated
* to render IMG's width and height
* Subclasses should override this method to provide correct sizes of rendered images
* @param facesContext
* @return dimensions of the image to be displayed on page
*/
public Dimension getDimensions(FacesContext facesContext, Object data){
if (data instanceof UIPaint2D) {
UIPaint2D paint2D = (UIPaint2D) data;
return new Dimension(paint2D.getWidth(),paint2D.getHeight());
}
return new Dimension(1,1);
}
/**
* Secondary calculation is used basically by getImage method
* @param resourceContext
* @return
*/
protected Dimension getDimensions(ResourceContext resourceContext){
ImageData data = (ImageData) restoreData(resourceContext);
return new Dimension(data._width,data._height);
}
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#send(javax.faces.context.FacesContext, java.lang.Object)
*/
public void send(ResourceContext context) throws IOException {
ImageData data = (ImageData) restoreData(context);
ImageRenderer renderer = (ImageRenderer) getRenderer(context);
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
BufferedImage image = renderer.createImage(data._width,data._height);
Graphics2D graphics = image.createGraphics();
try {
if (data._bgColor != 0) {
Color color = new Color(data._bgColor);
graphics.setBackground(color);
graphics.clearRect(0, 0, data._width, data._height);
}
MethodBinding paint = (MethodBinding) UIComponentBase.restoreAttachedState(facesContext, data._paint);
paint.invoke(facesContext, new Object[] {graphics,data._data});
} finally {
if (graphics != null) {
graphics.dispose();
}
}
renderer.sendImage(context, image);
} catch (Exception e) {
// log.error("Error send image from resource "+context.getPathInfo(),e);
throw new FacesException("Error send image ",e);
}
}
// public String getContentType(ResourceContext context) {
// Object contentType = threadLocalContentType.get();
// if (contentType != null) {
// return (String) contentType;
// } else {
// return super.getContentType(context);
// }
// }
/* (non-Javadoc)
* @see org.ajax4jsf.resource.InternetResourceBase#sendHeaders(org.ajax4jsf.resource.ResourceContext)
*/
// public void sendHeaders(ResourceContext context) {
// ImageData data = (ImageData) restoreData(context);
// ImageRenderer renderer = _renderers[data._format];
// threadLocalContentType.set(renderer.getContentType());
//
// super.sendHeaders(context);
//
// threadLocalContentType.set(null);
// }
}
|
./CrossVul/dataset_final_sorted/CWE-502/java/good_5761_7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.