proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQPrivateHandler.java
IQPrivateHandler
handleIQ
class IQPrivateHandler extends IQHandler implements ServerFeaturesProvider { private static final Logger Log = LoggerFactory.getLogger(IQPrivacyHandler.class); public static final String NAMESPACE = "jabber:iq:private"; private IQHandlerInfo info; private PrivateStorage privateStorage = null; public IQPrivateHandler() { super("XMPP Private Storage Handler"); info = new IQHandlerInfo("query", NAMESPACE); } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {<FILL_FUNCTION_BODY>} @Override public void initialize(XMPPServer server) { super.initialize(server); privateStorage = server.getPrivateStorage(); } @Override public IQHandlerInfo getInfo() { return info; } @Override public Iterator<String> getFeatures() { return Arrays.asList( "jabber:iq:private", "urn:xmpp:bookmarks-conversion:0" ).iterator(); } }
IQ replyPacket = IQ.createResultIQ(packet); Element child = packet.getChildElement(); Element dataElement = child.elementIterator().next(); if ( !UserManager.getInstance().isRegisteredUser( packet.getFrom(), false ) ) { Log.trace("Responding with 'service-unavailable': service unavailable to non-local, unregistered users: {}", packet); replyPacket.setChildElement(packet.getChildElement().createCopy()); replyPacket.setError(PacketError.Condition.service_unavailable); replyPacket.getError().setText( "Service available only to locally registered users." ); return replyPacket; } if (dataElement != null) { if (IQ.Type.get.equals(packet.getType())) { Element dataStored = privateStorage.get(packet.getFrom().getNode(), dataElement); dataStored.setParent(null); child.remove(dataElement); child.setParent(null); replyPacket.setChildElement(child); child.add(dataStored); } else { if (privateStorage.isEnabled()) { privateStorage.add(packet.getFrom().getNode(), dataElement); } else { Log.trace("Responding with 'service-unavailable': private storage is not enabled: {}", packet); replyPacket.setChildElement(packet.getChildElement().createCopy()); replyPacket.setError(PacketError.Condition.service_unavailable); } } } else { replyPacket.setChildElement("query", "jabber:iq:private"); } return replyPacket;
292
436
728
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQSessionEstablishmentHandler.java
IQSessionEstablishmentHandler
handleIQ
class IQSessionEstablishmentHandler extends IQHandler { private IQHandlerInfo info; public IQSessionEstablishmentHandler() { super("Session Establishment handler"); info = new IQHandlerInfo("session", "urn:ietf:params:xml:ns:xmpp-session"); } @Override public boolean performNoSuchUserCheck() { return false; } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException {<FILL_FUNCTION_BODY>} @Override public IQHandlerInfo getInfo() { return info; } }
// Just answer that the session has been activated IQ reply = IQ.createResultIQ(packet); return reply;
171
36
207
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQSharedGroupHandler.java
IQSharedGroupHandler
handleIQ
class IQSharedGroupHandler extends IQHandler { private IQHandlerInfo info; private String serverName; private RosterManager rosterManager; public IQSharedGroupHandler() { super("Shared Groups Handler"); info = new IQHandlerInfo("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup"); } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException {<FILL_FUNCTION_BODY>} @Override public IQHandlerInfo getInfo() { return info; } @Override public void initialize(XMPPServer server) { super.initialize(server); serverName = server.getServerInfo().getXMPPDomain(); rosterManager = server.getRosterManager(); } }
IQ result = IQ.createResultIQ(packet); String username = packet.getFrom().getNode(); if (!serverName.equals(packet.getFrom().getDomain()) || username == null) { // Users of remote servers are not allowed to get their "shared groups". Users of // remote servers cannot have shared groups in this server. // Besides, anonymous users do not belong to shared groups so answer an error result.setChildElement(packet.getChildElement().createCopy()); result.setError(PacketError.Condition.not_allowed); return result; } Collection<Group> groups = rosterManager.getSharedGroups(username); Element sharedGroups = result.setChildElement("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup"); for (Group sharedGroup : groups) { String displayName = sharedGroup.getSharedDisplayName(); if (displayName != null) { sharedGroups.addElement("group").setText(displayName); } } return result;
215
264
479
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQVersionHandler.java
IQVersionHandler
handleIQ
class IQVersionHandler extends IQHandler implements ServerFeaturesProvider { private static Element bodyElement; private IQHandlerInfo info; private static final Logger Log = LoggerFactory.getLogger(IQVersionHandler.class); public IQVersionHandler() { super("XMPP Server Version Handler"); info = new IQHandlerInfo("query", "jabber:iq:version"); if (bodyElement == null) { bodyElement = DocumentHelper.createElement(QName.get("query", "jabber:iq:version")); bodyElement.addElement("name").setText(AdminConsole.getAppName()); bodyElement.addElement("version").setText(AdminConsole.getVersionString()); } } @Override public IQ handleIQ(IQ packet) throws PacketException {<FILL_FUNCTION_BODY>} @Override public IQHandlerInfo getInfo() { return info; } @Override public Iterator<String> getFeatures() { return Collections.singleton("jabber:iq:version").iterator(); } }
if (IQ.Type.get == packet.getType()) { // Could cache this information for every server we see Element answerElement = bodyElement.createCopy(); try { // Try to retrieve this for every request - security settings // might be changed runtime! final String os = System.getProperty("os.name") + ' ' + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ')'; final String java = "Java " + System.getProperty("java.version"); answerElement.addElement("os").setText(os + " - " + java); } catch (SecurityException ex) { // Security settings don't allow the OS to be read. We'll honor // this and simply not report it. } IQ result = IQ.createResultIQ(packet); result.setChildElement(answerElement); return result; } else if (IQ.Type.set == packet.getType()) { // Answer an not-acceptable error since IQ should be of type GET IQ result = IQ.createResultIQ(packet); result.setError(PacketError.Condition.not_acceptable); return result; } else if (IQ.Type.result == packet.getType()) { /* handle results coming through BOSH Connections, * other results are processed in org.jivesoftware.openfire.net.SocketRead.java - getIQ() */ LocalSession localSession = (LocalSession) XMPPServer.getInstance().getSessionManager().getSession(packet.getFrom()); Element query = packet.getChildElement(); List<Element> elements = query.elements(); if (elements.size() > 0) { for (Element element : elements) { if (element.getName() != null && element.getStringValue() != null) { if (localSession!=null) { localSession.setSoftwareVersionData(element.getName(), element.getStringValue()); } else { /* The result comes from a server 2 server connection, so we write the information only to the debug log, because we dont need it at this point. */ Log.debug("XEP-0092 Packet from={} {}={}",packet.getFrom(),element.getName(),element.getStringValue()); } } } } return null; } // Ignore any other type of packet return null;
280
630
910
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQvCardHandler.java
IQvCardHandler
handleIQ
class IQvCardHandler extends IQHandler { private static final Logger Log = LoggerFactory.getLogger(IQvCardHandler.class); private IQHandlerInfo info; private XMPPServer server; private UserManager userManager; public IQvCardHandler() { super("XMPP vCard Handler"); info = new IQHandlerInfo("vCard", "vcard-temp"); } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {<FILL_FUNCTION_BODY>} @Override public void initialize(XMPPServer server) { super.initialize(server); this.server = server; userManager = server.getUserManager(); } @Override public IQHandlerInfo getInfo() { return info; } }
IQ result = IQ.createResultIQ(packet); IQ.Type type = packet.getType(); if (type.equals(IQ.Type.set)) { try { User user = userManager.getUser(packet.getFrom().getNode()); Element vcard = packet.getChildElement(); if (vcard != null) { try { VCardManager.getInstance().setVCard( user.getUsername(), vcard ); } catch ( UnsupportedOperationException e ) { Log.debug( "Entity '{}' tried to set VCard, but the configured VCard provider is read-only. An IQ error will be returned to sender.", packet.getFrom() ); // VCards can include binary data. Let's not echo that back in the error. // result.setChildElement( packet.getChildElement().createCopy() ); result.setError( PacketError.Condition.not_allowed ); Locale locale = JiveGlobals.getLocale(); // default to server locale. final Session session = SessionManager.getInstance().getSession( result.getTo() ); if ( session != null && session.getLanguage() != null ) { locale = session.getLanguage(); // use client locale if one is available. } result.getError().setText( LocaleUtils.getLocalizedString( "vcard.read_only", locale ), locale.getLanguage() ); } } } catch (UserNotFoundException e) { // VCards can include binary data. Let's not echo that back in the error. // result.setChildElement( packet.getChildElement().createCopy() ); result.setError(PacketError.Condition.item_not_found); } catch (Exception e) { Log.error(e.getMessage(), e); result.setError(PacketError.Condition.internal_server_error); } } else if (type.equals(IQ.Type.get)) { JID recipient = packet.getTo(); // If no TO was specified then get the vCard of the sender of the packet if (recipient == null) { recipient = packet.getFrom(); } // By default return an empty vCard result.setChildElement("vCard", "vcard-temp"); // Only try to get the vCard values of non-anonymous users if (recipient != null) { if (recipient.getNode() != null && server.isLocal(recipient)) { VCardManager vManager = VCardManager.getInstance(); Element userVCard = vManager.getVCard(recipient.getNode()); if (userVCard != null) { // Check if the requester wants to ignore some vCard's fields Element filter = packet.getChildElement() .element(QName.get("filter", "vcard-temp-filter")); if (filter != null) { // Create a copy so we don't modify the original vCard userVCard = userVCard.createCopy(); // Ignore fields requested by the user for (Iterator toFilter = filter.elementIterator(); toFilter.hasNext();) { Element field = (Element) toFilter.next(); Element fieldToRemove = userVCard.element(field.getName()); if (fieldToRemove != null) { fieldToRemove.detach(); } } } result.setChildElement(userVCard); } } else { result = IQ.createResultIQ(packet); result.setChildElement(packet.getChildElement().createCopy()); result.setError(PacketError.Condition.item_not_found); } } else { result = IQ.createResultIQ(packet); result.setChildElement(packet.getChildElement().createCopy()); result.setError(PacketError.Condition.item_not_found); } } else { result.setChildElement(packet.getChildElement().createCopy()); result.setError(PacketError.Condition.not_acceptable); } return result;
224
1,047
1,271
<methods>public void <init>(java.lang.String) ,public abstract org.jivesoftware.openfire.IQHandlerInfo getInfo() ,public abstract IQ handleIQ(IQ) throws org.jivesoftware.openfire.auth.UnauthorizedException,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public boolean performNoSuchUserCheck() ,public void process(Packet) throws org.jivesoftware.openfire.PacketException<variables>private static final Logger Log,protected org.jivesoftware.openfire.PacketDeliverer deliverer,protected org.jivesoftware.openfire.SessionManager sessionManager
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/http/HttpBindBody.java
HttpBindBody
getPacketReader
class HttpBindBody { private static final Logger Log = LoggerFactory.getLogger( HttpBindBody.class ); private static XmlPullParserFactory factory; static { try { factory = XmlPullParserFactory.newInstance( MXParser.class.getName(), null ); } catch ( XmlPullParserException e ) { Log.error( "Error creating a parser factory", e ); } } private final ThreadLocal<XMPPPacketReader> localReader = new ThreadLocal<>(); private final Document document; public static HttpBindBody from( String content ) throws DocumentException, XmlPullParserException, IOException { return new HttpBindBody( content ); } protected HttpBindBody( String content ) throws DocumentException, XmlPullParserException, IOException { // Parse document from the content. document = getPacketReader().read( new StringReader( content ), "UTF-8" ); final Element node = document.getRootElement(); if ( node == null || !"body".equals( node.getName() ) ) { throw new IllegalArgumentException( "Root element 'body' is missing from parsed request data" ); } } private XMPPPacketReader getPacketReader() {<FILL_FUNCTION_BODY>} public Long getRid() { final String value = document.getRootElement().attributeValue( "rid" ); if ( value == null ) { return null; } return getLongAttribute( value, -1 ); } public String getSid() { return document.getRootElement().attributeValue( "sid" ); } public boolean isEmpty() { return document.getRootElement().elements().isEmpty(); } public boolean isPoll() { boolean isPoll = isEmpty(); if ( "terminate".equals( document.getRootElement().attributeValue( "type" ) ) ) { isPoll = false; } else if ( "true".equals( document.getRootElement().attributeValue( new QName( "restart", document.getRootElement().getNamespaceForPrefix( "xmpp" ) ) ) ) ) { isPoll = false; } else if ( document.getRootElement().attributeValue( "pause" ) != null ) { isPoll = false; } return isPoll; } public String getLanguage() { // Default language is English ("en"). final String language = document.getRootElement().attributeValue( QName.get( "lang", XMLConstants.XML_NS_URI ) ); if ( language == null || "".equals( language ) ) { return "en"; } return language; } public Duration getWait() { return Duration.ofSeconds( getIntAttribute( document.getRootElement().attributeValue( "wait" ), 60 ) ); } public int getHold() { return getIntAttribute( document.getRootElement().attributeValue( "hold" ), 1 ); } public Duration getPause() { final int value = getIntAttribute( document.getRootElement().attributeValue( "pause" ), -1 ); if (value == -1) { return null; } return Duration.ofSeconds(value); } public String getVersion() { final String version = document.getRootElement().attributeValue( "ver" ); if ( version == null || "".equals( version ) ) { return "1.5"; } return version; } public int getMajorVersion() { return Integer.parseInt( getVersion().split( "\\." )[0] ); } public int getMinorVersion() { return Integer.parseInt( getVersion().split( "\\." )[1] ); } public String getType() { return document.getRootElement().attributeValue( "type" ); } public boolean isRestart() { final String restart = document.getRootElement().attributeValue( new QName( "restart", document.getRootElement().getNamespaceForPrefix( "xmpp" ) ) ); return "true".equals( restart ); } public List<Element> getStanzaElements() { return document.getRootElement().elements(); } public String asXML() { return document.getRootElement().asXML(); } @Override public String toString() { return asXML(); } public Document getDocument() { return document; } protected static long getLongAttribute(String value, long defaultValue) { if (value == null || "".equals(value)) { return defaultValue; } try { return Long.parseLong(value); } catch (Exception ex) { return defaultValue; } } protected static int getIntAttribute(String value, int defaultValue) { if (value == null || "".equals(value)) { return defaultValue; } try { return Integer.parseInt(value); } catch (Exception ex) { return defaultValue; } } }
// Reader is associated with a new XMPPPacketReader XMPPPacketReader reader = localReader.get(); if ( reader == null ) { reader = new XMPPPacketReader(); reader.setXPPFactory( factory ); localReader.set( reader ); } return reader;
1,373
84
1,457
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/http/HttpConnection.java
HttpConnection
deliverBody
class HttpConnection { private static final Logger Log = LoggerFactory.getLogger(HttpConnection.class); private final long requestId; private final boolean isRestart; private final Duration pause; private final boolean isTerminate; private final boolean isPoll; @Nullable private HttpSession session; @GuardedBy("this") private boolean isClosed; @Nonnull private final AsyncContext context; @Nonnull private final List<Element> inboundDataQueue; /** * Constructs an HTTP Connection. * * @param body the BOSH data that is in this request. * @param context execution context of the servlet request that created this instance. */ public HttpConnection(@Nonnull final HttpBindBody body, @Nonnull final AsyncContext context) { this.requestId = body.getRid(); this.inboundDataQueue = body.getStanzaElements(); this.isRestart = body.isRestart(); this.pause = body.getPause(); this.isTerminate = "terminate".equals(body.getType()); this.context = context; this.isPoll = body.isPoll(); } /** * The connection should be closed without delivering a stanza to the requestor. */ public void close() { synchronized (this) { if (isClosed) { return; } } try { deliverBody(null, true); } catch (HttpConnectionClosedException | IOException e) { Log.warn("Unexpected exception occurred while trying to close an HttpException.", e); } } /** * Returns true if this connection has been closed, either a response was delivered to the * client or the server closed the connection abruptly. * * @return true if this connection has been closed. */ public synchronized boolean isClosed() { return isClosed; } /** * @deprecated Renamed. See {@link #isEncrypted()} */ @Deprecated // Remove in Openfire 4.9 or later. public boolean isSecure() { return isEncrypted(); } /** * Returns true if this connection is using HTTPS. * * @return true if this connection is using HTTPS. */ public boolean isEncrypted() { return context.getRequest().isSecure(); } /** * Delivers content to the client. The content should be valid XMPP wrapped inside of a body. * A <i>null</i> value for body indicates that the connection should be closed and the client * sent an empty body. * * @param body the XMPP content to be forwarded to the client inside of a body tag. * @param async when false, this method blocks until the data has been delivered to the client. * * @throws HttpConnectionClosedException when this connection to the client has already received * a deliverable to forward to the client * @throws IOException if an input or output exception occurred */ public void deliverBody(@Nullable final String body, final boolean async) throws HttpConnectionClosedException, IOException {<FILL_FUNCTION_BODY>} /** * The list of stanzas that was sent by the client to the server over this connection. Possibly empty. * * @return An ordered collection of stanzas (possibly empty). */ @Nonnull public List<Element> getInboundDataQueue() { return inboundDataQueue; } /** * Returns the ID which uniquely identifies this connection. * * @return the ID which uniquely identifies this connection. */ public long getRequestId() { return requestId; } /** * Set the session that this connection belongs to. * * @param session the session that this connection belongs to. */ void setSession(@Nonnull HttpSession session) { this.session = session; } /** * Returns the session that this connection belongs to. * * Although technically, this method can return null, it is expected that a session is bound to this connection * almost immediately after it is created. * * @return the session that this connection belongs to. */ @Nullable public HttpSession getSession() { return session; } /** * Returns the Internet Protocol (IP) address of the client * or last proxy that sent the request. * * @return IP address of the remote peer * @throws UnknownHostException if no IP address for the peer could be found, */ @Nonnull public InetAddress getRemoteAddr() throws UnknownHostException { return InetAddress.getByName(context.getRequest().getRemoteAddr()); } /** * Returns if the request that was sent is a 'restart request'. * * @return if the request that was sent is a 'restart request'. */ public boolean isRestart() { return isRestart; } /** * Returns the number of seconds of pause that the client is requesting, or null if it's not requesting a pause. * * @return The amount of seconds of pause that is being requested, or null. */ public Duration getPause() { return pause; } /** * Returns if the request that was sent is a request to terminate the session. * * @return if the request that was sent is a request to terminate the session. */ public boolean isTerminate() { return isTerminate; } /** * Returns if the request that was sent is a request is polling for data, without providing any data itself. * * @return if the request that was sent is a request is polling for data, without providing any data itself. */ public boolean isPoll() { return isPoll; } /** * Returns the peer certificates for this connection. * * @return the peer certificates for this connection or null. */ public X509Certificate[] getPeerCertificates() { return (X509Certificate[]) context.getRequest().getAttribute("javax.servlet.request.X509Certificate"); } @Override public String toString() { return (session != null ? session.toString() : "[Anonymous]") + " rid: " + this.getRequestId(); } }
if (session == null) { // This indicates that there's an implementation error in Openfire. throw new IllegalStateException("Cannot be used before bound to a session."); } // We only want to use this function once so we will close it when the body is delivered. synchronized (this) { if (isClosed) { throw new HttpConnectionClosedException("The http connection is no longer " + "available to deliver content"); } isClosed = true; } HttpBindServlet.respond(getSession(), this.context, body != null ? body : session.createEmptyBody(false), async);
1,670
161
1,831
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/http/ResourceServlet.java
ResourceServlet
getJavaScriptContent
class ResourceServlet extends HttpServlet { private static final Logger Log = LoggerFactory.getLogger(ResourceServlet.class); // private static String suffix = ""; // Set to "_src" to use source version private static final Duration expiresOffset = Duration.ofDays(10); // This long until client cache expires private boolean debug = false; private boolean disableCompression = false; private static final Cache<String, byte[]> cache = CacheFactory.createCache("Javascript Cache"); @Override public void init(ServletConfig config) throws ServletException { super.init(config); debug = Boolean.parseBoolean(config.getInitParameter("debug")); disableCompression = Boolean.parseBoolean(config.getInitParameter("disableCompression")); } @Override public void service(HttpServletRequest request, HttpServletResponse response) { boolean compress = false; boolean javascript = request.getRequestURI().endsWith("scripts/"); if (!disableCompression) { if (request.getHeader("accept-encoding") != null && request.getHeader("accept-encoding").contains("gzip")) { compress = true; } else if (request.getHeader("---------------") != null) { // norton internet security compress = true; } } if(javascript) { response.setHeader("Content-type", "text/javascript"); } else { response.setHeader("Content-type", "text/css"); } response.setHeader("Vary", "Accept-Encoding"); // Handle proxies if (!debug) { DateFormat formatter = new SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'", Locale.US); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); response.setHeader("Expires", formatter.format(Instant.now().plus(expiresOffset))); response.setHeader("Cache-Control", "max-age=" + expiresOffset.toSeconds()); } else { response.setHeader("Expires", "1"); compress = false; } try { byte[] content; String cacheKey = compress + " " + javascript; content = cache.get(cacheKey); if (javascript && (debug || content == null)) { content = getJavaScriptContent(compress); cache.put(cacheKey, content); } // else if(!javascript && content == null) { // // } response.setContentLength(content == null ? 0 : content.length); if (compress) { response.setHeader("Content-Encoding", "gzip"); } // Write the content out if (content != null) { try (ByteArrayInputStream in = new ByteArrayInputStream(content)) { try (OutputStream out = response.getOutputStream()) { // Use a 128K buffer. byte[] buf = new byte[128 * 1024]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.flush(); } } } } catch (IOException e) { Log.error(e.getMessage(), e); } } private static byte[] getJavaScriptContent(boolean compress) throws IOException {<FILL_FUNCTION_BODY>} private static Collection<String> getJavascriptFiles() { return Arrays.asList("prototype.js", "getelementsbyselector.js", "sarissa.js", "connection.js", "yahoo-min.js", "dom-min.js", "event-min.js", "dragdrop-min.js", "yui-ext.js", "spank.js"); } private static String getJavaScriptFile(String path) { StringBuilder sb = new StringBuilder(); try (InputStream in = getResourceAsStream(path)) { if (in == null) { Log.error("Unable to find javascript file: '" + path + "' in classpath"); return ""; } try (BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.ISO_8859_1))) { String line; while ((line = br.readLine()) != null) { sb.append(line.trim()).append('\n'); } } } catch (Exception e) { Log.error("Error loading JavaScript file: '" + path + "'.", e); } return sb.toString(); } private static InputStream getResourceAsStream(String resourceName) { File file = new File(JiveGlobals.getHomePath() + File.separator + "resources" + File.separator + "spank" + File.separator + "scripts", resourceName); try { return new FileInputStream(file); } catch (FileNotFoundException e) { return null; } } }
StringWriter writer = new StringWriter(); for(String file : getJavascriptFiles()) { writer.write(getJavaScriptFile(file)); } if (compress) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) { gzos.write(writer.toString().getBytes()); gzos.finish(); gzos.flush(); return baos.toByteArray(); } } } else { return writer.toString().getBytes(); }
1,285
159
1,444
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/http/SessionEventDispatcher.java
SessionEventDispatcher
addListener
class SessionEventDispatcher { private static final Logger Log = LoggerFactory.getLogger( SessionEventDispatcher.class ); private static final Set<SessionListener> listeners = new CopyOnWriteArraySet<>(); private SessionEventDispatcher() { // Not instantiable. } /** * Adds a {@link org.jivesoftware.openfire.http.SessionListener} to this session. The listener * will be notified of changes to the session. * * @param listener the listener which is being added to the session. */ public static void addListener( SessionListener listener ) {<FILL_FUNCTION_BODY>} /** * Removes a {@link org.jivesoftware.openfire.http.SessionListener} from this session. The * listener will no longer be updated when an event occurs on the session. * * @param listener the session listener that is to be removed. */ public static void removeListener( SessionListener listener ) { listeners.remove( listener ); } /** * Dispatches an event related to a particular BOSH session to all registered listeners. * * @param session The session that relates to the event (can be null when the event type is 'pre_session_created'). * @param eventType The type of the event (cannot be null). * @param connection The connection where the event originated. * @param context The servlet context of the event */ public static void dispatchEvent( HttpSession session, EventType eventType, HttpConnection connection, AsyncContext context ) { for ( final SessionListener listener : listeners ) { try { switch ( eventType ) { case connection_opened: listener.connectionOpened( context, session, connection ); break; case connection_closed: listener.connectionClosed( context, session, connection ); break; case pre_session_created: listener.preSessionCreated( context ); break; case post_session_created: listener.postSessionCreated( context, session ); break; case session_closed: listener.sessionClosed( session ); break; default: throw new IllegalStateException( "An unexpected and unsupported event type was used: " + eventType ); } } catch ( Exception e ) { Log.warn( "An exception occurred while dispatching an event of type {}", eventType, e ); } } } public enum EventType { connection_opened, connection_closed, pre_session_created, post_session_created, session_closed } }
if ( listener == null ) { throw new NullPointerException(); } listeners.add( listener );
679
33
712
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/http/TempFileToucherTask.java
TempFileToucherTask
run
class TempFileToucherTask extends TimerTask { private final static Logger Log = LoggerFactory.getLogger( TempFileToucherTask.class ); private final Server server; public TempFileToucherTask( final Server server ) { this.server = server; } @Override public void run() {<FILL_FUNCTION_BODY>} }
final FileTime now = FileTime.fromMillis( System.currentTimeMillis() ); for ( final Handler handler : this.server.getChildHandlersByClass( WebAppContext.class ) ) { final File tempDirectory = ((WebAppContext) handler).getTempDirectory(); try { Log.debug( "Updating the last modified timestamp of content in Jetty's temporary storage in: {}", tempDirectory); Files.walk( tempDirectory.toPath() ) .forEach( f -> { try { Log.trace( "Setting the last modified timestamp of file '{}' in Jetty's temporary storage to: {}", f, now); Files.setLastModifiedTime( f, now ); } catch ( IOException e ) { Log.warn( "An exception occurred while trying to update the last modified timestamp of content in Jetty's temporary storage in: {}", f, e ); } } ); } catch ( IOException e ) { Log.warn( "An exception occurred while trying to update the last modified timestamp of content in Jetty's temporary storage in: {}", tempDirectory, e ); } }
107
297
404
<methods>public boolean cancel() ,public abstract void run() ,public long scheduledExecutionTime() <variables>static final int CANCELLED,static final int EXECUTED,static final int SCHEDULED,static final int VIRGIN,final java.lang.Object lock,long nextExecutionTime,long period,int state
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/keystore/CertificateStore.java
CertificateStore
delete
class CertificateStore { private static final Logger Log = LoggerFactory.getLogger( CertificateStore.class ); protected static final Provider PROVIDER = new BouncyCastleProvider(); static { // Add the BC provider to the list of security providers Security.addProvider( PROVIDER ); } protected final KeyStore store; protected final CertificateStoreConfiguration configuration; public CertificateStore( CertificateStoreConfiguration configuration, boolean createIfAbsent ) throws CertificateStoreConfigException { if (configuration == null) { throw new IllegalArgumentException( "Argument 'configuration' cannot be null." ); } this.configuration = configuration; try { final File file = configuration.getFile(); if ( createIfAbsent && !file.exists() ) { try ( final FileOutputStream os = new FileOutputStream( file.getPath() ) ) { store = KeyStore.getInstance( configuration.getType() ); store.load( null, configuration.getPassword() ); store.store( os, configuration.getPassword() ); } } else { try ( final FileInputStream is = new FileInputStream( file ) ) { store = KeyStore.getInstance( configuration.getType() ); store.load( is, configuration.getPassword() ); } } } catch ( IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException ex ) { throw new CertificateStoreConfigException( "Unable to load store of type '" + configuration.getType() + "' from file '" + configuration.getFile() + "'", ex ); } } /** * Reloads the content of the store from disk. Useful when the store content has been modified outside of the * Openfire process, or when changes that have not been persisted need to be undone. * @throws CertificateStoreConfigException if the store could not be reloaded */ public void reload() throws CertificateStoreConfigException { try ( final FileInputStream is = new FileInputStream( configuration.getFile() ) ) { store.load( is, configuration.getPassword() ); CertificateManager.fireCertificateStoreChanged( this ); } catch ( IOException | NoSuchAlgorithmException | CertificateException ex ) { throw new CertificateStoreConfigException( "Unable to reload store in '" + configuration.getFile() + "'", ex ); } } /** * Saves the current state of the store to disk. Useful when certificates have been added or removed from the * store. * @throws CertificateStoreConfigException of the configuration could not be persisted */ public void persist() throws CertificateStoreConfigException { try ( final FileOutputStream os = new FileOutputStream( configuration.getFile() ) ) { store.store( os, configuration.getPassword() ); } catch ( NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException ex ) { throw new CertificateStoreConfigException( "Unable to save changes to store in '" + configuration.getFile() + "'", ex ); } } /** * Copies the file that is the persistent storage for this store to a new file in the backup location. * * @return The path in which the backup was created, or null if the creation of the backup failed. */ public Path backup() { final String postfix = "." + new Date().getTime(); final Path original = configuration.getFile().toPath(); final Path backup = configuration.getBackupDirectory().toPath().resolve( original.getFileName() + postfix ); Log.info( "Creating a backup of {} in {}.", original, backup ); try { Files.copy( original, backup ); return backup; } catch ( IOException e ) { Log.error( "An error occurred creating a backup of {} in {}!", original, backup, e ); } return null; } /** * Returns a collection of all x.509 certificates in this store. Certificates returned by this method can be of any * state (eg: invalid, on a revocation list, etc). * * @return A collection (possibly empty, never null) of all certificates in this store, mapped by their alias. * @throws KeyStoreException if a keystore has not been initialized */ public Map<String, X509Certificate> getAllCertificates() throws KeyStoreException { final Map<String, X509Certificate> results = new HashMap<>(); for ( final String alias : Collections.list( store.aliases() ) ) { final Certificate certificate = store.getCertificate( alias ); if ( !( certificate instanceof X509Certificate ) ) { continue; } results.put( alias, (X509Certificate) certificate ); } return results; } /** * Deletes an entry (by entry) in this store. All information related to this entry will be removed, including * certificates and keys. * * When the store does not contain an entry that matches the provided alias, this method does nothing. * * @param alias The alias for which to delete an entry (cannot be null or empty). * @throws CertificateStoreConfigException if the entry could not be deleted */ public void delete( String alias ) throws CertificateStoreConfigException {<FILL_FUNCTION_BODY>} public KeyStore getStore() { return store; } public CertificateStoreConfiguration getConfiguration() { return configuration; } }
// Input validation if ( alias == null || alias.trim().isEmpty() ) { throw new IllegalArgumentException( "Argument 'alias' cannot be null or an empty String." ); } try { if ( !store.containsAlias( alias ) ) { Log.info( "Unable to delete certificate for alias '" + alias + "' from store, as the store does not contain a certificate for that alias." ); return; } store.deleteEntry( alias ); persist(); } catch ( CertificateStoreConfigException | KeyStoreException e ) { reload(); // reset state of the store. throw new CertificateStoreConfigException( "Unable to delete the certificate from the identity store.", e ); }
1,423
191
1,614
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/keystore/CertificateStoreConfiguration.java
CertificateStoreConfiguration
equals
class CertificateStoreConfiguration { protected final String type; protected final File file; protected final char[] password; protected final File backupDirectory; /** * Creates a new instance. * * @param type The store type (jks, jceks, pkcs12, etc). Cannot be null or an empty string. * @param file The file-system based representation of the store (cannot be null). * @param password the password used to check the integrity of the store, the password used to unlock the store, or null. * @param backupDirectory the directory in which the backup of the original keystore should be saved */ public CertificateStoreConfiguration( String type, File file, char[] password, File backupDirectory ) { if ( type == null || type.isEmpty() ) { throw new IllegalArgumentException( "Argument 'type' cannot be null or an empty string." ); } if ( file == null ) { throw new IllegalArgumentException( "Argument 'file' cannot be null." ); } if ( backupDirectory == null ) { throw new IllegalArgumentException( "Argument 'backupDirectory' cannot be null." ); } this.type = type; this.file = file; this.password = password; this.backupDirectory = backupDirectory; } public String getType() { return type; } public File getFile() { return file; } public char[] getPassword() { return password; } public File getBackupDirectory() { return backupDirectory; } @Override public boolean equals( final Object o ) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = Objects.hash( type, file, backupDirectory ); result = 31 * result + Arrays.hashCode( password ); return result; } @Override @SuppressWarnings("lgtm[java/equals-on-arrays]") // For this particular instance, what LGTM warns against is exactly what the intended behavior is: ignore content of the array. public String toString() { return "CertificateStoreConfiguration{" + "type='" + type + '\'' + ", file=" + file + ", password hashcode=" + password.hashCode() + // java.lang.Array.hashCode inherits from Object. As it is a reference, it should be safe to log and useful enough to compare against other passwords. ", backupDirectory=" + backupDirectory + '}'; } }
if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } final CertificateStoreConfiguration that = (CertificateStoreConfiguration) o; return Objects.equals( type, that.type ) && Objects.equals( file, that.file ) && Arrays.equals( password, that.password ) && Objects.equals( backupDirectory, that.backupDirectory );
662
115
777
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/keystore/CertificateStoreWatcher.java
CertificateStoreWatcher
run
class CertificateStoreWatcher { public static final SystemProperty<Boolean> ENABLED = SystemProperty.Builder.ofType( Boolean.class ) .setKey( "cert.storewatcher.enabled" ) .setDefaultValue( true ) .setDynamic( false ) .build(); private static final Logger Log = LoggerFactory.getLogger( CertificateStoreWatcher.class ); private final Map<CertificateStore, Path> watchedStores = new HashMap<>(); private final Map<Path, WatchKey> watchedPaths = new HashMap<>(); private WatchService storeWatcher; private final ExecutorService executorService = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("CertstoreWatcher-", Executors.defaultThreadFactory(), false, Thread.NORM_PRIORITY) ); public CertificateStoreWatcher() { try { if ( !ENABLED.getValue() ) { Log.info( "Certificate update detection disabled by configuration." ); storeWatcher = null; return; } storeWatcher = FileSystems.getDefault().newWatchService(); executorService.submit( new Runnable() { @Override public void run() {<FILL_FUNCTION_BODY>} }); } catch ( UnsupportedOperationException e ) { storeWatcher = null; Log.info( "This file system does not support watching file system objects for changes and events. Changes to Openfire certificate stores made outside of Openfire might not be detected. A restart of Openfire might be required for these to be applied." ); } catch ( IOException e ) { storeWatcher = null; Log.warn( "An exception occured while trying to create a service that monitors the Openfire certificate stores for changes. Changes to Openfire certificate stores made outside of Openfire might not be detected. A restart of Openfire might be required for these to be applied.", e ); } } /** * Shuts down this watcher, releasing all resources. */ public void destroy() { if ( executorService != null ) { executorService.shutdown(); } synchronized ( watchedStores ) { if ( storeWatcher != null ) { try { storeWatcher.close(); } catch ( IOException e ) { Log.warn( "Unable to close the watcherservice that is watching for file system changes to certificate stores.", e ); } } } } /** * Start watching the file that backs a Certificate Store for changes, reloading the Certificate Store when * appropriate. * * This method does nothing when the file watching functionality is not supported by the file system. * * @param store The certificate store (cannot be null). */ public void watch( CertificateStore store ) { if ( store == null ) { throw new IllegalArgumentException( "Argument 'store' cannot be null." ); } if ( storeWatcher == null ) { return; } final Path dir = store.getConfiguration().getFile().toPath().normalize().getParent(); synchronized ( watchedStores ) { watchedStores.put( store, dir ); // Watch the directory that contains the keystore, if we're not already watching it. if ( !watchedPaths.containsKey( dir ) ) { try { // Ignoring deletion events, as those changes should be applied via property value changes. final WatchKey watchKey = dir.register( storeWatcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE ); watchedPaths.put( dir, watchKey ); } catch ( Throwable t ) { Log.warn( "Unable to add a watcher for a path that contains files that provides the backend storage for certificate stores. Changes to those files are unlikely to be picked up automatically. Path: {}", dir, t ); watchedStores.remove( store ); } } } } /** * Stop watching the file that backs a Certificate Store for changes * * @param store The certificate store (cannot be null). */ public synchronized void unwatch( CertificateStore store ) { if ( store == null ) { throw new IllegalArgumentException( "Argument 'store' cannot be null." ); } synchronized ( watchedStores ) { watchedStores.remove( store ); final Path dir = store.getConfiguration().getFile().toPath().normalize().getParent(); // Check if there are any other stores being watched in the same directory. if ( watchedStores.containsValue( dir ) ) { return; } final WatchKey key = watchedPaths.remove( dir ); if ( key != null ) { key.cancel(); } } } }
while ( !executorService.isShutdown() ) { final WatchKey key; try { key = storeWatcher.poll( 5, TimeUnit.SECONDS ); } catch ( InterruptedException e ) { // Interrupted. Stop waiting continue; } if ( key == null ) { continue; } for ( final WatchEvent<?> event : key.pollEvents() ) { final WatchEvent.Kind<?> kind = event.kind(); // An OVERFLOW event can occur regardless of what kind of events the watcher was configured for. if ( kind == StandardWatchEventKinds.OVERFLOW ) { continue; } synchronized ( watchedStores ) { // The filename is the context of the event. final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path changedFile = ((Path) key.watchable()).resolve( ev.context() ); // Can't use the value from the 'watchedStores' map, as that's the parent dir, not the keystore file! for ( final CertificateStore store : watchedStores.keySet() ) { final Path storeFile = store.getConfiguration().getFile().toPath().normalize(); if ( storeFile.equals( changedFile ) ) { // Check if the modified file is usable. try ( final FileInputStream is = new FileInputStream( changedFile.toFile() ) ) { final KeyStore tmpStore = KeyStore.getInstance( store.getConfiguration().getType() ); tmpStore.load( is, store.getConfiguration().getPassword() ); } catch ( EOFException e ) { Log.debug( "The keystore is still being modified. Ignore for now. A new event should be thrown later.", e ); break; } catch ( Exception e ) { Log.debug( "Can't read the modified keystore with this config. Continue iterating over configs.", e ); continue; } Log.info( "A file system change was detected. A(nother) certificate store that is backed by file '{}' will be reloaded.", storeFile ); try { store.reload(); } catch ( CertificateStoreConfigException e ) { Log.warn( "An unexpected exception occurred while trying to reload a certificate store that is backed by file '{}'!", storeFile, e ); } } } } } // Reset the key to receive further events. key.reset(); }
1,290
671
1,961
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/ldap/LdapAuthProvider.java
LdapAuthProvider
authenticate
class LdapAuthProvider implements AuthProvider { private static final Logger Log = LoggerFactory.getLogger(LdapAuthProvider.class); private LdapManager manager; private Cache<String, String> authCache = null; public LdapAuthProvider() { // Convert XML based provider setup to Database based JiveGlobals.migrateProperty("ldap.authCache.enabled"); manager = LdapManager.getInstance(); if (JiveGlobals.getBooleanProperty("ldap.authCache.enabled", false)) { String cacheName = "LDAP Authentication"; authCache = CacheFactory.createCache(cacheName); } } @Override public void authenticate(String username, String password) throws UnauthorizedException {<FILL_FUNCTION_BODY>} @Override public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void setPassword(String username, String password) throws UserNotFoundException { throw new UnsupportedOperationException(); } @Override public boolean supportsPasswordRetrieval() { return false; } @Override public boolean isScramSupported() { return false; } @Override public String getSalt(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public int getIterations(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public String getServerKey(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } @Override public String getStoredKey(String username) throws UnsupportedOperationException, UserNotFoundException { throw new UnsupportedOperationException(); } }
if (username == null || password == null || "".equals(password.trim())) { throw new UnauthorizedException(); } if (username.contains("@")) { // Check that the specified domain matches the server's domain int index = username.indexOf("@"); String domain = username.substring(index + 1); if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) { username = username.substring(0, index); } else { // Unknown domain. Return authentication failed. throw new UnauthorizedException(); } } // Un-escape username. username = JID.unescapeNode(username); // If cache is enabled, see if the auth is in cache. if (authCache != null && authCache.containsKey(username)) { String hash = authCache.get(username); if (StringUtils.hash(password).equals(hash)) { return; } } Rdn[] userRDN; try { // The username by itself won't help us much with LDAP since we // need a fully qualified dn. We could make the assumption that // the baseDN would always be the location of user profiles. For // example if the baseDN was set to "ou=People, o=jivesoftare, o=com" // then we would be able to directly load users from that node // of the LDAP tree. However, it's a poor assumption that only a // flat structure will be used. Therefore, we search all sub-trees // of the baseDN for the username (assuming the user has not disabled // sub-tree searching). So, if the baseDN is set to // "o=jivesoftware, o=com" then a search will include the "People" // node as well all the others under the base. userRDN = manager.findUserRDN(username); // See if the user authenticates. if (!manager.checkAuthentication(userRDN, password)) { throw new UnauthorizedException("Username and password don't match"); } } catch (CommunicationException e) { // Log error here since it will be wrapped with an UnauthorizedException that // is never logged Log.error("Error connecting to LDAP server", e); throw new UnauthorizedException(e); } catch (Exception e) { throw new UnauthorizedException(e); } // If cache is enabled, add the item to cache. if (authCache != null) { authCache.put(username, StringUtils.hash(password)); }
487
675
1,162
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/ldap/LdapAuthorizationMapping.java
LdapAuthorizationMapping
map
class LdapAuthorizationMapping implements AuthorizationMapping { private static final Logger Log = LoggerFactory.getLogger(LdapAuthorizationMapping.class); private LdapManager manager; private String princField; private String princSearchFilter; public LdapAuthorizationMapping() { // Convert XML based provider setup to Database based JiveGlobals.migrateProperty("ldap.princField"); JiveGlobals.migrateProperty("ldap.princSearchFilter"); manager = LdapManager.getInstance(); princField = JiveGlobals.getProperty("ldap.princField", "k5login"); princSearchFilter = JiveGlobals.getProperty("ldap.princSearchFilter"); StringBuilder filter = new StringBuilder(); if(princSearchFilter == null) { filter.append('(').append(princField).append("={0})"); } else { filter.append("(&(").append(princField).append("={0})("); filter.append(princSearchFilter).append("))"); } princSearchFilter = filter.toString(); } @Override public String map(String authcid) {<FILL_FUNCTION_BODY>} /** * Returns the short name of the Policy * * @return The short name of the Policy */ @Override public String name() { return "LDAP Authorization Mapping"; } /** * Returns a description of the Policy * * @return The description of the Policy. */ @Override public String description() { return "Provider for authorization using LDAP. Returns the authentication identity's (principal, whose password " + "is used) default authorization identity (username to act as) using the attribute specified in ldap.princField."; } }
String authzid = authcid; DirContext ctx = null; try { Log.debug("LdapAuthorizationMapping: Starting LDAP search..."); String usernameField = manager.getUsernameField(); //String baseDN = manager.getBaseDN(); boolean subTreeSearch = manager.isSubTreeSearch(); ctx = manager.getContext(); SearchControls constraints = new SearchControls(); if (subTreeSearch) { constraints.setSearchScope (SearchControls.SUBTREE_SCOPE); } // Otherwise, only search a single level. else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } constraints.setReturningAttributes(new String[] { usernameField }); NamingEnumeration answer = ctx.search("", princSearchFilter, new String[] {LdapManager.sanitizeSearchFilter(authcid)}, constraints); Log.debug("LdapAuthorizationMapping: ... search finished"); if (answer == null || !answer.hasMoreElements()) { Log.debug("LdapAuthorizationMapping: Username based on principal '" + authcid + "' not found."); return authcid; } Attributes atrs = ((SearchResult)answer.next()).getAttributes(); Attribute usernameAttribute = atrs.get(usernameField); authzid = (String) usernameAttribute.get(); } catch (Exception e) { // Ignore. } finally { try { if (ctx != null) { ctx.close(); } } catch (Exception ex) { Log.debug("An exception occurred while trying to close a LDAP context after trying to map authorization for principal {}.", authcid, ex); } } return authzid;
483
462
945
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/ldap/LdapAuthorizationPolicy.java
LdapAuthorizationPolicy
getAuthorized
class LdapAuthorizationPolicy implements AuthorizationPolicy { private static final Logger Log = LoggerFactory.getLogger(LdapAuthorizationPolicy.class) ; private LdapManager manager; private String usernameField; private String authorizeField; public LdapAuthorizationPolicy() { // Convert XML based provider setup to Database based JiveGlobals.migrateProperty("ldap.authorizeField"); manager = LdapManager.getInstance(); usernameField = manager.getUsernameField(); authorizeField = JiveGlobals.getProperty("ldap.authorizeField", "k5login"); } /** * Returns true if the provided XMPP authentication identity (identity whose password will be used) is explicitly * allowed to the provided XMPP authorization identity (identity to act as). * * @param authzid XMPP authorization identity (identity to act as). * @param authcid XMPP authentication identity, or 'principal' (identity whose password will be used) * @return true if the authzid is explicitly allowed to be used by the user authenticated with the authcid. */ @Override public boolean authorize(String authzid, String authcid) { return getAuthorized(authzid).contains(authcid); } /** * Returns a collection of XMPP authentication identities (or 'principals') that are authorized to use the XMPP * authorization identity (identity to act as) as provided in the argument of this method. * * @param authzid XMPP authorization identity (identity to act as). * @return A collection of XMPP authentication identities (or 'principals') that are authorized to use the authzid */ private Collection<String> getAuthorized(String authzid) {<FILL_FUNCTION_BODY>} /** * Returns the short name of the Policy * * @return The short name of the Policy */ @Override public String name() { return "LDAP Authorization Policy"; } /** * Returns a description of the Policy * * @return The description of the Policy. */ @Override public String description() { return "Provider for authorization using LDAP. Checks if the authentication identity, or 'principal' (identity" + " whose password will be used) is in the user's LDAP object using the authorizeField property."; } }
// Un-escape Node authzid = JID.unescapeNode(authzid); Collection<String> authorized = new ArrayList<>(); DirContext ctx = null; try { Rdn[] userRDN = manager.findUserRDN(authzid); // Load record. String[] attributes = new String[]{ usernameField, authorizeField }; ctx = manager.getContext(); Attributes attrs = ctx.getAttributes(LdapManager.escapeForJNDI(userRDN), attributes); Attribute authorizeField_a = attrs.get(authorizeField); if (authorizeField_a != null) { for (Enumeration e = authorizeField_a.getAll(); e.hasMoreElements();) { authorized.add((String)e.nextElement()); } } return authorized; } catch (Exception ex) { Log.debug("An exception occurred while trying to retrieve authorized principals for user {}.", authzid, ex); } finally { try { if (ctx != null) { ctx.close(); } } catch (Exception ex) { Log.debug("An exception occurred while trying to close a LDAP context after trying to retrieve authorized principals for user {}.", authzid, ex); } } return authorized;
623
347
970
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/lockout/DefaultLockOutProvider.java
DefaultLockOutProvider
getDisabledStatus
class DefaultLockOutProvider implements LockOutProvider { private static final Logger Log = LoggerFactory.getLogger(DefaultLockOutProvider.class); private static final String FLAG_ID = "lockout"; private static final String DELETE_FLAG = "DELETE FROM ofUserFlag WHERE username=? AND name='"+FLAG_ID+"'"; private static final String ADD_FLAG = "INSERT INTO ofUserFlag VALUES(?,'"+FLAG_ID+"',?,?)"; private static final String RETRIEVE_FLAG = "SELECT name,startTime,endTime FROM ofUserFlag WHERE username=? AND name='"+FLAG_ID+"'"; /** * Constructs a new DefaultLockOutProvider */ public DefaultLockOutProvider() { } /** * Default provider retrieves disabled status from ofUserFlag table. * @see org.jivesoftware.openfire.lockout.LockOutProvider#getDisabledStatus(String) */ @Override public LockOutFlag getDisabledStatus(String username) {<FILL_FUNCTION_BODY>} /** * Default provider deletes existing flag, if it exists, and adds new described flag in ofUserFlag table. * @see org.jivesoftware.openfire.lockout.LockOutProvider#setDisabledStatus(LockOutFlag) */ @Override public void setDisabledStatus(LockOutFlag flag) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(DELETE_FLAG); pstmt.setString(1, flag.getUsername()); pstmt.executeUpdate(); } catch (SQLException sqle) { // Nothing to do. } finally { DbConnectionManager.closeConnection(pstmt, con); } try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(ADD_FLAG); pstmt.setString(1, flag.getUsername()); if (flag.getStartTime() != null) { pstmt.setString(2, StringUtils.dateToMillis(flag.getStartTime())); } else { pstmt.setNull(2, Types.VARCHAR); } if (flag.getEndTime() != null) { pstmt.setString(3, StringUtils.dateToMillis(flag.getEndTime())); } else { pstmt.setNull(3, Types.VARCHAR); } pstmt.executeUpdate(); } catch (SQLException sqle) { // Nothing to do. } finally { DbConnectionManager.closeConnection(pstmt, con); } } /** * Default provider deletes existing flag from ofUserFlag table. * @see org.jivesoftware.openfire.lockout.LockOutProvider#unsetDisabledStatus(String) */ @Override public void unsetDisabledStatus(String username) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(DELETE_FLAG); pstmt.setString(1, username); pstmt.executeUpdate(); } catch (SQLException sqle) { // Nothing to do. } finally { DbConnectionManager.closeConnection(pstmt, con); } } /** * Default provider allows editing of disabled status. * @see org.jivesoftware.openfire.lockout.LockOutProvider#isReadOnly() */ @Override public boolean isReadOnly() { return false; } /** * Default provider allows delayed start to disabled status. * @see org.jivesoftware.openfire.lockout.LockOutProvider#isDelayedStartSupported() */ @Override public boolean isDelayedStartSupported() { return true; } /** * Default provider allows timeout of disabled status. * @see org.jivesoftware.openfire.lockout.LockOutProvider#isTimeoutSupported() */ @Override public boolean isTimeoutSupported() { return true; } /** * Default provider should be cached. * @see org.jivesoftware.openfire.lockout.LockOutProvider#shouldNotBeCached() */ @Override public boolean shouldNotBeCached() { return false; } }
Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; LockOutFlag ret = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(RETRIEVE_FLAG); pstmt.setString(1, username); rs = pstmt.executeQuery(); if (!rs.next()) { return null; } Date startTime = null; if (rs.getString(2) != null) { startTime = new Date(Long.parseLong(rs.getString(2).trim())); } Date endTime = null; if (rs.getString(3) != null) { endTime = new Date(Long.parseLong(rs.getString(3).trim())); } ret = new LockOutFlag(username, startTime, endTime); } catch (Exception e) { Log.error("Error loading lockout information from DB", e); return null; } finally { DbConnectionManager.closeConnection(rs, pstmt, con); } return ret;
1,168
288
1,456
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/lockout/LockOutEventDispatcher.java
LockOutEventDispatcher
lockedAccountDenied
class LockOutEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(LockOutEventDispatcher.class); private static List<LockOutEventListener> listeners = new CopyOnWriteArrayList<>(); /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(LockOutEventListener listener) { if (listener == null) { throw new NullPointerException(); } listeners.add(listener); } /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(LockOutEventListener listener) { listeners.remove(listener); } /** * Notifies the listeners that an account was just set to be disabled/locked out. * * @param flag The LockOutFlag that was set, which includes the username of the account and start/end times. */ public static void accountLocked(LockOutFlag flag) { if (!listeners.isEmpty()) { for (LockOutEventListener listener : listeners) { try { listener.accountLocked(flag); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'accountLocked' event!", e); } } } } /** * Notifies the listeners that an account was just enabled (lockout removed). * * @param username The username of the account that was enabled. */ public static void accountUnlocked(String username) { if (!listeners.isEmpty()) { for (LockOutEventListener listener : listeners) { try { listener.accountUnlocked(username); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'accountUnlocked' event!", e); } } } } /** * Notifies the listeners that a locked out account attempted to log in. * * @param username The username of the account that tried to log in. */ public static void lockedAccountDenied(String username) {<FILL_FUNCTION_BODY>} }
if (!listeners.isEmpty()) { for (LockOutEventListener listener : listeners) { try { listener.lockedAccountDenied(username); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'lockedAccountDenied' event!", e); } } }
554
84
638
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/lockout/LockOutFlag.java
LockOutFlag
getCachedSize
class LockOutFlag implements Cacheable, Externalizable { private String username; private Date startTime = null; private Date endTime = null; /** * Constructor added for Externalizable. Do not use this constructor. */ public LockOutFlag() { } /** * Creates a representation of a lock out flag, including which user it is attached to * and an optional start and end time. * * @param username User the flag is attached to. * @param startTime Optional start time for the disabled status to start. * @param endTime Optional end time for the disabled status to end. */ public LockOutFlag(String username, Date startTime, Date endTime) { this.username = username; this.startTime = startTime; this.endTime = endTime; } /** * Retrieves the username that this lock out flag is attached to. * * @return Username the flag is attached to. */ public String getUsername() { return username; } /** * Retrieves the date/time at which the account this flag references will begin having a disabled status. * This can be null if there is no start time set, meaning that the start time is immediate. * * @return The Date when the disabled status will start, or null for immediately. */ public Date getStartTime() { return startTime; } /** * Sets the start time for when the account will be disabled, or null if immediate. * * @param startTime Date when the disabled status will start, or null for immediately. */ public void setStartTime(Date startTime) { this.startTime = startTime; } /** * Retrieves the date/time at which the account this flag references will stop having a disabled status. * This can be null if the disabled status is to continue until manually disabled. * * @return The Date when the disabled status will end, or null for "forever". */ public Date getEndTime() { return endTime; } /** * Sets the end time for when the account will be reenabled, or null if manual reenable required. * * @param endTime Date when the disabled status will end, or null for forever. */ public void setEndTime(Date endTime) { this.endTime = endTime; } @Override public int getCachedSize() {<FILL_FUNCTION_BODY>} @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeSafeUTF(out, username); ExternalizableUtil.getInstance().writeLong(out, startTime != null ? startTime.getTime() : -1); ExternalizableUtil.getInstance().writeLong(out, endTime != null ? endTime.getTime() : -1); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { username = ExternalizableUtil.getInstance().readSafeUTF(in); long st = ExternalizableUtil.getInstance().readLong(in); startTime = st != -1 ? new Date(st) : null; long et = ExternalizableUtil.getInstance().readLong(in); endTime = et != -1 ? new Date(et) : null; } }
// Approximate the size of the object in bytes by calculating the size // of each field. int size = 0; size += CacheSizes.sizeOfObject(); // overhead of object size += CacheSizes.sizeOfString(username); size += CacheSizes.sizeOfDate(); size += CacheSizes.sizeOfDate(); return size;
853
95
948
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/lockout/LockOutManager.java
LockOutManagerContainer
initProvider
class LockOutManagerContainer { private static LockOutManager instance = new LockOutManager(); } /** * Returns the currently-installed LockOutProvider. <b>Warning:</b> in virtually all * cases the lockout provider should not be used directly. Instead, the appropriate * methods in LockOutManager should be called. Direct access to the lockout provider is * only provided for special-case logic. * * @return the current LockOutProvider. */ public static LockOutProvider getLockOutProvider() { return LockOutManagerContainer.instance.provider; } /** * Returns a singleton instance of LockOutManager. * * @return a LockOutManager instance. */ public static LockOutManager getInstance() { return LockOutManagerContainer.instance; } /* Cache of locked out accounts */ private Cache<String,LockOutFlag> lockOutCache; private static LockOutProvider provider; /** * Constructs a LockOutManager, setting up it's cache, propery listener, and setting up the provider. */ private LockOutManager() { // Initialize the lockout cache. lockOutCache = CacheFactory.createCache("Locked Out Accounts"); // Load an lockout provider. initProvider(LOCKOUT_PROVIDER.getValue()); } /** * Initializes the server's lock out provider, based on configuration and defaults to * DefaultLockOutProvider if the specified provider is not valid or not specified. */ private static void initProvider(final Class clazz) {<FILL_FUNCTION_BODY>
if (provider == null || !clazz.equals(provider.getClass())) { try { provider = (LockOutProvider) clazz.newInstance(); } catch (Exception e) { Log.error("Error loading lockout provider: " + clazz.getName(), e); provider = new DefaultLockOutProvider(); } }
405
90
495
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/mediaproxy/Channel.java
Channel
cancel
class Channel implements Runnable { private static final Logger Log = LoggerFactory.getLogger(Channel.class); protected byte[] buf = new byte[5000]; protected DatagramSocket dataSocket; protected DatagramPacket packet; protected boolean enabled = true; List<DatagramListener> listeners = new ArrayList<>(); protected InetAddress host; protected int port; /** * Creates a Channel according to the parameters. * * @param dataSocket datasocket to used to send and receive packets * @param host default destination host for received packets * @param port default destination port for received packets */ public Channel(DatagramSocket dataSocket, InetAddress host, int port) { this.dataSocket = dataSocket; this.host = host; this.port = port; } /** * Get the host that the packet will be sent to. * * @return remote host address */ public InetAddress getHost() { return host; } /** * Set the host that the packet will be sent to. * @param host the host to send the packet to */ protected void setHost(InetAddress host) { this.host = host; } /** * Get the port that the packet will be sent to. * * @return The remote port number */ public int getPort() { return port; } /** * Set the port that the packet will be sent to. * * @param port the port to send the packet to */ protected void setPort(int port) { this.port = port; } /** * Adds a DatagramListener to the Channel * * @param datagramListener the listener to add */ public void addListener(DatagramListener datagramListener) { listeners.add(datagramListener); } /** * Remove a DatagramListener from the Channel * * @param datagramListener the listener to remove */ public void removeListener(DatagramListener datagramListener) { listeners.remove(datagramListener); } /** * Remove every Listeners */ public void removeListeners() { listeners.clear(); } public void cancel() {<FILL_FUNCTION_BODY>} /** * Thread override method */ @Override public void run() { try { while (enabled) { // Block until a datagram appears: packet = new DatagramPacket(buf, buf.length); dataSocket.receive(packet); if (handle(packet)) { boolean resend = true; for (DatagramListener dl : listeners) { boolean send = dl.datagramReceived(packet); if (resend && !send) { resend = false; } } if (resend) { relayPacket(packet); } } } } catch (UnknownHostException uhe) { if (enabled) { Log.error("Unknown Host", uhe); } } catch (SocketException se) { if (enabled) { Log.error("Socket closed", se); } } catch (IOException ioe) { if (enabled) { Log.error("Communication error", ioe); } } } public void relayPacket(DatagramPacket packet) { try { DatagramPacket echo = new DatagramPacket(packet.getData(), packet.getLength(), host, port); dataSocket.send(echo); } catch (IOException e) { Log.error(e.getMessage(), e); } } /** * Handles received packet and returns true if the packet should be processed by the channel. * * @param packet received datagram packet * @return true if listeners will be alerted that a new packet was received. */ abstract boolean handle(DatagramPacket packet); }
this.enabled = false; if (dataSocket != null){ dataSocket.close(); }
1,050
31
1,081
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/mediaproxy/DynamicAddressChannel.java
DynamicAddressChannel
handle
class DynamicAddressChannel extends Channel implements Runnable, DatagramListener { private int c = 0; /** * Default Channel Constructor * * @param dataSocket datasocket to used to send and receive packets * @param host default destination host for received packets * @param port default destination port for received packets */ public DynamicAddressChannel(DatagramSocket dataSocket, InetAddress host, int port) { super(dataSocket, host, port); } @Override boolean handle(DatagramPacket packet) {<FILL_FUNCTION_BODY>} /** * Implement DatagramListener method. * Set the host and port value to the host and port value from the received packet. * * @param datagramPacket the received packet */ @Override public boolean datagramReceived(DatagramPacket datagramPacket) { this.relayPacket(datagramPacket); return false; } }
// Relay Destination if (c++ < 100) { // 100 packets are enough to discover relay address this.setHost(packet.getAddress()); this.setPort(packet.getPort()); return true; } else { c = 1000; // Prevents long overflow // Check Source Address. If it's different, discard packet. return this.getHost().equals(packet.getAddress()); }
249
121
370
<methods>public void <init>(java.net.DatagramSocket, java.net.InetAddress, int) ,public void addListener(org.jivesoftware.openfire.mediaproxy.DatagramListener) ,public void cancel() ,public java.net.InetAddress getHost() ,public int getPort() ,public void relayPacket(java.net.DatagramPacket) ,public void removeListener(org.jivesoftware.openfire.mediaproxy.DatagramListener) ,public void removeListeners() ,public void run() <variables>private static final Logger Log,protected byte[] buf,protected java.net.DatagramSocket dataSocket,protected boolean enabled,protected java.net.InetAddress host,List<org.jivesoftware.openfire.mediaproxy.DatagramListener> listeners,protected java.net.DatagramPacket packet,protected int port
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/mediaproxy/Echo.java
Echo
run
class Echo implements Runnable { private static final Logger Log = LoggerFactory.getLogger(Echo.class); DatagramSocket socket = null; byte password[] = null; List<DatagramListener> listeners = new ArrayList<>(); boolean enabled = true; public Echo(int port) throws UnknownHostException, SocketException { this.socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0")); } @Override public void run() {<FILL_FUNCTION_BODY>} public void cancel() { this.enabled = false; socket.close(); } }
try { //System.out.println("Listening for ECHO: " + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort()); while (true) { DatagramPacket packet = new DatagramPacket(new byte[8], 8); socket.receive(packet); System.out.println("ECHO Packet Received in: " + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + " From: " + packet.getAddress().getHostAddress() + ":" + packet.getPort()); for (DatagramListener listener : listeners) { try { listener.datagramReceived(packet); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'datagramReceived' event!", e); } } packet.setAddress(packet.getAddress()); packet.setPort(packet.getPort()); if (!Arrays.equals(packet.getData(), password)) for (int i = 0; i < 3; i++) socket.send(packet); } } catch (IOException ioe) { if (enabled) { } }
170
313
483
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/mediaproxy/RelaySession.java
RelaySession
createChannels
class RelaySession extends MediaProxySession { /** * Creates a new Smart Session to provide connectivity between Host A and Host B. * * @param id of the Session (Could be a Jingle session ID) * @param localhost The localhost IP that will listen for UDP packets * @param hostA the hostname or IP of the point A of the Channel * @param portA the port number point A of the Channel * @param hostB the hostname or IP of the point B of the Channel * @param portB the port number point B of the Channel * @param creator the created name or description of the Channel * @param minPort the minimal port number to be used by the proxy * @param maxPort the maximun port number to be used by the proxy */ public RelaySession(String id, String creator, String localhost, String hostA, int portA, String hostB, int portB, int minPort, int maxPort) { super(id, creator, localhost, hostA, portA, hostB, portB, minPort, maxPort); } /** * Creates a new Smart Session to provide connectivity between Host A and Host B. * * @param id of the Session (Could be a Jingle session ID) * @param localhost The localhost IP that will listen for UDP packets * @param hostA the hostname or IP of the point A of the Channel * @param portA the port number point A of the Channel * @param hostB the hostname or IP of the point B of the Channel * @param portB the port number point B of the Channel * @param creator the created name or description of the Channel */ public RelaySession(String id, String creator, String localhost, String hostA, int portA, String hostB, int portB) { super(id, creator, localhost, hostA, portA, hostB, portB, 10000, 20000); } @Override void createChannels() {<FILL_FUNCTION_BODY>} @Override void addChannelListeners() { super.addChannelListeners(); // Add channel as listeners channelAtoB.addListener((DynamicAddressChannel) channelBtoA); channelAtoBControl.addListener((DynamicAddressChannel) channelBtoAControl); channelBtoA.addListener((DynamicAddressChannel) channelAtoB); channelBtoAControl.addListener((DynamicAddressChannel) channelAtoBControl); } }
channelAtoB = new DynamicAddressChannel(socketA, hostB, portB); channelAtoBControl = new DynamicAddressChannel(socketAControl, hostB, portB + 1); channelBtoA = new DynamicAddressChannel(socketB, hostA, portA); channelBtoAControl = new DynamicAddressChannel(socketBControl, hostA, portA + 1);
644
99
743
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, java.lang.String, int, int, int) ,public void addAgentListener(org.jivesoftware.openfire.mediaproxy.SessionListener) ,public void clearAgentListeners() ,public boolean datagramReceived(java.net.DatagramPacket) ,public void dispatchAgentStopped() ,public java.lang.String getCreator() ,public java.net.InetAddress getHostA() ,public java.net.InetAddress getHostB() ,public int getLocalPortA() ,public int getLocalPortB() ,public java.net.InetAddress getLocalhost() ,public java.lang.String getPass() ,public int getPortA() ,public int getPortB() ,public java.lang.String getSID() ,public long getTimestamp() ,public void removeAgentListener(org.jivesoftware.openfire.mediaproxy.SessionListener) ,public void run() ,public void sendFromPortA(java.lang.String, int) ,public void sendFromPortB(java.lang.String, int) ,public void setHostA(java.net.InetAddress) ,public void setHostB(java.net.InetAddress) ,public void setPortA(int) ,public void setPortB(int) ,public void stopAgent() <variables>private static final Logger Log,protected org.jivesoftware.openfire.mediaproxy.Channel channelAtoB,protected org.jivesoftware.openfire.mediaproxy.Channel channelAtoBControl,protected org.jivesoftware.openfire.mediaproxy.Channel channelBtoA,protected org.jivesoftware.openfire.mediaproxy.Channel channelBtoAControl,private java.lang.String creator,protected java.net.InetAddress hostA,protected java.net.InetAddress hostB,private java.lang.String id,private java.util.Timer idleTimer,private java.util.Timer lifeTimer,protected java.net.InetAddress localAddress,protected int localPortA,protected int localPortB,private int maxPort,private int minPort,private java.lang.String pass,protected int portA,protected int portB,private List<org.jivesoftware.openfire.mediaproxy.SessionListener> sessionListeners,protected java.net.DatagramSocket socketA,protected java.net.DatagramSocket socketAControl,protected java.net.DatagramSocket socketB,protected java.net.DatagramSocket socketBControl,protected java.lang.Thread threadAtoB,protected java.lang.Thread threadAtoBControl,protected java.lang.Thread threadBtoA,protected java.lang.Thread threadBtoAControl,private long timestamp
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/HistoryRequest.java
HistoryRequest
sendHistory
class HistoryRequest { private static final Logger Log = LoggerFactory.getLogger(HistoryRequest.class); private static final XMPPDateTimeFormat xmppDateTime = new XMPPDateTimeFormat(); private int maxChars = -1; private int maxStanzas = -1; private int seconds = -1; private Date since; public HistoryRequest(Element userFragment) { Element history = userFragment.element("history"); if (history != null) { if (history.attribute("maxchars") != null) { this.maxChars = Integer.parseInt(history.attributeValue("maxchars")); } if (history.attribute("maxstanzas") != null) { this.maxStanzas = Integer.parseInt(history.attributeValue("maxstanzas")); } if (history.attribute("seconds") != null) { this.seconds = Integer.parseInt(history.attributeValue("seconds")); } if (history.attribute("since") != null) { try { // parse since String into Date this.since = xmppDateTime.parseString(history.attributeValue("since")); } catch(ParseException pe) { Log.error("Error parsing date from history management", pe); this.since = null; } } } } /** * Returns the total number of characters to receive in the history. * * @return total number of characters to receive in the history. */ public int getMaxChars() { return maxChars; } /** * Returns the total number of messages to receive in the history. * * @return the total number of messages to receive in the history. */ public int getMaxStanzas() { return maxStanzas; } /** * Returns the number of seconds to use to filter the messages received during that time. * In other words, only the messages received in the last "X" seconds will be included in * the history. * * @return the number of seconds to use to filter the messages received during that time. */ public int getSeconds() { return seconds; } /** * Returns the since date to use to filter the messages received during that time. * In other words, only the messages received since the datetime specified will be * included in the history. * * @return the since date to use to filter the messages received during that time. */ public Date getSince() { return since; } /** * Returns true if the history has been configured with some values. * * @return true if the history has been configured with some values. */ private boolean isConfigured() { return maxChars > -1 || maxStanzas > -1 || seconds > -1 || since != null; } /** * Sends the smallest amount of traffic that meets any combination of the requested criteria. * * @param joinRole the user that will receive the history. * @param roomHistory the history of the room. */ public void sendHistory(MUCRole joinRole, MUCRoomHistory roomHistory) {<FILL_FUNCTION_BODY>} }
if (!isConfigured()) { Iterator<Message> history = roomHistory.getMessageHistory(); while (history.hasNext()) { // OF-2163: Create a defensive copy of the message, to prevent the address that it is sent to to leak back into the archive. joinRole.send(history.next().createCopy()); } } else { if (getMaxChars() == 0) { // The user requested to receive no history return; } int accumulatedChars = 0; int accumulatedStanzas = 0; Element delayInformation; LinkedList<Message> historyToSend = new LinkedList<>(); ListIterator<Message> iterator = roomHistory.getReverseMessageHistory(); while (iterator.hasPrevious()) { Message message = iterator.previous(); // Update number of characters to send String text = message.getBody() == null ? message.getSubject() : message.getBody(); if (text == null) { // Skip this message since it has no body and no subject continue; } accumulatedChars += text.length(); if (getMaxChars() > -1 && accumulatedChars > getMaxChars()) { // Stop collecting history since we have exceded a limit break; } // Update number of messages to send accumulatedStanzas ++; if (getMaxStanzas() > -1 && accumulatedStanzas > getMaxStanzas()) { // Stop collecting history since we have exceded a limit break; } if (getSeconds() > -1 || getSince() != null) { delayInformation = message.getChildElement("delay", "urn:xmpp:delay"); try { // Get the date when the historic message was sent Date delayedDate = xmppDateTime.parseString(delayInformation.attributeValue("stamp")); if (getSince() != null && delayedDate != null && delayedDate.before(getSince())) { // Stop collecting history since we have exceded a limit break; } if (getSeconds() > -1) { Date current = new Date(); long diff = (current.getTime() - delayedDate.getTime()) / 1000; if (getSeconds() <= diff) { // Stop collecting history since we have exceded a limit break; } } } catch (Exception e) { Log.error("Error parsing date from historic message", e); } } historyToSend.addFirst(message); } // Send the smallest amount of traffic to the user for (final Message aHistoryToSend : historyToSend) { // OF-2163: Create a defensive copy of the message, to prevent the address that it is sent to to leak back into the archive. joinRole.send(aHistoryToSend.createCopy()); } }
833
739
1,572
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCEventDelegate.java
MUCEventDelegate
loadConfig
class MUCEventDelegate { public enum InvitationResult { HANDLED_BY_DELEGATE, HANDLED_BY_OPENFIRE, REJECTED }; public enum InvitationRejectionResult { HANDLED_BY_DELEGATE, HANDLED_BY_OPENFIRE, }; /** * This event will be triggered when an entity joins an existing room. * * Returns true if the user is allowed to join the room. * * @param room the MUC room. * @param userjid the JID of the user attempting to join the room. * @return true if the user is allowed to join the room. */ public abstract boolean joiningRoom(MUCRoom room, JID userjid); /** * This event will be triggered when an entity attempts to invite someone to a room. * * Returns a String indicating whether the invitation should be abandoned, handled by the delegate, or handled by openfire. * * @param room the MUC room. * @param inviteeJID the JID of the user the invitation will be sent to. * @param inviterJID the JID of the user that is sending the invitation * @param inviteMessage the (optional) message that is sent explaining the invitation * @return true if the user is allowed to join the room. */ public abstract InvitationResult sendingInvitation(MUCRoom room, JID inviteeJID, JID inviterJID, String inviteMessage); /** * This event will be triggered when an entity reject invite from someone to a room. * * Returns a String indicating whether the invitation should be abandoned, handled by the delegate, or handled by openfire. * * @param room the MUC room. * @param to the JID of the user the rejecting of invitation will be sent to. * @param from the JID of the user that is sending the rejecting of invitation * @param reason the (optional) message that is sent explaining the rejection invitation * @return true if the user is allowed to join the room. */ public abstract InvitationRejectionResult sendingInvitationRejection(MUCRoom room, JID to, JID from, String reason); /** * Returns a map containing room configuration variables and values. * * @param roomName the name of the room the configuration map is associated with. * @return a map containing room configuration variables and values, or null if roomName was not valid. */ public abstract Map<String, String> getRoomConfig(String roomName); /** * This event will be triggered when an entity attempts to destroy a room. * * Returns true if the user is allowed to destroy the room. * * @param roomName the name of the MUC room being destroyed. * @param userjid the JID of the user attempting to destroy the room. * @return true if the user is allowed to destroy the room. */ public abstract boolean destroyingRoom(String roomName, JID userjid); /** * Returns true if the room that is not present in the server should have existed and needs * to be recreated. * * @param roomName name of the room. * @param userjid JID Of the user trying to join/create the room. * @return true if the room that is not present in the server should have existed and needs * to be recreated. */ public abstract boolean shouldRecreate(String roomName, JID userjid); /** * Loads a delegate provided room configuration for the room specified. * * @param room the room to load the configuration for. * @return true if the room configuration was received from the delegate and applied to the room. */ public boolean loadConfig(MUCRoom room) {<FILL_FUNCTION_BODY>} }
Map<String, String> roomConfig = getRoomConfig(room.getName()); if (roomConfig != null) { room.setNaturalLanguageName(roomConfig.get("muc#roomconfig_roomname")); room.setDescription(roomConfig.get("muc#roomconfig_roomdesc")); room.setCanOccupantsChangeSubject("1".equals(roomConfig.get("muc#roomconfig_changesubject"))); room.setMaxUsers(Integer.parseInt(roomConfig.get("muc#roomconfig_maxusers"))); room.setPublicRoom("1".equals(roomConfig.get("muc#roomconfig_publicroom"))); room.setCanOccupantsInvite("1".equals(roomConfig.get("muc#roomconfig_allowinvites"))); room.setCanAnyoneDiscoverJID("anyone".equals(roomConfig.get("muc#roomconfig_whois"))); room.setCanSendPrivateMessage( roomConfig.get("muc#roomconfig_allowpm") ); room.setChangeNickname("1".equals(roomConfig.get("x-muc#roomconfig_canchangenick"))); room.setRegistrationEnabled("1".equals(roomConfig.get("x-muc#roomconfig_registration"))); room.setPersistent("1".equals(roomConfig.get("muc#roomconfig_persistentroom"))); final String property = roomConfig.get("muc#roomconfig_roomowners"); if (property != null) { String jids[] = property.split(","); for (String jid : jids) { if (jid != null && jid.trim().length() != 0) { room.addFirstOwner(new JID(jid.trim().toLowerCase()).asBareJID()); } } } try { room.unlock(room.getRole()); } catch (ForbiddenException e) { return false; } } return roomConfig != null;
969
513
1,482
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCEventDispatcher.java
MUCEventDispatcher
roomCreated
class MUCEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(MUCEventDispatcher.class); private static final Collection<MUCEventListener> listeners = new ConcurrentLinkedQueue<>(); public static void addListener(MUCEventListener listener) { listeners.add(listener); } public static void removeListener(MUCEventListener listener) { listeners.remove(listener); } public static void occupantJoined(JID roomJID, JID user, String nickname) { for (MUCEventListener listener : listeners) { try { listener.occupantJoined(roomJID, user, nickname); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'occupantJoined' event!", e); } } } public static void occupantLeft(JID roomJID, JID user, String nickname) { for (MUCEventListener listener : listeners) { try { listener.occupantLeft(roomJID, user, nickname); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'occupantLeft' event!", e); } } } public static void nicknameChanged(JID roomJID, JID user, String oldNickname, String newNickname) { for (MUCEventListener listener : listeners) { try { listener.nicknameChanged(roomJID, user, oldNickname, newNickname); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'nicknameChanged' event!", e); } } } public static void messageReceived(JID roomJID, JID user, String nickname, Message message) { for (MUCEventListener listener : listeners) { try { listener.messageReceived(roomJID, user, nickname, message); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'messageReceived' event!", e); } } } public static void privateMessageRecieved(JID toJID, JID fromJID, Message message) { for (MUCEventListener listener : listeners) { try { listener.privateMessageRecieved(toJID, fromJID, message); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'privateMessageRecieved' event!", e); } } } public static void roomCreated(JID roomJID) {<FILL_FUNCTION_BODY>} public static void roomDestroyed(JID roomJID) { for (MUCEventListener listener : listeners) { try { listener.roomDestroyed(roomJID); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'roomDestroyed' event!", e); } } } public static void roomSubjectChanged(JID roomJID, JID user, String newSubject) { for (MUCEventListener listener : listeners) { try { listener.roomSubjectChanged(roomJID, user, newSubject); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'roomSubjectChanged' event!", e); } } } }
for (MUCEventListener listener : listeners) { try { listener.roomCreated(roomJID); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'roomCreated' event!", e); } }
857
68
925
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/MUCServicePropertyClusterEventTask.java
MUCServicePropertyClusterEventTask
writeExternal
class MUCServicePropertyClusterEventTask implements ClusterTask<Void> { private Type event; private String service; private String key; private String value; public static MUCServicePropertyClusterEventTask createPutTask(String service, String key, String value) { MUCServicePropertyClusterEventTask task = new MUCServicePropertyClusterEventTask(); task.event = Type.put; task.service = service; task.key = key; task.value = value; return task; } public static MUCServicePropertyClusterEventTask createDeleteTask(String service, String key) { MUCServicePropertyClusterEventTask task = new MUCServicePropertyClusterEventTask(); task.event = Type.deleted; task.service = service; task.key = key; return task; } @Override public Void getResult() { return null; } @Override public void run() { if (Type.put == event) { MUCPersistenceManager.setLocalProperty(service, key, value); } else if (Type.deleted == event) { MUCPersistenceManager.deleteLocalProperty(service, key); } } @Override public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { event = Type.values()[ExternalizableUtil.getInstance().readInt(in)]; service = ExternalizableUtil.getInstance().readSafeUTF(in); key = ExternalizableUtil.getInstance().readSafeUTF(in); if (ExternalizableUtil.getInstance().readBoolean(in)) { value = ExternalizableUtil.getInstance().readSafeUTF(in); } } private static enum Type { /** * Event triggered when a muc service property was added or updated in the system. */ put, /** * Event triggered when a muc service property was deleted from the system. */ deleted } }
ExternalizableUtil.getInstance().writeInt(out, event.ordinal()); ExternalizableUtil.getInstance().writeSafeUTF(out, service); ExternalizableUtil.getInstance().writeSafeUTF(out, key); ExternalizableUtil.getInstance().writeBoolean(out, value != null); if (value != null) { ExternalizableUtil.getInstance().writeSafeUTF(out, value); }
527
105
632
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/NewClusterMemberJoinedTask.java
NewClusterMemberJoinedTask
readExternal
class NewClusterMemberJoinedTask implements ClusterTask<Void> { private static final Logger Log = LoggerFactory.getLogger(NewClusterMemberJoinedTask.class); private NodeID originator; public NewClusterMemberJoinedTask() { this.originator = XMPPServer.getInstance().getNodeID(); } public NodeID getOriginator() { return originator; } @Override public Void getResult() { return null; } @Override public void run() { Log.debug("Node {} informed us that it has joined the cluster. Firing joined cluster event for that node.", originator); ClusterManager.fireJoinedCluster(originator.toByteArray(), true); } @Override public void writeExternal(ObjectOutput out) throws IOException { final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); externalizableUtil.writeSerializable(out, originator); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); originator = (NodeID) externalizableUtil.readSerializable(in);
282
40
322
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/OccupantAddedTask.java
OccupantAddedTask
readExternal
class OccupantAddedTask implements ClusterTask<Void> { private String subdomain; private String roomName; private String nickname; private JID realJID; private NodeID originator; public OccupantAddedTask() {} public OccupantAddedTask(@Nonnull final String subdomain, @Nonnull final String roomName, @Nonnull final String nickname, @Nonnull final JID realJID, @Nonnull final NodeID originator) { this.subdomain = subdomain; this.roomName = roomName; this.nickname = nickname; this.realJID = realJID; this.originator = originator; } public String getSubdomain() { return subdomain; } public String getRoomName() { return roomName; } public String getNickname() { return nickname; } public JID getRealJID() { return realJID; } public NodeID getOriginator() { return originator; } @Override public Void getResult() { return null; } @Override public void run() { final MultiUserChatService multiUserChatService = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(subdomain); ((MultiUserChatServiceImpl) multiUserChatService).getOccupantManager().process(this); } @Override public void writeExternal(ObjectOutput out) throws IOException { final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); externalizableUtil.writeSafeUTF(out, subdomain); externalizableUtil.writeSafeUTF(out, roomName); externalizableUtil.writeSafeUTF(out, nickname); externalizableUtil.writeSerializable(out, realJID); externalizableUtil.writeSerializable(out, originator); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); subdomain = externalizableUtil.readSafeUTF(in); roomName = externalizableUtil.readSafeUTF(in); nickname = externalizableUtil.readSafeUTF(in); realJID = (JID) externalizableUtil.readSerializable(in); originator = (NodeID) externalizableUtil.readSerializable(in);
528
105
633
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/OccupantKickedForNicknameTask.java
OccupantKickedForNicknameTask
readExternal
class OccupantKickedForNicknameTask implements ClusterTask<Void> { private String subdomain; private String roomName; private String nickname; private NodeID originator; public OccupantKickedForNicknameTask() {} public OccupantKickedForNicknameTask(@Nonnull final String subdomain, @Nonnull final String roomName, @Nonnull final String nickname, @Nonnull final NodeID originator) { this.subdomain = subdomain; this.roomName = roomName; this.nickname = nickname; this.originator = originator; } public String getSubdomain() { return subdomain; } public String getRoomName() { return roomName; } public String getNickname() { return nickname; } public NodeID getOriginator() { return originator; } @Override public Void getResult() { return null; } @Override public void run() { final MultiUserChatService multiUserChatService = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(subdomain); ((MultiUserChatServiceImpl) multiUserChatService).getOccupantManager().process(this); } @Override public void writeExternal(ObjectOutput out) throws IOException { final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); externalizableUtil.writeSafeUTF(out, subdomain); externalizableUtil.writeSafeUTF(out, roomName); externalizableUtil.writeSafeUTF(out, nickname); externalizableUtil.writeSerializable(out, originator); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); subdomain = externalizableUtil.readSafeUTF(in); roomName = externalizableUtil.readSafeUTF(in); nickname = externalizableUtil.readSafeUTF(in); originator = (NodeID) externalizableUtil.readSerializable(in);
475
85
560
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/OccupantRemovedTask.java
OccupantRemovedTask
readExternal
class OccupantRemovedTask implements ClusterTask<Void> { private String subdomain; private String roomName; private String nickname; private JID realJID; private NodeID originator; public OccupantRemovedTask() {} public OccupantRemovedTask(@Nonnull final String subdomain, @Nonnull final String roomName, @Nonnull final String nickname, @Nonnull final JID realJID, @Nonnull final NodeID originator) { this.subdomain = subdomain; this.roomName = roomName; this.nickname = nickname; this.realJID = realJID; this.originator = originator; } public String getSubdomain() { return subdomain; } public String getRoomName() { return roomName; } public String getNickname() { return nickname; } public JID getRealJID() { return realJID; } public NodeID getOriginator() { return originator; } @Override public Void getResult() { return null; } @Override public void run() { final MultiUserChatService multiUserChatService = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(subdomain); ((MultiUserChatServiceImpl) multiUserChatService).getOccupantManager().process(this); } @Override public void writeExternal(ObjectOutput out) throws IOException { final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); externalizableUtil.writeSafeUTF(out, subdomain); externalizableUtil.writeSafeUTF(out, roomName); externalizableUtil.writeSafeUTF(out, nickname); externalizableUtil.writeSerializable(out, realJID); externalizableUtil.writeSerializable(out, originator); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); subdomain = externalizableUtil.readSafeUTF(in); roomName = externalizableUtil.readSafeUTF(in); nickname = externalizableUtil.readSafeUTF(in); realJID = (JID) externalizableUtil.readSerializable(in); originator = (NodeID) externalizableUtil.readSerializable(in);
532
105
637
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/OccupantUpdatedTask.java
OccupantUpdatedTask
writeExternal
class OccupantUpdatedTask implements ClusterTask<Void> { private String subdomain; private String roomName; private String oldNickname; private String newNickname; private JID realJID; private NodeID originator; public OccupantUpdatedTask() {} public OccupantUpdatedTask(@Nonnull final String subdomain, @Nonnull final String roomName, @Nonnull final String oldNickname, @Nonnull final String newNickname, @Nonnull final JID realJID, @Nonnull final NodeID originator) { this.subdomain = subdomain; this.roomName = roomName; this.oldNickname = oldNickname; this.newNickname = newNickname; this.realJID = realJID; this.originator = originator; } public String getSubdomain() { return subdomain; } public String getRoomName() { return roomName; } public String getOldNickname() { return oldNickname; } public String getNewNickname() { return newNickname; } public JID getRealJID() { return realJID; } public NodeID getOriginator() { return originator; } @Override public Void getResult() { return null; } @Override public void run() { final MultiUserChatService multiUserChatService = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(subdomain); multiUserChatService.getOccupantManager().process(this); } @Override public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); subdomain = externalizableUtil.readSafeUTF(in); roomName = externalizableUtil.readSafeUTF(in); oldNickname = externalizableUtil.readSafeUTF(in); newNickname = externalizableUtil.readSafeUTF(in); realJID = (JID) externalizableUtil.readSerializable(in); originator = (NodeID) externalizableUtil.readSerializable(in); } }
final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); externalizableUtil.writeSafeUTF(out, subdomain); externalizableUtil.writeSafeUTF(out, roomName); externalizableUtil.writeSafeUTF(out, oldNickname); externalizableUtil.writeSafeUTF(out, newNickname); externalizableUtil.writeSerializable(out, realJID); externalizableUtil.writeSerializable(out, originator);
614
116
730
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/ServiceAddedEvent.java
ServiceAddedEvent
readExternal
class ServiceAddedEvent implements ClusterTask<Void> { private String subdomain; private String description; private Boolean isHidden; public ServiceAddedEvent() { } public ServiceAddedEvent(String subdomain, String description, Boolean isHidden) { this.subdomain = subdomain; this.description = description; this.isHidden = isHidden; } @Override public Void getResult() { return null; } @Override public void run() { // If it's registered already, no need to create it. Most likely this is because the service // is provided by an internal component that registered at startup. This scenario, however, // should really never occur. if (!XMPPServer.getInstance().getMultiUserChatManager().isServiceRegistered(subdomain)) { MultiUserChatService service = new MultiUserChatServiceImpl(subdomain, description, isHidden); XMPPServer.getInstance().getMultiUserChatManager().registerMultiUserChatService(service, false); } } @Override public void writeExternal(ObjectOutput out) throws IOException { final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); externalizableUtil.writeSafeUTF(out, subdomain); externalizableUtil.writeSafeUTF(out, description); externalizableUtil.writeBoolean(out, isHidden); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); subdomain = externalizableUtil.readSafeUTF(in); description = externalizableUtil.readSafeUTF(in); isHidden = externalizableUtil.readBoolean(in);
389
65
454
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/ServiceUpdatedEvent.java
ServiceUpdatedEvent
run
class ServiceUpdatedEvent implements ClusterTask<Void> { private static final Logger Log = LoggerFactory.getLogger(ServiceUpdatedEvent.class); private String subdomain; public ServiceUpdatedEvent() { } public ServiceUpdatedEvent(String subdomain) { this.subdomain = subdomain; } @Override public Void getResult() { return null; } @Override public void run() {<FILL_FUNCTION_BODY>} @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeSafeUTF(out, subdomain); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { subdomain = ExternalizableUtil.getInstance().readSafeUTF(in); } }
MultiUserChatService service = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(subdomain); if (service != null) { // Reload properties from database (OF-2164) XMPPServer.getInstance().getMultiUserChatManager().refreshService(subdomain); if (service instanceof MultiUserChatServiceImpl) { MUCPersistenceManager.refreshProperties(subdomain); ((MultiUserChatServiceImpl)service).initializeSettings(); } else { // Ok. We don't handle non default implementations for this. Why are we seeing it? Log.warn("Processing an update event for service '{}' that is of an unknown implementation: {}", subdomain, service.getClass()); } } else { // Hrm. We got an update for something that we don't have. Log.warn("ServiceUpdatedEvent: Received update for service we are not running: {}", subdomain); }
216
248
464
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/cluster/SyncLocalOccupantsAndSendJoinPresenceTask.java
SyncLocalOccupantsAndSendJoinPresenceTask
readExternal
class SyncLocalOccupantsAndSendJoinPresenceTask implements ClusterTask<Void> { private static final Logger Log = LoggerFactory.getLogger(SyncLocalOccupantsAndSendJoinPresenceTask.class); private String subdomain; private Set<OccupantManager.Occupant> occupants = new HashSet<>(); private NodeID originator; public SyncLocalOccupantsAndSendJoinPresenceTask() {} public SyncLocalOccupantsAndSendJoinPresenceTask(@Nonnull final String subdomain, @Nonnull final Set<OccupantManager.Occupant> occupants) { this.subdomain = subdomain; this.occupants = occupants; this.originator = XMPPServer.getInstance().getNodeID(); } public Set<OccupantManager.Occupant> getOccupants() { return occupants; } public NodeID getOriginator() { return originator; } @Override public Void getResult() { return null; } @Override public void run() { Log.debug("Going to execute sync occupants task for {} occupants from node {}", occupants.size(), originator); final MultiUserChatService multiUserChatService = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(subdomain); ((MultiUserChatServiceImpl) multiUserChatService).process(this); Log.trace("Finished executing sync occupants task for occupants {} from node {}", occupants.size(), originator); } @Override public void writeExternal(ObjectOutput out) throws IOException { final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); externalizableUtil.writeSafeUTF(out, subdomain); externalizableUtil.writeLong(out, occupants.size()); for (final OccupantManager.Occupant occupant : occupants) { externalizableUtil.writeSafeUTF(out, occupant.getRoomName()); externalizableUtil.writeSafeUTF(out, occupant.getNickname()); externalizableUtil.writeSerializable(out, occupant.getRealJID()); // We should not send the lastActive field, as that's used only by the cluster node that the occupant is local to. } externalizableUtil.writeSerializable(out, originator); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
final ExternalizableUtil externalizableUtil = ExternalizableUtil.getInstance(); subdomain = externalizableUtil.readSafeUTF(in); final long size = externalizableUtil.readLong(in); this.occupants = new HashSet<>(); for (long i=0; i<size; i++) { final String roomName = externalizableUtil.readSafeUTF(in); final String nickname = externalizableUtil.readSafeUTF(in); final JID realJID = (JID) externalizableUtil.readSerializable(in); final OccupantManager.Occupant occupant = new OccupantManager.Occupant(roomName, nickname, realJID); occupants.add(occupant); } originator = (NodeID) externalizableUtil.readSerializable(in);
632
203
835
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/IQMuclumbusSearchHandler.java
SearchParameters
toString
class SearchParameters { String q = null; boolean sinname = true; boolean sindescription = true; boolean sinaddr = true; int minUsers = 1; Key key = Key.address; public String getQ() { return q; } public void setQ( final String q ) { this.q = q; } public boolean isSinname() { return sinname; } public void setSinname( final boolean sinname ) { this.sinname = sinname; } public boolean isSindescription() { return sindescription; } public void setSindescription( final boolean sindescription ) { this.sindescription = sindescription; } public boolean isSinaddr() { return sinaddr; } public void setSinaddr( final boolean sinaddr ) { this.sinaddr = sinaddr; } public int getMinUsers() { return minUsers; } public void setMinUsers( final int minUsers ) { this.minUsers = minUsers; } public Key getKey() { return key; } public void setKey( final Key key ) { this.key = key; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SearchParameters{" + "q='" + q + '\'' + ", sinname=" + sinname + ", sindescription=" + sindescription + ", sinaddr=" + sinaddr + ", minUsers=" + minUsers + ", key=" + key + '}';
386
83
469
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MUCServicePropertyEventDispatcher.java
MUCServicePropertyEventDispatcher
addListener
class MUCServicePropertyEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(MUCServicePropertyEventDispatcher.class); private static Set<MUCServicePropertyEventListener> listeners = new CopyOnWriteArraySet<>(); private MUCServicePropertyEventDispatcher() { // Not instantiable. } /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(MUCServicePropertyEventListener listener) {<FILL_FUNCTION_BODY>} /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(MUCServicePropertyEventListener listener) { listeners.remove(listener); } /** * Dispatches an event to all listeners. * * @param service the subdomain of the MUC service the property is set for. * @param property the property. * @param eventType the event type. * @param params event parameters. */ public static void dispatchEvent(String service, String property, EventType eventType, Map<String, Object> params) { for (MUCServicePropertyEventListener listener : listeners) { try { switch (eventType) { case property_set: { listener.propertySet(service, property, params); break; } case property_deleted: { listener.propertyDeleted(service, property, params); break; } default: break; } } catch (Exception e) { Log.error(e.getMessage(), e); } } } /** * Represents valid event types. */ public enum EventType { /** * A property was set. */ property_set, /** * A property was deleted. */ property_deleted } }
if (listener == null) { throw new NullPointerException(); } listeners.add(listener);
498
33
531
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/spi/MultiUserChatServiceImpl.java
UserTimeoutTask
checkForTimedOutUsers
class UserTimeoutTask extends TimerTask { @Override public void run() { checkForTimedOutUsers(); } } /** * Informs all users local to this cluster node that he or she is being removed from the room because the MUC * service is being shut down. * * The implementation is optimized to run as fast as possible (to prevent prolonging the shutdown). */ private void broadcastShutdown() { Log.debug( "Notifying all local users about the imminent destruction of chat service '{}'", chatServiceName ); final Set<OccupantManager.Occupant> localOccupants = occupantManager.getLocalOccupants(); if (localOccupants.isEmpty()) { return; } // A thread pool is used to broadcast concurrently, as well as to limit the execution time of this service. final ThreadFactory threadFactory = new NamedThreadFactory("MUC-Shutdown-", Executors.defaultThreadFactory(), false, Thread.NORM_PRIORITY); final ExecutorService service = Executors.newFixedThreadPool( Math.min( localOccupants.size(), 10 ), threadFactory ); // Queue all tasks in the executor service. for ( final OccupantManager.Occupant localOccupant : localOccupants ) { service.submit(() -> { try { // Obtaining the room without acquiring a lock. Usage of the room is read-only (the implementation below // should not modify the room state in a way that the cluster cares about), and more importantly, speed // is of importance (waiting for every room's lock to be acquired would slow down the shutdown process). // Lastly, this service is shutting down (likely because the server is shutting down). The trade-off // between speed and access of room state while not holding a lock seems worth while here. final MUCRoom room = getChatRoom(localOccupant.getRoomName()); if (room == null) { // Mismatch between MUCUser#getRooms() and MUCRoom#localMUCRoomManager ? Log.warn("User '{}' appears to have had a role in room '{}' of service '{}' that does not seem to exist.", localOccupant.getRealJID(), localOccupant.getRoomName(), chatServiceName); return; } final MUCRole role = room.getOccupantByFullJID(localOccupant.getRealJID()); if (role == null) { // Mismatch between MUCUser#getRooms() and MUCRoom#occupants ? Log.warn("User '{}' appears to have had a role in room '{}' of service '{}' but that role does not seem to exist.", localOccupant.getRealJID(), localOccupant.getRoomName(), chatServiceName); return; } // Send a presence stanza of type "unavailable" to the occupant final Presence presence = room.createPresence( Presence.Type.unavailable ); presence.setFrom( role.getRoleAddress() ); // A fragment containing the x-extension. final Element fragment = presence.addChildElement( "x", "http://jabber.org/protocol/muc#user" ); final Element item = fragment.addElement( "item" ); item.addAttribute( "affiliation", "none" ); item.addAttribute( "role", "none" ); fragment.addElement( "status" ).addAttribute( "code", "332" ); // Make sure that the presence change for each user is only sent to that user (and not broadcast in the room)! // Not needed to create a defensive copy of the stanza. It's not used anywhere else. role.send( presence ); // Let all other cluster nodes know! room.removeOccupantRole(role); } catch ( final Exception e ) { Log.debug( "Unable to inform {} about the imminent destruction of chat service '{}'", localOccupant.realJID, chatServiceName, e ); } }); } // Try to shutdown - wait - force shutdown. service.shutdown(); try { if (service.awaitTermination( JiveGlobals.getIntProperty( "xmpp.muc.await-termination-millis", 500 ), TimeUnit.MILLISECONDS )) { Log.debug("Successfully notified all local users about the imminent destruction of chat service '{}'", chatServiceName); } else { Log.debug("Unable to notify all local users about the imminent destruction of chat service '{}' (timeout)", chatServiceName); } } catch ( final InterruptedException e ) { Log.debug( "Interrupted while waiting for all users to be notified of shutdown of chat service '{}'. Shutting down immediately.", chatServiceName ); } service.shutdownNow(); } /** * Iterates over the local occupants of MUC rooms (users connected to the local cluster node), to determine if an * action needs to be taken based on their (lack of) activity. Depending on the configuration of Openfire, inactive * users (users that are connected, but have not typed anything) are kicked from the room, and/or are explicitly * asked for a proof of life (connectivity), removing them if this proof is not given. */ private void checkForTimedOutUsers() {<FILL_FUNCTION_BODY>
for (final OccupantManager.Occupant occupant : occupantManager.getLocalOccupants()) { try { if (userIdleKick != null && occupant.getLastActive().isBefore(Instant.now().minus(userIdleKick))) { // Kick users if 'user_idle' feature is enabled and the user has been idle for too long. tryRemoveOccupantFromRoom(occupant, JiveGlobals.getProperty("admin.mucRoom.timeoutKickReason", "User was inactive for longer than the allowed maximum duration of " + userIdleKick.toString().substring(2).replaceAll("(\\d[HMS])(?!$)", "$1 ").toLowerCase()) + "." ); } else if (userIdlePing != null) { // Check if the occupant has been inactive for to long. final Instant lastActive = occupant.getLastActive(); final boolean isInactive = lastActive.isBefore(Instant.now().minus(userIdlePing)); // Ensure that we didn't quite recently send a ping already. final Instant lastPing = occupant.getLastPingRequest(); final boolean isRecentlyPinged = lastPing != null && lastPing.isAfter(Instant.now().minus(userIdlePing)); if (isInactive && !isRecentlyPinged) { // Ping the user if it hasn't been kicked already, the feature is enabled, and the user has been idle for too long. pingOccupant(occupant); } } } catch (final Throwable e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } }
1,386
443
1,829
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/multiplex/ClientSessionConnection.java
ClientSessionConnection
closeVirtualConnection
class ClientSessionConnection extends VirtualConnection { private String connectionManagerName; private String serverName; private ConnectionMultiplexerManager multiplexerManager; private String hostName; private String hostAddress; public ClientSessionConnection(String connectionManagerName, String hostName, String hostAddress) { this.connectionManagerName = connectionManagerName; multiplexerManager = ConnectionMultiplexerManager.getInstance(); serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); this.hostName = hostName; this.hostAddress = hostAddress; } /** * Delivers the packet to the Connection Manager that in turn will forward it to the * target user. Connection Managers may have one or many connections to the server so * just get any connection to the Connection Manager (uses a random) and use it.<p> * * If the packet to send does not have a TO attribute then wrap the packet with a * special IQ packet. The wrapper IQ packet will be sent to the Connection Manager * and the stream ID of this Client Session will be used for identifying that the wrapped * packet must be sent to the connected user. Since some packets can be exchanged before * the user has a binded JID we need to use the stream ID as the unique identifier. * * @param packet the packet to send to the user. */ @Override public void deliver(Packet packet) { StreamID streamID = session.getStreamID(); ConnectionMultiplexerSession multiplexerSession = multiplexerManager.getMultiplexerSession(connectionManagerName,streamID); if (multiplexerSession != null) { // Wrap packet so that the connection manager can figure out the target session Route wrapper = new Route(streamID); wrapper.setFrom(serverName); wrapper.setTo(connectionManagerName); wrapper.setChildElement(packet.getElement().createCopy()); // Deliver wrapper multiplexerSession.process(wrapper); session.incrementServerPacketCount(); } } /** * Delivers the stanza to the Connection Manager that in turn will forward it to the * target user. Connection Managers may have one or many connections to the server so * just get any connection to the Connection Manager (uses a random) and use it.<p> * * The stanza to send wrapped with a special IQ packet. The wrapper IQ packet will be * sent to the Connection Manager and the stream ID of this Client Session will be used * for identifying that the wrapped stanza must be sent to the connected user. * * @param text the stanza to send to the user. */ @Override public void deliverRawText(String text) { StreamID streamID = session.getStreamID(); ConnectionMultiplexerSession multiplexerSession = multiplexerManager.getMultiplexerSession(connectionManagerName,streamID); if (multiplexerSession != null) { // Wrap packet so that the connection manager can figure out the target session final Element route = DocumentHelper.createElement("route"); route.addAttribute("from", serverName); route.addAttribute("to", connectionManagerName); route.addAttribute("streamid", streamID.getID()); route.addText(text); // Deliver the wrapped stanza multiplexerSession.deliverRawText(route.asXML()); } } @Override public Optional<String> getTLSProtocolName() { return Optional.of("unknown"); } @Override public Optional<String> getCipherSuiteName() { return Optional.of("unknown"); } @Override public ConnectionConfiguration getConfiguration() { // Here, a client-to-server configuration is mocked. It is likely not used, as actual connection handling takes // place at the connection manager. final ConnectionManager connectionManager = XMPPServer.getInstance().getConnectionManager(); return connectionManager.getListener( ConnectionType.SOCKET_C2S, true ).generateConnectionConfiguration(); } public byte[] getAddress() throws UnknownHostException { if (hostAddress != null) { return InetAddress.getByName(hostAddress).getAddress(); } return null; } @Override public String getHostAddress() throws UnknownHostException { if (hostAddress != null) { return hostAddress; } // Return IP address of the connection manager that the client used to log in ConnectionMultiplexerSession multiplexerSession = multiplexerManager.getMultiplexerSession(connectionManagerName); if (multiplexerSession != null) { return multiplexerSession.getHostAddress(); } return null; } @Override public String getHostName() throws UnknownHostException { if (hostName != null) { return hostName; } // Return IP address of the connection manager that the client used to log in ConnectionMultiplexerSession multiplexerSession = multiplexerManager.getMultiplexerSession(connectionManagerName); if (multiplexerSession != null) { return multiplexerSession.getHostName(); } return null; } @Override public void systemShutdown() { // Do nothing since a system-shutdown error will be sent to the Connection Manager // that in turn will send a system-shutdown to connected clients. This is an // optimization to reduce number of packets being sent from the server. } /** * If the Connection Manager or the Client requested to close the connection then just do * nothing. But if the server originated the request to close the connection then we need * to send to the Connection Manager a packet letting him know that the Client Session needs * to be terminated. * * @param error If non-null, this error will be sent to the peer before the connection is disconnected. */ @Override public void closeVirtualConnection(@Nullable final StreamError error) {<FILL_FUNCTION_BODY>} }
// Figure out who requested the connection to be closed StreamID streamID = session.getStreamID(); if (multiplexerManager.getClientSession(connectionManagerName, streamID) == null) { // Client or Connection manager requested to close the session // Do nothing since it has already been removed and closed } else { ConnectionMultiplexerSession multiplexerSession = multiplexerManager.getMultiplexerSession(connectionManagerName,streamID); if (multiplexerSession != null) { // Server requested to close the client session so let the connection manager // know that he has to finish the client session IQ closeRequest = new IQ(IQ.Type.set); closeRequest.setFrom(serverName); closeRequest.setTo(connectionManagerName); Element child = closeRequest.setChildElement("session", "http://jabber.org/protocol/connectionmanager"); child.addAttribute("id", streamID.getID()); child.addElement("close"); if (error != null) { // Note that this is ignored by all Connection Manager implementations at the time of writing. child.add(error.getElement()); } multiplexerSession.process(closeRequest); } }
1,523
316
1,839
<methods>public non-sealed void <init>() ,public void addCompression() ,public void close(StreamError, boolean) ,public abstract void closeVirtualConnection(StreamError) ,public java.security.cert.Certificate[] getLocalCertificates() ,public org.jivesoftware.openfire.PacketDeliverer getPacketDeliverer() ,public java.security.cert.Certificate[] getPeerCertificates() ,public boolean isClosed() ,public boolean isCompressed() ,public boolean isEncrypted() ,public boolean isInitialized() ,public boolean isSecure() ,public boolean isUsingSelfSignedCertificate() ,public void setUsingSelfSignedCertificate(boolean) ,public void startCompression() ,public void startTLS(boolean, boolean) throws java.lang.Exception,public boolean validate() <variables>private static final Logger Log,private final AtomicReference<org.jivesoftware.openfire.Connection.State> state
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/multiplex/MultiplexerPacketDeliverer.java
MultiplexerPacketDeliverer
deliver
class MultiplexerPacketDeliverer implements PacketDeliverer { private static final Logger Log = LoggerFactory.getLogger(MultiplexerPacketDeliverer.class); private OfflineMessageStrategy messageStrategy; private String connectionManagerDomain; private ConnectionMultiplexerManager multiplexerManager; public MultiplexerPacketDeliverer() { this.messageStrategy = XMPPServer.getInstance().getOfflineMessageStrategy(); multiplexerManager = ConnectionMultiplexerManager.getInstance(); } public void setConnectionManagerDomain(String connectionManagerDomain) { this.connectionManagerDomain = connectionManagerDomain; } @Override public void deliver(Packet packet) throws UnauthorizedException, PacketException {<FILL_FUNCTION_BODY>} private void handleUnprocessedPacket(Packet packet) { if (!NettyClientConnectionHandler.BACKUP_PACKET_DELIVERY_ENABLED.getValue()) { Log.trace("Discarding packet that was due to be delivered on closed connection {}, for which no other multiplex connections are available, and no client backup deliverer was configured.", this); return; } if (packet instanceof Message) { messageStrategy.storeOffline((Message) packet); } else if (packet instanceof Presence) { // presence packets are dropped silently //dropPacket(packet); } else if (packet instanceof IQ) { IQ iq = (IQ) packet; // Check if we need to unwrap the packet Element child = iq.getChildElement(); if (child != null && "session".equals(child.getName()) && "http://jabber.org/protocol/connectionmanager" .equals(child.getNamespacePrefix())) { Element send = child.element("send"); if (send != null) { // Unwrap packet Element wrappedElement = (Element) send.elements().get(0); if ("message".equals(wrappedElement.getName())) { handleUnprocessedPacket(new Message(wrappedElement)); } } } else { // IQ packets are logged but dropped Log.warn(LocaleUtils.getLocalizedString("admin.error.routing") + "\n" + packet.toString()); } } } }
// Check if we can send the packet using another session if (connectionManagerDomain == null) { // Packet deliverer has not yet been configured so handle unprocessed packet handleUnprocessedPacket(packet); } else { // Try getting another session to the same connection manager ConnectionMultiplexerSession session = multiplexerManager.getMultiplexerSession(connectionManagerDomain); if (session == null || session.isClosed()) { // No other session was found so handle unprocessed packet handleUnprocessedPacket(packet); } else { // Send the packet using this other session to the same connection manager session.process(packet); } }
593
184
777
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/multiplex/Route.java
Route
getChildElement
class Route extends Packet { /** * Constructs a new Route. * * @param streamID the stream ID that identifies the connection that is actually sending * the wrapped stanza. */ public Route(StreamID streamID) { this.element = docFactory.createDocument().addElement("route"); // Set the stream ID that identifies the target session element.addAttribute("streamid", streamID.getID()); } /** * Constructs a new Route using an existing Element. This is useful * for parsing incoming route Elements into Route objects. * * @param element the route Element. */ public Route(Element element) { super(element, true); } public Route(Route route) { Element elementCopy = route.element.createCopy(); docFactory.createDocument().add(elementCopy); this.element = elementCopy; // Copy cached JIDs (for performance reasons) this.toJID = route.toJID; this.fromJID = route.fromJID; } /** * Returns the wrapped stanza that is being routed. Route packets must have * a single wrapped stanza. This is a convenience method to avoid manipulating * the underlying packet's Element instance directly. * * @return the wrapped stanza. */ public Element getChildElement() {<FILL_FUNCTION_BODY>} /** * Sets the wrapped stanza by this Route packet. ClientRoute packets may have a single child * element. This is a convenience method to avoid manipulating this underlying packet's * Element instance directly. * * @param childElement the child element. */ public void setChildElement(Element childElement) { for (Iterator i=element.elementIterator(); i.hasNext(); ) { element.remove((Element)i.next()); } element.add(childElement); } /** * Return the stream ID that identifies the connection that is actually sending * the wrapped stanza. * * @return the stream ID that identifies the connection that is actually sending * the wrapped stanza. */ public StreamID getStreamID() { final String value = element.attributeValue( "streamid" ); if (value == null) { return null; } return BasicStreamIDFactory.createStreamID( value ); } /** * Returns a deep copy of this route packet. * * @return a deep copy of this route packet. */ @Override public Route createCopy() { return new Route(this); } }
List elements = element.elements(); if (elements.isEmpty()) { return null; } else { // Return the first child element return (Element) elements.get(0); }
676
56
732
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/AbstractConnection.java
AbstractConnection
notifyCloseListeners
class AbstractConnection implements Connection { private static final Logger Log = LoggerFactory.getLogger(AbstractConnection.class); /** * The major version of XMPP being used by this connection (major_version.minor_version). In most cases, the version * should be "1.0". However, older clients using the "Jabber" protocol do not set a version. In that case, the * version is "0.0". */ private int majorVersion = 1; /** * The minor version of XMPP being used by this connection (major_version.minor_version). In most cases, the version * should be "1.0". However, older clients using the "Jabber" protocol do not set a version. In that case, the * version is "0.0". */ private int minorVersion = 0; /** * When a connection is used to transmit an XML data, the root element of that data can define XML namespaces other * than the ones that are default (eg: 'jabber:client', 'jabber:server', etc). For an XML parser to be able to parse * stanzas or other elements that are defined in that namespace (eg: are prefixed), these namespaces are recorded * here. * * @see <a href="https://igniterealtime.atlassian.net/browse/OF-2556">Issue OF-2556</a> */ private final Set<Namespace> additionalNamespaces = new HashSet<>(); /** * Contains all registered listener for close event notification. Registrations after the Session is closed will be * immediately notified <em>before</em> the registration call returns (within the context of the registration call). * An optional handback object can be associated with the registration if the same listener is registered to listen * for multiple connection closures. */ final protected Map<ConnectionCloseListener, Object> closeListeners = new HashMap<>(); /** * The session that owns this connection. */ protected LocalSession session; @Override public void init(LocalSession owner) { session = owner; } @Override public void reinit(final LocalSession owner) { this.session = owner; // ConnectionCloseListeners are registered with their session instance as a callback object. When re-initializing, // this object needs to be replaced with the new session instance (or otherwise, the old session will be used // during the callback. OF-2014 closeListeners.entrySet().stream() .filter(entry -> entry.getValue() instanceof LocalSession) .forEach(entry -> entry.setValue(owner)); } /** * Returns the session that owns this connection, if the connection has been initialized. * * @return session that owns this connection. */ public LocalSession getSession() { // TODO is it needed to expose this publicly? This smells. return session; } @Override public int getMajorXMPPVersion() { return majorVersion; } @Override public int getMinorXMPPVersion() { return minorVersion; } @Override public void setXMPPVersion(int majorVersion, int minorVersion) { this.majorVersion = majorVersion; this.minorVersion = minorVersion; } @Override @Nonnull public Set<Namespace> getAdditionalNamespaces() { return additionalNamespaces; } @Override public void setAdditionalNamespaces(@Nonnull final Set<Namespace> additionalNamespaces) { this.additionalNamespaces.clear(); this.additionalNamespaces.addAll(additionalNamespaces); } @Override public void registerCloseListener(ConnectionCloseListener listener, Object callback) { if (isClosed()) { listener.onConnectionClose(callback); } else { closeListeners.put( listener, callback ); } } @Override public void removeCloseListener(ConnectionCloseListener listener) { closeListeners.remove( listener ); } /** * Notifies all close listeners that the connection has been closed. Used by subclasses to properly finish closing * the connection. */ protected void notifyCloseListeners() {<FILL_FUNCTION_BODY>} }
for( final Map.Entry<ConnectionCloseListener, Object> entry : closeListeners.entrySet() ) { if (entry.getKey() != null) { try { entry.getKey().onConnectionClose(entry.getValue()); } catch (Exception e) { Log.error("Error notifying listener: " + entry.getKey(), e); } } }
1,093
102
1,195
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/BlockingReadingMode.java
BlockingReadingMode
run
class BlockingReadingMode extends SocketReadingMode { private static final Logger Log = LoggerFactory.getLogger(BlockingReadingMode.class); public BlockingReadingMode(Socket socket, SocketReader socketReader) { super(socket, socketReader); } /** * A dedicated thread loop for reading the stream and sending incoming * packets to the appropriate router. */ @Override public void run() {<FILL_FUNCTION_BODY>} /** * Read the incoming stream until it ends. */ private void readStream() throws Exception { socketReader.open = true; while (socketReader.open) { Element doc = socketReader.reader.parseDocument().getRootElement(); if (doc == null) { // Stop reading the stream since the client has sent an end of // stream element and probably closed the connection. return; } String tag = doc.getName(); if ("starttls".equals(tag)) { // Negotiate TLS if (negotiateTLS()) { tlsNegotiated(); } else { socketReader.open = false; socketReader.session = null; } } else if ("auth".equals(tag)) { // User is trying to authenticate using SASL if (authenticateClient(doc)) { // SASL authentication was successful so open a new stream and offer // resource binding and session establishment (to client sessions only) saslSuccessful(); } else if (socketReader.connection.isClosed()) { socketReader.open = false; socketReader.session = null; } } else if ("error".equals(tag)) { try { final StreamError error = new StreamError( doc ); Log.info( "Peer '{}' sent a stream error: '{}'{}. Closing connection.", socketReader.session != null ? socketReader.session.getAddress() : "(unknown)", error.getCondition().toXMPP(), error.getText() != null ? " ('" + error.getText() +"')" : "" ); } catch ( Exception e ) { Log.debug( "An unexpected exception occurred while trying to parse a stream error.", e ); } finally { if ( socketReader.session != null ) { socketReader.session.close(); socketReader.session = null; } socketReader.open = false; } } else if ("compress".equals(tag)) { // Client is trying to initiate compression if (compressClient(doc)) { // Compression was successful so open a new stream and offer // resource binding and session establishment (to client sessions only) compressionSuccessful(); } } else { socketReader.process(doc); } } } @Override protected void tlsNegotiated() throws XmlPullParserException, IOException { XmlPullParser xpp = socketReader.reader.getXPPParser(); // Reset the parser to use the new reader xpp.setInput(new InputStreamReader( socketReader.connection.getTLSStreamHandler().getInputStream(), CHARSET)); // Skip new stream element for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) { eventType = xpp.next(); } super.tlsNegotiated(); } @Override protected void saslSuccessful() throws XmlPullParserException, IOException { MXParser xpp = socketReader.reader.getXPPParser(); // Reset the parser since a new stream header has been sent from the client xpp.resetInput(); // Skip the opening stream sent by the client for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) { eventType = xpp.next(); } super.saslSuccessful(); } @Override protected boolean compressClient(Element doc) throws XmlPullParserException, IOException { boolean answer = super.compressClient(doc); if (answer) { XmlPullParser xpp = socketReader.reader.getXPPParser(); // Reset the parser since a new stream header has been sent from the client if (socketReader.connection.getTLSStreamHandler() == null) { ZInputStream in = new ZInputStream( ServerTrafficCounter.wrapInputStream(socket.getInputStream())); in.setFlushMode(JZlib.Z_PARTIAL_FLUSH); xpp.setInput(new InputStreamReader(in, CHARSET)); } else { ZInputStream in = new ZInputStream( socketReader.connection.getTLSStreamHandler().getInputStream()); in.setFlushMode(JZlib.Z_PARTIAL_FLUSH); xpp.setInput(new InputStreamReader(in, CHARSET)); } } return answer; } @Override protected void compressionSuccessful() throws XmlPullParserException, IOException { XmlPullParser xpp = socketReader.reader.getXPPParser(); // Skip the opening stream sent by the client for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) { eventType = xpp.next(); } super.compressionSuccessful(); } }
try { final InputStream inputStream; if (socketReader.directTLS ) { inputStream = socketReader.connection.getTLSStreamHandler().getInputStream(); } else { inputStream = socket.getInputStream(); } socketReader.reader.getXPPParser().setInput(new InputStreamReader( ServerTrafficCounter.wrapInputStream(inputStream), CHARSET)); // Read in the opening tag and prepare for packet stream try { socketReader.createSession(); } catch (IOException e) { Log.debug("Error creating session", e); throw e; } // Read the packet stream until it ends if (socketReader.session != null) { readStream(); } } catch (EOFException eof) { // Normal disconnect } catch (SocketException se) { // The socket was closed. The server may close the connection for several // reasons (e.g. user requested to remove his account). Do nothing here. } catch (AsynchronousCloseException ace) { // The socket was closed. } catch (XmlPullParserException ie) { // It is normal for clients to abruptly cut a connection // rather than closing the stream document. Since this is // normal behavior, we won't log it as an error. // Log.error(LocaleUtils.getLocalizedString("admin.disconnect"),ie); } catch (Exception e) { if (socketReader.session != null) { Log.warn(LocaleUtils.getLocalizedString("admin.error.stream") + ". Session: " + socketReader.session, e); } } finally { if (socketReader.session != null) { if (Log.isDebugEnabled()) { Log.debug("Logging off " + socketReader.session.getAddress() + " on " + socketReader.connection); } try { Log.debug( "Closing session: {}", socketReader.session ); socketReader.session.close(); } catch (Exception e) { Log.warn(LocaleUtils.getLocalizedString("admin.error.connection") + socket.toString()); } } else { // Close and release the created connection socketReader.connection.close(); Log.debug(LocaleUtils.getLocalizedString("admin.error.connection") + socket.toString()); } socketReader.shutdown(); }
1,371
624
1,995
<methods><variables>protected static java.lang.String CHARSET,private static final Logger Log,protected java.net.Socket socket,protected org.jivesoftware.openfire.net.SocketReader socketReader
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/ClientStanzaHandler.java
ClientStanzaHandler
processUnknowPacket
class ClientStanzaHandler extends StanzaHandler { private static final Logger Log = LoggerFactory.getLogger(ClientStanzaHandler.class); public ClientStanzaHandler(PacketRouter router, Connection connection) { super(router, connection); } @Override protected boolean processUnknowPacket(Element doc) {<FILL_FUNCTION_BODY>} @Override protected Namespace getNamespace() { return new Namespace("", "jabber:client"); } @Override protected boolean validateHost() { return JiveGlobals.getBooleanProperty("xmpp.client.validate.host",false); } @Override protected boolean validateJIDs() { return true; } @Override protected void createSession(String serverName, XmlPullParser xpp, Connection connection) throws XmlPullParserException { // The connected client is a regular client so create a ClientSession session = LocalClientSession.createSession(serverName, xpp, connection); } @Override protected void processIQ(IQ packet) throws UnauthorizedException { // Overwrite the FROM attribute to avoid spoofing packet.setFrom(session.getAddress()); super.processIQ(packet); } @Override protected void processPresence(Presence packet) throws UnauthorizedException { // Overwrite the FROM attribute to avoid spoofing packet.setFrom(session.getAddress()); super.processPresence(packet); } @Override protected void processMessage(Message packet) throws UnauthorizedException { // Overwrite the FROM attribute to avoid spoofing packet.setFrom(session.getAddress()); super.processMessage(packet); } @Override protected void startTLS() throws Exception { connection.startTLS(false, false); } }
if (CsiManager.isStreamManagementNonza(doc)) { Log.trace("Client is sending client state indication nonza."); ((LocalClientSession) session).getCsiManager().process(doc); return true; } return false;
485
66
551
<methods>public void <init>(org.jivesoftware.openfire.PacketRouter, org.jivesoftware.openfire.Connection) ,public JID getAddress() ,public void process(java.lang.String, org.dom4j.io.XMPPPacketReader) throws java.lang.Exception,public void setSession(org.jivesoftware.openfire.session.LocalSession) <variables>private static final Logger Log,public static final SystemProperty<java.lang.Boolean> PROPERTY_OVERWRITE_EMPTY_TO,private static final org.jivesoftware.openfire.StreamIDFactory STREAM_ID_FACTORY,protected org.jivesoftware.openfire.Connection connection,protected org.jivesoftware.openfire.PacketRouter router,protected org.jivesoftware.openfire.net.SASLAuthentication.Status saslStatus,protected org.jivesoftware.openfire.session.LocalSession session,protected boolean sessionCreated,protected boolean startedSASL,protected boolean startedTLS,protected boolean waitingCompressionACK
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/ComponentStanzaHandler.java
ComponentStanzaHandler
processUnknowPacket
class ComponentStanzaHandler extends StanzaHandler { private static final Logger Log = LoggerFactory.getLogger(ComponentStanzaHandler.class); public ComponentStanzaHandler(PacketRouter router, Connection connection) { super(router, connection); } @Override boolean processUnknowPacket(Element doc) throws UnauthorizedException {<FILL_FUNCTION_BODY>} @Override protected void processIQ(IQ packet) throws UnauthorizedException { if (!session.isAuthenticated()) { // Session is not authenticated so return error IQ reply = new IQ(); reply.setChildElement(packet.getChildElement().createCopy()); reply.setID(packet.getID()); reply.setTo(packet.getFrom()); reply.setFrom(packet.getTo()); reply.setError(PacketError.Condition.not_authorized); session.process(reply); return; } // Keep track of the component that sent an IQ get/set if (packet.getType() == IQ.Type.get || packet.getType() == IQ.Type.set) { // Handle subsequent bind packets LocalComponentSession componentSession = (LocalComponentSession) session; // Get the external component of this session LocalComponentSession.LocalExternalComponent component = (LocalComponentSession.LocalExternalComponent) componentSession.getExternalComponent(); component.track(packet); } super.processIQ(packet); } @Override protected void processPresence(Presence packet) throws UnauthorizedException { if (!session.isAuthenticated()) { // Session is not authenticated so return error Presence reply = new Presence(); reply.setID(packet.getID()); reply.setTo(packet.getFrom()); reply.setFrom(packet.getTo()); reply.setError(PacketError.Condition.not_authorized); session.process(reply); return; } super.processPresence(packet); } @Override protected void processMessage(Message packet) throws UnauthorizedException { if (!session.isAuthenticated()) { // Session is not authenticated so return error Message reply = new Message(); reply.setID(packet.getID()); reply.setTo(packet.getFrom()); reply.setFrom(packet.getTo()); reply.setError(PacketError.Condition.not_authorized); session.process(reply); return; } super.processMessage(packet); } @Override void startTLS() throws Exception { connection.startTLS(false, false); } @Override Namespace getNamespace() { return new Namespace("", "jabber:component:accept"); } @Override boolean validateHost() { return false; } @Override boolean validateJIDs() { return false; } @Override void createSession(String serverName, XmlPullParser xpp, Connection connection) throws XmlPullParserException { // The connected client is a connection manager so create a ConnectionMultiplexerSession session = LocalComponentSession.createSession(serverName, xpp, connection); } }
String tag = doc.getName(); if ("handshake".equals(tag)) { // External component is trying to authenticate if (!((LocalComponentSession) session).authenticate(doc.getStringValue())) { Log.debug( "Closing session that failed to authenticate: {}", session ); session.close(); } return true; } else if ("error".equals(tag) && "stream".equals(doc.getNamespacePrefix())) { Log.debug( "Closing session because of received stream error {}. Affected session: {}", doc.asXML(), session ); session.close(); return true; } else if ("bind".equals(tag)) { // Handle subsequent bind packets LocalComponentSession componentSession = (LocalComponentSession) session; // Get the external component of this session ComponentSession.ExternalComponent component = componentSession.getExternalComponent(); String initialDomain = component.getInitialSubdomain(); String extraDomain = doc.attributeValue("name"); String allowMultiple = doc.attributeValue("allowMultiple"); if (extraDomain == null || "".equals(extraDomain)) { // No new bind domain was specified so return a bad_request error Element reply = doc.createCopy(); reply.add(new PacketError(PacketError.Condition.bad_request).getElement()); connection.deliverRawText(reply.asXML()); } else if (extraDomain.equals(initialDomain)) { // Component is binding initial domain that is already registered // Send confirmation that the new domain has been registered connection.deliverRawText("<bind/>"); } else if (extraDomain.endsWith(initialDomain)) { // Only accept subdomains under the initial registered domain if (allowMultiple != null && component.getSubdomains().contains(extraDomain)) { // Domain already in use so return a conflict error Element reply = doc.createCopy(); reply.add(new PacketError(PacketError.Condition.conflict).getElement()); connection.deliverRawText(reply.asXML()); } else { try { // Get the requested subdomain final String subdomain; int index = extraDomain.indexOf( XMPPServer.getInstance().getServerInfo().getXMPPDomain() ); if (index > -1) { subdomain = extraDomain.substring(0, index -1); } else { subdomain = extraDomain; } InternalComponentManager.getInstance().addComponent(subdomain, component); componentSession.getConnection().registerCloseListener( handback -> InternalComponentManager.getInstance().removeComponent( subdomain, (ComponentSession.ExternalComponent) handback ), component ); // Send confirmation that the new domain has been registered connection.deliverRawText("<bind/>"); } catch (ComponentException e) { Log.error("Error binding extra domain: " + extraDomain + " to component: " + component, e); // Return internal server error Element reply = doc.createCopy(); reply.add(new PacketError( PacketError.Condition.internal_server_error).getElement()); connection.deliverRawText(reply.asXML()); } } } else { // Return forbidden error since we only allow subdomains of the intial domain // to be used by the same external component Element reply = doc.createCopy(); reply.add(new PacketError(PacketError.Condition.forbidden).getElement()); connection.deliverRawText(reply.asXML()); } return true; } return false;
850
897
1,747
<methods>public void <init>(org.jivesoftware.openfire.PacketRouter, org.jivesoftware.openfire.Connection) ,public JID getAddress() ,public void process(java.lang.String, org.dom4j.io.XMPPPacketReader) throws java.lang.Exception,public void setSession(org.jivesoftware.openfire.session.LocalSession) <variables>private static final Logger Log,public static final SystemProperty<java.lang.Boolean> PROPERTY_OVERWRITE_EMPTY_TO,private static final org.jivesoftware.openfire.StreamIDFactory STREAM_ID_FACTORY,protected org.jivesoftware.openfire.Connection connection,protected org.jivesoftware.openfire.PacketRouter router,protected org.jivesoftware.openfire.net.SASLAuthentication.Status saslStatus,protected org.jivesoftware.openfire.session.LocalSession session,protected boolean sessionCreated,protected boolean startedSASL,protected boolean startedTLS,protected boolean waitingCompressionACK
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/MulticastDNSService.java
MulticastDNSService
run
class MulticastDNSService extends BasicModule { private static final Logger Log = LoggerFactory.getLogger(MulticastDNSService.class); private JmDNS jmdns; public MulticastDNSService() { super("Multicast DNS Service"); PropertyEventDispatcher.addListener(new PropertyEventListener() { @Override public void propertySet(String property, Map params) { // Restart the service if component settings changes. if (property.equals("xmpp.component.socket.active") || property.equals(" xmpp.component.socket.port")) { stop(); start(); } } @Override public void propertyDeleted(String property, Map params) { // Restart the service if component settings changes. if (property.equals("xmpp.component.socket.active") || property.equals(" xmpp.component.socket.port")) { stop(); start(); } } @Override public void xmlPropertySet(String property, Map params) { } @Override public void xmlPropertyDeleted(String property, Map params) { } }); } @Override public void initialize(XMPPServer server) { } @Override public void start() throws IllegalStateException { // If the service isn't enabled, return. if (!JiveGlobals.getBooleanProperty("multicastDNS.enabled", false) ) { return; } TimerTask startService = new TimerTask() { @Override public void run() {<FILL_FUNCTION_BODY>} }; // Schedule the task to run in 5 seconds, to give Openfire time to start the ports. TaskEngine.getInstance().schedule(startService, Duration.ofSeconds(5)); } @Override public void stop() { if (jmdns != null) { try { jmdns.close(); } catch (Exception e) { // Ignore. } } } @Override public void destroy() { if (jmdns != null) { jmdns = null; } } }
int clientPortNum = -1; int componentPortNum = -1; final ConnectionManager connectionManager = XMPPServer.getInstance().getConnectionManager(); if ( connectionManager != null ) { clientPortNum = connectionManager.getPort( ConnectionType.SOCKET_C2S, false ); componentPortNum = connectionManager.getPort( ConnectionType.COMPONENT, false); } try { if (jmdns == null) { jmdns = new JmDNS(); } String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); if (clientPortNum != -1) { ServiceInfo clientService = new ServiceInfo("_xmpp-client._tcp.local.", serverName + "._xmpp-client._tcp.local.", clientPortNum, "XMPP Server"); jmdns.registerService(clientService); } if (componentPortNum != -1) { ServiceInfo componentService = new ServiceInfo("_xmpp-component._tcp.local.", serverName + "._xmpp-component._tcp.local.", componentPortNum, "XMPP Component Server"); jmdns.registerService(componentService); } } catch (IOException ioe) { Log.error(ioe.getMessage(), ioe); }
589
342
931
<methods>public void <init>(java.lang.String) ,public void destroy() ,public java.lang.String getName() ,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public void start() throws java.lang.IllegalStateException,public void stop() <variables>private java.lang.String name
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/MultiplexerStanzaHandler.java
MultiplexerStanzaHandler
processIQ
class MultiplexerStanzaHandler extends StanzaHandler { private static final Logger Log = LoggerFactory.getLogger( MultiplexerStanzaHandler.class ); /** * Handler of IQ packets sent from the Connection Manager to the server. */ private MultiplexerPacketHandler packetHandler; public MultiplexerStanzaHandler(PacketRouter router, Connection connection) { super(router, connection); } @Override protected void processIQ(final IQ packet) {<FILL_FUNCTION_BODY>} @Override protected void processMessage(final Message packet) throws UnauthorizedException { throw new UnauthorizedException("Message packets are not supported. Original packets " + "should be wrapped by route packets."); } @Override protected void processPresence(final Presence packet) throws UnauthorizedException { throw new UnauthorizedException("Message packets are not supported. Original packets " + "should be wrapped by route packets."); } /** * Process stanza sent by a client that is connected to a connection manager. The * original stanza is wrapped in the route element. Only a single stanza must be * wrapped in the route element. * * @param packet the route element. */ private void processRoute(final Route packet) { if (!session.isAuthenticated()) { // Session is not authenticated so return error Route reply = new Route(packet.getStreamID()); reply.setID(packet.getID()); reply.setTo(packet.getFrom()); reply.setFrom(packet.getTo()); reply.setError(PacketError.Condition.not_authorized); session.process(reply); return; } // Process the packet packetHandler.route(packet); } @Override boolean processUnknowPacket(Element doc) { String tag = doc.getName(); if ("route".equals(tag)) { // Process stanza wrapped by the route packet processRoute(new Route(doc)); return true; } else if ("handshake".equals(tag)) { if (!((LocalConnectionMultiplexerSession) session).authenticate(doc.getStringValue())) { Log.debug( "Closing session that failed to authenticate: {}", session ); session.close(); } return true; } else if ("error".equals(tag) && "stream".equals(doc.getNamespacePrefix())) { Log.debug( "Closing session because of received stream error {}. Affected session: {}", doc.asXML(), session ); session.close(); return true; } return false; } @Override Namespace getNamespace() { return new Namespace("", "jabber:connectionmanager"); } @Override boolean validateHost() { return false; } @Override boolean validateJIDs() { return false; } @Override void createSession(String serverName, XmlPullParser xpp, Connection connection) throws XmlPullParserException { // The connected client is a connection manager so create a ConnectionMultiplexerSession session = LocalConnectionMultiplexerSession.createSession(serverName, xpp, connection); if (session != null) { packetHandler = new MultiplexerPacketHandler(session.getAddress().getDomain()); } } @Override void startTLS() throws Exception { connection.startTLS(false, false); } }
if (!session.isAuthenticated()) { // Session is not authenticated so return error IQ reply = new IQ(); reply.setChildElement(packet.getChildElement().createCopy()); reply.setID(packet.getID()); reply.setTo(packet.getFrom()); reply.setFrom(packet.getTo()); reply.setError(PacketError.Condition.not_authorized); session.process(reply); return; } // Process the packet packetHandler.handle(packet);
908
143
1,051
<methods>public void <init>(org.jivesoftware.openfire.PacketRouter, org.jivesoftware.openfire.Connection) ,public JID getAddress() ,public void process(java.lang.String, org.dom4j.io.XMPPPacketReader) throws java.lang.Exception,public void setSession(org.jivesoftware.openfire.session.LocalSession) <variables>private static final Logger Log,public static final SystemProperty<java.lang.Boolean> PROPERTY_OVERWRITE_EMPTY_TO,private static final org.jivesoftware.openfire.StreamIDFactory STREAM_ID_FACTORY,protected org.jivesoftware.openfire.Connection connection,protected org.jivesoftware.openfire.PacketRouter router,protected org.jivesoftware.openfire.net.SASLAuthentication.Status saslStatus,protected org.jivesoftware.openfire.session.LocalSession session,protected boolean sessionCreated,protected boolean startedSASL,protected boolean startedTLS,protected boolean waitingCompressionACK
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/ServerTrustManager.java
ServerTrustManager
getAcceptedIssuers
class ServerTrustManager implements X509TrustManager { private static final Logger Log = LoggerFactory.getLogger(ServerTrustManager.class); /** * KeyStore that holds the trusted CA */ private KeyStore trustStore; public ServerTrustManager(KeyStore trustTrust) { super(); this.trustStore = trustTrust; } @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String string) { // Do not validate the certificate at this point. The certificate is going to be used // when the remote server requests to do EXTERNAL SASL } /** * Given the partial or complete certificate chain provided by the peer, build a certificate * path to a trusted root and return if it can be validated and is trusted for server SSL * authentication based on the authentication type. The authentication type is the key * exchange algorithm portion of the cipher suites represented as a String, such as "RSA", * "DHE_DSS". Note: for some exportable cipher suites, the key exchange algorithm is * determined at run time during the handshake. For instance, for * TLS_RSA_EXPORT_WITH_RC4_40_MD5, the authType should be RSA_EXPORT when an ephemeral * RSA key is used for the key exchange, and RSA when the key from the server certificate * is used. Checking is case-sensitive.<p> * * By default certificates are going to be verified. This includes verifying the certificate * chain, the root certificate and the certificates validity. However, it is possible to * disable certificates validation as a whole or each specific validation. * * @param x509Certificates an ordered array of peer X.509 certificates with the peer's own * certificate listed first and followed by any certificate authorities. * @param string the key exchange algorithm used. * @throws CertificateException if the certificate chain is not trusted by this TrustManager. */ @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String string) throws CertificateException { // Do nothing here. As before, the certificate will be validated when the remote server authenticates. } @Override public X509Certificate[] getAcceptedIssuers() {<FILL_FUNCTION_BODY>} }
if (JiveGlobals.getBooleanProperty(ConnectionSettings.Server.TLS_ACCEPT_SELFSIGNED_CERTS, false)) { // Answer an empty list since we accept any issuer return new X509Certificate[0]; } else { X509Certificate[] X509Certs = null; try { // See how many certificates are in the keystore. int numberOfEntry = trustStore.size(); // If there are any certificates in the keystore. if (numberOfEntry > 0) { // Create an array of X509Certificates X509Certs = new X509Certificate[numberOfEntry]; // Get all of the certificate alias out of the keystore. Enumeration aliases = trustStore.aliases(); // Retrieve all of the certificates out of the keystore // via the alias name. int i = 0; while (aliases.hasMoreElements()) { X509Certs[i] = (X509Certificate) trustStore. getCertificate((String) aliases.nextElement()); i++; } } } catch (Exception e) { Log.error(e.getMessage(), e); X509Certs = null; } return X509Certs; }
613
360
973
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/SocketPacketWriteHandler.java
SocketPacketWriteHandler
process
class SocketPacketWriteHandler implements ChannelHandler { private static final Logger Log = LoggerFactory.getLogger(SocketPacketWriteHandler.class); private XMPPServer server; private RoutingTable routingTable; public SocketPacketWriteHandler(RoutingTable routingTable) { this.routingTable = routingTable; this.server = XMPPServer.getInstance(); } @Override public void process(Packet packet) throws UnauthorizedException, PacketException {<FILL_FUNCTION_BODY>} }
try { JID recipient = packet.getTo(); // Check if the target domain belongs to a remote server or a component if (server.matchesComponent(recipient) || server.isRemote(recipient)) { routingTable.routePacket(recipient, packet); } // The target domain belongs to the local server else if (recipient == null || (recipient.getNode() == null && recipient.getResource() == null)) { // no TO was found so send back the packet to the sender routingTable.routePacket(packet.getFrom(), packet); } else if (recipient.getResource() != null || !(packet instanceof Presence)) { // JID is of the form <user@domain/resource> routingTable.routePacket(recipient, packet); } else { // JID is of the form <user@domain> for (JID route : routingTable.getRoutes(recipient, null)) { routingTable.routePacket(route, packet); } } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error.deliver") + "\n" + packet.toString(), e); }
140
320
460
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/SocketUtil.java
SocketUtil
createSocketToXmppDomain
class SocketUtil { private final static Logger Log = LoggerFactory.getLogger( SocketUtil.class ); /** * Creates a socket connection to an XMPP domain. * * This implementation uses DNS SRV records to find a list of remote hosts for the XMPP domain (as implemented by * {@link DNSUtil#resolveXMPPDomain(String, int)}. It then iteratively tries to create a socket connection to each * of them, until one socket connection succeeds. * * Either the connected Socket instance is returned, or null if no connection could be established. * * Note that this method blocks while performing network IO. The timeout as defined by * {@link RemoteServerManager#getSocketTimeout()} is observed. * * @param xmppDomain The XMPP domain to connect to. * @param port The port to connect to when DNS resolution fails. * @return a Socket instance that is connected, or null. * @see DNSUtil#resolveXMPPDomain(String, int) */ public static Map.Entry<Socket, Boolean> createSocketToXmppDomain( String xmppDomain, int port ) {<FILL_FUNCTION_BODY>} }
Log.debug( "Creating a socket connection to XMPP domain '{}' ...", xmppDomain ); Log.debug( "Use DNS to resolve remote hosts for the provided XMPP domain '{}' (default port: {}) ...", xmppDomain, port ); final List<DNSUtil.HostAddress> remoteHosts = DNSUtil.resolveXMPPDomain( xmppDomain, port ); Log.debug( "Found {} host(s) for XMPP domain '{}'.", remoteHosts.size(), xmppDomain ); remoteHosts.forEach( remoteHost -> Log.debug( "- {} ({})", remoteHost.toString(), (remoteHost.isDirectTLS() ? "direct TLS" : "no direct TLS" ) ) ); Socket socket = null; final int socketTimeout = RemoteServerManager.getSocketTimeout(); for ( DNSUtil.HostAddress remoteHost : remoteHosts ) { final String realHostname = remoteHost.getHost(); final int realPort = remoteHost.getPort(); final boolean directTLS = remoteHost.isDirectTLS(); if (!JiveGlobals.getBooleanProperty(ConnectionSettings.Server.ENABLE_OLD_SSLPORT, true) && directTLS) { Log.debug("Skipping directTLS host, as we're ourselves not accepting directTLS S2S"); continue; } if (!JiveGlobals.getBooleanProperty(ConnectionSettings.Server.SOCKET_ACTIVE, true) && !directTLS) { Log.debug("Skipping non direct TLS host, as we're ourselves not accepting non direct S2S"); continue; } try { // (re)initialize the socket. socket = new Socket(); Log.debug( "Trying to create socket connection to XMPP domain '{}' using remote host: {}:{} (blocks up to {} ms) ...", xmppDomain, realHostname, realPort, socketTimeout ); socket.connect( new InetSocketAddress( realHostname, realPort ), socketTimeout ); Log.debug( "Successfully created socket connection to XMPP domain '{}' using remote host: {}:{}!", xmppDomain, realHostname, realPort ); return new AbstractMap.SimpleEntry<>(socket, directTLS); } catch ( Exception e ) { Log.debug( "An exception occurred while trying to create a socket connection to XMPP domain '{}' using remote host {}:{}", xmppDomain, realHostname, realPort, e ); Log.warn( "Unable to create a socket connection to XMPP domain '{}' using remote host: {}:{}. Cause: {} (a full stacktrace is logged on debug level)", xmppDomain, realHostname, realPort, e.getMessage() ); try { if ( socket != null ) { socket.close(); socket = null; } } catch ( IOException ex ) { Log.debug( "An additional exception occurred while trying to close a socket when creating a connection to {}:{} failed.", realHostname, realPort, ex ); } } } Log.warn( "Unable to create a socket connection to XMPP domain '{}': Unable to connect to any of its remote hosts.", xmppDomain ); return null;
303
826
1,129
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/TLSStreamReader.java
TLSStreamReader
doRead
class TLSStreamReader { /** * <code>TLSWrapper</code> is a TLS wrapper for connections requiring TLS protocol. */ private TLSWrapper wrapper; private ReadableByteChannel rbc; /** * <code>inNetBB</code> buffer keeps data read from socket. */ private ByteBuffer inNetBB; /** * <code>inAppBB</code> buffer keeps decypted data. */ private ByteBuffer inAppBB; private TLSStatus lastStatus; public TLSStreamReader(TLSWrapper tlsWrapper, Socket socket) throws IOException { wrapper = tlsWrapper; // DANIELE: Add code to use directly the socket channel if (socket.getChannel() != null) { rbc = ServerTrafficCounter.wrapReadableChannel(socket.getChannel()); } else { rbc = Channels.newChannel( ServerTrafficCounter.wrapInputStream(socket.getInputStream())); } inNetBB = ByteBuffer.allocate(wrapper.getNetBuffSize()); inAppBB = ByteBuffer.allocate(wrapper.getAppBuffSize()); } /* * Read TLS encrpyted data from SocketChannel, and use <code>decrypt</code> method to decypt. */ private void doRead() throws IOException {<FILL_FUNCTION_BODY>} /* * This method uses <code>TLSWrapper</code> to decrypt TLS encrypted data. */ private ByteBuffer decrypt(ByteBuffer input, ByteBuffer output) throws IOException { ByteBuffer out = output; input.flip(); do { // Decode TLS network data and place it in the app buffer out = wrapper.unwrap(input, out); lastStatus = wrapper.getStatus(); } while ((lastStatus == TLSStatus.NEED_READ || lastStatus == TLSStatus.OK) && input.hasRemaining()); if (input.hasRemaining()) { // Complete TLS packets have been read, decrypted and written to the output buffer. // However, the input buffer contains incomplete TLS packets that cannot be decrpted. // Discard the read data and keep the unread data in the input buffer. The channel will // be read again to obtain the missing data to complete the TLS packet. So in the next // round the TLS packet will be decrypted and written to the output buffer input.compact(); } else { // All the encrypted data in the inpu buffer was decrypted so we can clear // the input buffer. input.clear(); } return out; } public InputStream getInputStream() { return createInputStream(); } /* * Returns an input stream for a ByteBuffer. The read() methods use the relative ByteBuffer * get() methods. */ private InputStream createInputStream() { return new InputStream() { @Override public synchronized int read() throws IOException { doRead(); if (!inAppBB.hasRemaining()) { return -1; } return inAppBB.get(); } @Override public synchronized int read(byte[] bytes, int off, int len) throws IOException { // Check if in the previous read the inAppBB ByteBuffer remained with unread data. // If all the data was consumed then read from the socket channel. Otherwise, // consume the data contained in the buffer. if (inAppBB.position() == 0) { // Read from the channel the encrypted data, decrypt it and load it // into inAppBB doRead(); } else { //System.out.println("#createInputStream. Detected previously unread data. position: " + inAppBB.position()); // The inAppBB contains data from a previous read so set the position to 0 // to consume it inAppBB.flip(); } len = Math.min(len, inAppBB.remaining()); if (len == 0) { // Nothing was read so the end of stream should have been reached. return -1; } inAppBB.get(bytes, off, len); // If the requested length is less than the limit of inAppBB then all the data // inside inAppBB was not read. In that case we need to discard the read data and // keep only the unread data to be consume the next time this method is called if (inAppBB.hasRemaining()) { // Discard read data and move unread data to the begining of the buffer. Leave // the position at the end of the buffer as a way to indicate that there is // unread data inAppBB.compact(); //System.out.println("#createInputStream. Data left unread. inAppBB compacted. position: " + inAppBB.position() + " limit: " + inAppBB.limit()); } else { // Everything was read so reset the buffer inAppBB.clear(); } return len; } }; } }
//System.out.println("doRead inNet position: " + inNetBB.position() + " capacity: " + inNetBB.capacity() + " (before read)"); // Read from the channel and fill inNetBB with the encrypted data final int cnt = rbc.read(inNetBB); if (cnt > 0) { //System.out.println("doRead inNet position: " + inNetBB.position() + " capacity: " + inNetBB.capacity() + " (after read)"); //System.out.println("doRead inAppBB (before decrypt) position: " + inAppBB.position() + " limit: " + inAppBB.limit() + " capacity: " + inAppBB.capacity()); // Decode encrypted data inAppBB = decrypt(inNetBB, inAppBB); ///System.out.println("doRead inAppBB (after decrypt) position: " + inAppBB.position() + " limit: " + inAppBB.limit() + " capacity: " + inAppBB.capacity() + " lastStatus: " + lastStatus); if (lastStatus == TLSStatus.OK) { // All the data contained in inNetBB was read and decrypted so we can safely // set the position of inAppBB to 0 to process it. inAppBB.flip(); } else { // Some data in inNetBB was not decrypted since it is not complete. A // bufferunderflow was detected since the TLS packet is not complete to be // decrypted. We need to read more data from the channel to decrypt the whole // TLS packet. The inNetBB byte buffer has been compacted so the read and // decrypted is discarded and only the unread and encrypted data is left in the // buffer. The inAppBB has been completed with the decrypted data and we must // leave the position at the end of the written so that in the next doRead the // decrypted data is appended to the end of the buffer. //System.out.println("Reading more data from the channel (UNDERFLOW state)"); doRead(); } } else { if (cnt == -1) { inAppBB.flip(); rbc.close(); } }
1,280
568
1,848
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/TLSStreamWriter.java
TLSStreamWriter
resizeApplicationBuffer
class TLSStreamWriter { /** * <code>TLSWrapper</code> is a TLS wrapper for connections requiring TLS protocol. */ private TLSWrapper wrapper; private WritableByteChannel wbc; private ByteBuffer outAppData; public TLSStreamWriter(TLSWrapper tlsWrapper, Socket socket) throws IOException { wrapper = tlsWrapper; // DANIELE: Add code to use directly the socket channel if (socket.getChannel() != null) { wbc = ServerTrafficCounter.wrapWritableChannel(socket.getChannel()); } else { wbc = Channels.newChannel( ServerTrafficCounter.wrapOutputStream(socket.getOutputStream())); } outAppData = ByteBuffer.allocate(tlsWrapper.getAppBuffSize()); } private void doWrite(ByteBuffer buff) throws IOException { if (buff == null) { // Possibly handshaking process buff = ByteBuffer.allocate(0); } if (wrapper == null) { writeToSocket(buff); } else { tlsWrite(buff); } } private void tlsWrite(ByteBuffer buf) throws IOException { ByteBuffer tlsBuffer; ByteBuffer tlsOutput; do { // TODO Consider optimizing by not creating new instances each time tlsBuffer = ByteBuffer.allocate(Math.min(buf.remaining(), wrapper.getAppBuffSize())); tlsOutput = ByteBuffer.allocate(wrapper.getNetBuffSize()); while (tlsBuffer.hasRemaining() && buf.hasRemaining()) { tlsBuffer.put(buf.get()); } tlsBuffer.flip(); wrapper.wrap(tlsBuffer, tlsOutput); tlsOutput.flip(); writeToSocket(tlsOutput); tlsOutput.clear(); } while (buf.hasRemaining()); } /* * Writes outNetData to the SocketChannel. <P> Returns true when the ByteBuffer has no remaining * data. */ private boolean writeToSocket(ByteBuffer outNetData) throws IOException { wbc.write(outNetData); return !outNetData.hasRemaining(); } public OutputStream getOutputStream() { return createOutputStream(); } /* * Returns an output stream for a ByteBuffer. The write() methods use the relative ByteBuffer * put() methods. */ private OutputStream createOutputStream() { return new OutputStream() { @Override public synchronized void write(int b) throws IOException { outAppData.put((byte) b); outAppData.flip(); doWrite(outAppData); outAppData.clear(); } @Override public synchronized void write(byte[] bytes, int off, int len) throws IOException { outAppData = resizeApplicationBuffer(bytes.length); outAppData.put(bytes, off, len); outAppData.flip(); doWrite(outAppData); outAppData.clear(); } }; } private ByteBuffer resizeApplicationBuffer(int increment) {<FILL_FUNCTION_BODY>} }
// TODO Creating new buffers and copying over old one may not scale. Consider using views. Thanks to Noah for the tip. if (outAppData.remaining() < increment) { ByteBuffer bb = ByteBuffer.allocate(outAppData.capacity() + wrapper.getAppBuffSize()); outAppData.flip(); bb.put(outAppData); return bb; } else { return outAppData; }
827
117
944
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/VirtualConnection.java
VirtualConnection
close
class VirtualConnection extends AbstractConnection { private static final Logger Log = LoggerFactory.getLogger(VirtualConnection.class); private final AtomicReference<State> state = new AtomicReference<State>(State.OPEN); @Override public Certificate[] getLocalCertificates() { // Ignore return new Certificate[0]; } @Override public Certificate[] getPeerCertificates() { // Ignore return new Certificate[0]; } @Override public void setUsingSelfSignedCertificate(boolean isSelfSigned) { } @Override public boolean isUsingSelfSignedCertificate() { return false; } @Override public boolean isClosed() { return state.get() == State.CLOSED; } @Override public boolean isCompressed() { // Return false since compression is not used for virtual connections return false; } @Override @Nullable public PacketDeliverer getPacketDeliverer() { //Ignore return null; } public void startTLS(boolean clientMode, boolean directTLS) throws Exception { //Ignore } public void addCompression() { //Ignore } @Override public void startCompression() { //Ignore } @Override @Deprecated // Remove in Openfire 4.9 or later. public boolean isSecure() { return isEncrypted(); } @Override public boolean isEncrypted() { // Return false since TLS is not used for virtual connections return false; } @Override public boolean validate() { // Return true since the virtual connection is valid until it no longer exists return true; } @Override public boolean isInitialized() { return session != null && !isClosed(); } /** * Closes the session, the virtual connection and notifies listeners that the connection * has been closed. * * @param error If non-null, the end-stream tag will be preceded with this error. */ @Override public void close(@Nullable final StreamError error, final boolean networkInterruption) {<FILL_FUNCTION_BODY>} /** * Closes the virtual connection. Subclasses should indicate what closing a virtual * connection means. At this point the session has a CLOSED state. * * @param error If non-null, this error will be sent to the peer before the connection is disconnected. */ public abstract void closeVirtualConnection(@Nullable final StreamError error); }
if (state.compareAndSet(State.OPEN, State.CLOSED)) { if (session != null) { if (!networkInterruption) { // A 'clean' closure should never be resumed (see #onRemoteDisconnect for handling of unclean disconnects). OF-2752 session.getStreamManager().formalClose(); } session.setStatus(Session.Status.CLOSED); } // See OF-1596 // The notification will trigger some shutdown procedures that, amongst other things, // check what type of session (eg: anonymous) is being closed. This check depends on the // session still being available. // // For that reason, it's important to first notify the listeners, and then close the // session - not the other way around. // // This fixes a very visible bug where MUC users would remain in the MUC room long after // their session was closed. Effectively, the bug prevents the MUC room from getting a // presence update to notify it that the user logged off. notifyCloseListeners(); closeListeners.clear(); try { closeVirtualConnection(error); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error.close") + "\n" + toString(), e); } }
672
339
1,011
<methods>public non-sealed void <init>() ,public Set<Namespace> getAdditionalNamespaces() ,public int getMajorXMPPVersion() ,public int getMinorXMPPVersion() ,public org.jivesoftware.openfire.session.LocalSession getSession() ,public void init(org.jivesoftware.openfire.session.LocalSession) ,public void registerCloseListener(org.jivesoftware.openfire.ConnectionCloseListener, java.lang.Object) ,public void reinit(org.jivesoftware.openfire.session.LocalSession) ,public void removeCloseListener(org.jivesoftware.openfire.ConnectionCloseListener) ,public void setAdditionalNamespaces(Set<Namespace>) ,public void setXMPPVersion(int, int) <variables>private static final Logger Log,private final Set<Namespace> additionalNamespaces,protected final Map<org.jivesoftware.openfire.ConnectionCloseListener,java.lang.Object> closeListeners,private int majorVersion,private int minorVersion,protected org.jivesoftware.openfire.session.LocalSession session
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/XMLSocketWriter.java
XMLSocketWriter
flush
class XMLSocketWriter extends XMLWriter { private SocketConnection connection; public XMLSocketWriter(Writer writer, SocketConnection connection) { super( writer, DEFAULT_FORMAT ); this.connection = connection; } /** * Flushes the underlying writer making sure that if the connection is dead then the thread * that is flushing does not end up in an endless wait. * * @throws IOException if an I/O error occurs while flushing the writer. */ @Override public void flush() throws IOException {<FILL_FUNCTION_BODY>} }
// Register that we have started sending data connection.writeStarted(); try { super.flush(); } finally { // Register that we have finished sending data connection.writeFinished(); }
147
59
206
<methods>public void <init>(java.io.Writer) ,public void <init>(java.io.Writer, OutputFormat) ,public void <init>() throws java.io.UnsupportedEncodingException,public void <init>(java.io.OutputStream) throws java.io.UnsupportedEncodingException,public void <init>(java.io.OutputStream, OutputFormat) throws java.io.UnsupportedEncodingException,public void <init>(OutputFormat) throws java.io.UnsupportedEncodingException,public void characters(char[], int, int) throws org.xml.sax.SAXException,public void close() throws java.io.IOException,public void comment(char[], int, int) throws org.xml.sax.SAXException,public void endCDATA() throws org.xml.sax.SAXException,public void endDTD() throws org.xml.sax.SAXException,public void endDocument() throws org.xml.sax.SAXException,public void endElement(java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void endEntity(java.lang.String) throws org.xml.sax.SAXException,public void endPrefixMapping(java.lang.String) throws org.xml.sax.SAXException,public void flush() throws java.io.IOException,public org.xml.sax.ext.LexicalHandler getLexicalHandler() ,public int getMaximumAllowedCharacter() ,public java.lang.Object getProperty(java.lang.String) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException,public void ignorableWhitespace(char[], int, int) throws org.xml.sax.SAXException,public boolean isEscapeText() ,public void notationDecl(java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void parse(org.xml.sax.InputSource) throws java.io.IOException, org.xml.sax.SAXException,public void println() throws java.io.IOException,public void processingInstruction(java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public boolean resolveEntityRefs() ,public void setDocumentLocator(org.xml.sax.Locator) ,public void setEscapeText(boolean) ,public void setIndentLevel(int) ,public void setLexicalHandler(org.xml.sax.ext.LexicalHandler) ,public void setMaximumAllowedCharacter(int) ,public void setOutputStream(java.io.OutputStream) throws java.io.UnsupportedEncodingException,public void setProperty(java.lang.String, java.lang.Object) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException,public void setResolveEntityRefs(boolean) ,public void setWriter(java.io.Writer) ,public void startCDATA() throws org.xml.sax.SAXException,public void startDTD(java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void startDocument() throws org.xml.sax.SAXException,public void startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) throws org.xml.sax.SAXException,public void startEntity(java.lang.String) throws org.xml.sax.SAXException,public void startPrefixMapping(java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void write(Attribute) throws java.io.IOException,public void write(Document) throws java.io.IOException,public void write(Element) throws java.io.IOException,public void write(CDATA) throws java.io.IOException,public void write(Comment) throws java.io.IOException,public void write(DocumentType) throws java.io.IOException,public void write(Entity) throws java.io.IOException,public void write(Namespace) throws java.io.IOException,public void write(ProcessingInstruction) throws java.io.IOException,public void write(java.lang.String) throws java.io.IOException,public void write(Text) throws java.io.IOException,public void write(Node) throws java.io.IOException,public void write(java.lang.Object) throws java.io.IOException,public void writeClose(Element) throws java.io.IOException,public void writeOpen(Element) throws java.io.IOException<variables>protected static final OutputFormat DEFAULT_FORMAT,protected static final java.lang.String[] LEXICAL_HANDLER_NAMES,private static final Logger Log,private static final java.lang.String PAD_TEXT,private boolean autoFlush,private java.lang.StringBuilder buffer,private boolean charactersAdded,private boolean escapeText,private OutputFormat format,private boolean inDTD,private int indentLevel,private char lastChar,protected int lastOutputNodeType,private org.xml.sax.ext.LexicalHandler lexicalHandler,private int maximumAllowedCharacter,private NamespaceStack namespaceStack,private Map<java.lang.String,java.lang.String> namespacesMap,protected boolean preserve,private boolean resolveEntityRefs,private boolean showCommentsInDTDs,protected java.io.Writer writer
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/XMPPCallbackHandler.java
XMPPCallbackHandler
handle
class XMPPCallbackHandler implements CallbackHandler { private static final Logger Log = LoggerFactory.getLogger(XMPPCallbackHandler.class); public XMPPCallbackHandler() { } @Override public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {<FILL_FUNCTION_BODY>} }
String name = null; for (Callback callback : callbacks) { if (callback instanceof RealmCallback) { ((RealmCallback) callback).setText( XMPPServer.getInstance().getServerInfo().getXMPPDomain() ); } else if (callback instanceof NameCallback) { name = ((NameCallback) callback).getName(); if (name == null) { name = ((NameCallback) callback).getDefaultName(); } Log.trace("NameCallback: {}", name); } else if (callback instanceof PasswordCallback) { try { // Get the password from the UserProvider. Some UserProviders may not support this operation ((PasswordCallback) callback).setPassword(AuthFactory.getPassword(name).toCharArray()); Log.trace("PasswordCallback"); } catch (UserNotFoundException | UnsupportedOperationException e) { throw new IOException(e.toString()); } } else if (callback instanceof VerifyPasswordCallback) { Log.trace("VerifyPasswordCallback"); VerifyPasswordCallback vpcb = (VerifyPasswordCallback) callback; try { AuthToken at = AuthFactory.authenticate(name, new String(vpcb.getPassword())); vpcb.setVerified((at != null)); } catch (Exception e) { vpcb.setVerified(false); } } else if (callback instanceof AuthorizeCallback) { Log.trace("AuthorizeCallback"); AuthorizeCallback authCallback = ((AuthorizeCallback) callback); // Principal that authenticated - identity whose password was used. String authcid = authCallback.getAuthenticationID(); // Username requested (not full JID) - identity to act as. String authzid = authCallback.getAuthorizationID(); // Remove any REALM from the username. This is optional in the specifications, and it may cause // a lot of users to fail to log in if their clients is sending an incorrect value. if (authzid != null && authzid.contains("@")) { authzid = authzid.substring(0, authzid.lastIndexOf("@")); } if (authcid.equals(authzid)) { // Client perhaps made no request, get default username. authzid = AuthorizationManager.map(authcid); Log.trace("No username requested, using {}", authzid); } if (AuthorizationManager.authorize(authzid, authcid)) { Log.trace("{} authorized to {}", authcid, authzid); authCallback.setAuthorized(true); authCallback.setAuthorizedID(authzid); } else { Log.trace("{} not authorized to {}", authcid, authzid); authCallback.setAuthorized(false); } } else { Log.debug("Unsupported callback: {}" + callback.getClass().getSimpleName()); throw new UnsupportedCallbackException(callback, "Unrecognized Callback"); } }
93
756
849
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyClientConnectionHandler.java
NettyClientConnectionHandler
createNettyConnection
class NettyClientConnectionHandler extends NettyConnectionHandler{ /** * Enable / disable backup delivery of stanzas to the 'offline message store' of the corresponding user when a stanza * failed to be delivered on a client connection. When disabled, stanzas that can not be delivered on the connection * are discarded. */ public static final SystemProperty<Boolean> BACKUP_PACKET_DELIVERY_ENABLED = SystemProperty.Builder.ofType(Boolean.class) .setKey("xmpp.client.backup-packet-delivery.enabled") .setDefaultValue(true) .setDynamic(true) .build(); public NettyClientConnectionHandler(ConnectionConfiguration configuration) { super(configuration); } @Override NettyConnection createNettyConnection(ChannelHandlerContext ctx) {<FILL_FUNCTION_BODY>} @Override StanzaHandler createStanzaHandler(NettyConnection connection) { return new ClientStanzaHandler(XMPPServer.getInstance ().getPacketRouter(), connection); } @Override public Duration getMaxIdleTime() { return ConnectionSettings.Client.IDLE_TIMEOUT_PROPERTY.getValue(); } @Override public String toString() { return "NettyClientConnectionHandler{" + "sslInitDone=" + sslInitDone + ", configuration=" + configuration + '}'; } }
final PacketDeliverer backupDeliverer = BACKUP_PACKET_DELIVERY_ENABLED.getValue() ? new OfflinePacketDeliverer() : null; return new NettyConnection(ctx, backupDeliverer, configuration);
372
64
436
<methods>public void channelRead0(ChannelHandlerContext, java.lang.String) ,public void channelUnregistered(ChannelHandlerContext) throws java.lang.Exception,public void exceptionCaught(ChannelHandlerContext, java.lang.Throwable) ,public abstract java.time.Duration getMaxIdleTime() ,public void handlerAdded(ChannelHandlerContext) ,public void handlerRemoved(ChannelHandlerContext) ,public java.lang.String toString() ,public void userEventTriggered(ChannelHandlerContext, java.lang.Object) throws java.lang.Exception<variables>public static final AttributeKey<org.jivesoftware.openfire.nio.NettyConnection> CONNECTION,static final AttributeKey<org.jivesoftware.openfire.net.StanzaHandler> HANDLER,public static final AttributeKey<java.lang.Boolean> IDLE_FLAG,private static final Logger Log,protected static final ThreadLocal<org.dom4j.io.XMPPPacketReader> PARSER_CACHE,public static final AttributeKey<java.lang.Long> READ_BYTES,public static final AttributeKey<java.lang.Long> WRITTEN_BYTES,static final AttributeKey<org.jivesoftware.openfire.nio.XMLLightweightParser> XML_PARSER,protected final non-sealed org.jivesoftware.openfire.spi.ConnectionConfiguration configuration,private static XmlPullParserFactory factory,protected boolean sslInitDone
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyComponentConnectionHandler.java
NettyComponentConnectionHandler
toString
class NettyComponentConnectionHandler extends NettyConnectionHandler { /** * Enable / disable backup delivery of stanzas to the XMPP server itself when a stanza failed to be delivered on a * component connection. When disabled, stanzas that can not be delivered on the connection are discarded. */ public static final SystemProperty<Boolean> BACKUP_PACKET_DELIVERY_ENABLED = SystemProperty.Builder.ofType(Boolean.class) .setKey("xmpp.component.backup-packet-delivery.enabled") .setDefaultValue(true) .setDynamic(true) .build(); public NettyComponentConnectionHandler(ConnectionConfiguration configuration) { super(configuration); } @Override NettyConnection createNettyConnection(ChannelHandlerContext ctx) { final PacketDeliverer backupDeliverer = BACKUP_PACKET_DELIVERY_ENABLED.getValue() ? XMPPServer.getInstance().getPacketDeliverer() : null; return new NettyConnection(ctx, backupDeliverer, configuration); } @Override StanzaHandler createStanzaHandler(NettyConnection connection) { return new ComponentStanzaHandler(XMPPServer.getInstance().getPacketRouter(), connection); } @Override public Duration getMaxIdleTime() { return ConnectionSettings.Component.IDLE_TIMEOUT_PROPERTY.getValue(); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "NettyComponentConnectionHandler{" + "sslInitDone=" + sslInitDone + ", configuration=" + configuration + '}';
389
42
431
<methods>public void channelRead0(ChannelHandlerContext, java.lang.String) ,public void channelUnregistered(ChannelHandlerContext) throws java.lang.Exception,public void exceptionCaught(ChannelHandlerContext, java.lang.Throwable) ,public abstract java.time.Duration getMaxIdleTime() ,public void handlerAdded(ChannelHandlerContext) ,public void handlerRemoved(ChannelHandlerContext) ,public java.lang.String toString() ,public void userEventTriggered(ChannelHandlerContext, java.lang.Object) throws java.lang.Exception<variables>public static final AttributeKey<org.jivesoftware.openfire.nio.NettyConnection> CONNECTION,static final AttributeKey<org.jivesoftware.openfire.net.StanzaHandler> HANDLER,public static final AttributeKey<java.lang.Boolean> IDLE_FLAG,private static final Logger Log,protected static final ThreadLocal<org.dom4j.io.XMPPPacketReader> PARSER_CACHE,public static final AttributeKey<java.lang.Long> READ_BYTES,public static final AttributeKey<java.lang.Long> WRITTEN_BYTES,static final AttributeKey<org.jivesoftware.openfire.nio.XMLLightweightParser> XML_PARSER,protected final non-sealed org.jivesoftware.openfire.spi.ConnectionConfiguration configuration,private static XmlPullParserFactory factory,protected boolean sslInitDone
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyConnectionHandler.java
NettyConnectionHandler
channelRead0
class NettyConnectionHandler extends SimpleChannelInboundHandler<String> { private static final Logger Log = LoggerFactory.getLogger(NettyConnectionHandler.class); static final AttributeKey<XMLLightweightParser> XML_PARSER = AttributeKey.valueOf("XML-PARSER"); public static final AttributeKey<NettyConnection> CONNECTION = AttributeKey.valueOf("CONNECTION"); public static final AttributeKey<Long> READ_BYTES = AttributeKey.valueOf("READ_BYTES"); public static final AttributeKey<Long> WRITTEN_BYTES = AttributeKey.valueOf("WRITTEN_BYTES"); static final AttributeKey<StanzaHandler> HANDLER = AttributeKey.valueOf("HANDLER"); public static final AttributeKey<Boolean> IDLE_FLAG = AttributeKey.valueOf("IDLE_FLAG"); protected static final ThreadLocal<XMPPPacketReader> PARSER_CACHE = new ThreadLocal<XMPPPacketReader>() { @Override protected XMPPPacketReader initialValue() { final XMPPPacketReader parser = new XMPPPacketReader(); parser.setXPPFactory( factory ); return parser; } }; /** * Reuse the same factory for all the connections. */ private static XmlPullParserFactory factory = null; protected boolean sslInitDone; static { try { factory = XmlPullParserFactory.newInstance(MXParser.class.getName(), null); factory.setNamespaceAware(true); } catch (XmlPullParserException e) { Log.error("Error creating a parser factory", e); } } /** * The configuration for new connections. */ protected final ConnectionConfiguration configuration; protected NettyConnectionHandler(ConnectionConfiguration configuration ) { this.configuration = configuration; } abstract NettyConnection createNettyConnection(ChannelHandlerContext ctx); abstract StanzaHandler createStanzaHandler(NettyConnection connection); /** * Returns the time that a connection can be idle before being closed. * * @return the time a connection can be idle. */ public abstract Duration getMaxIdleTime(); @Override public void handlerAdded(ChannelHandlerContext ctx) { Log.trace("Netty XMPP handler added: {}", ctx.channel().remoteAddress() == null ? ctx.channel().localAddress() : ctx.channel().localAddress() + "--" + ctx.channel().remoteAddress()); // Create a new XML parser for the new connection. The parser will be used by the XMPPDecoder filter. ctx.channel().attr(XML_PARSER).set(new XMLLightweightParser()); // Create a new Connection for the new session final NettyConnection nettyConnection = createNettyConnection(ctx); ctx.channel().attr(CONNECTION).set(nettyConnection); ctx.channel().attr(READ_BYTES).set(0L); ctx.channel().attr(HANDLER).set(createStanzaHandler(nettyConnection)); } @Override public void handlerRemoved(ChannelHandlerContext ctx) { Log.trace("Netty XMPP handler removed: {}", ctx.channel().remoteAddress() == null ? ctx.channel().localAddress() : ctx.channel().localAddress() + "--" + ctx.channel().remoteAddress()); } @Override public void channelRead0(ChannelHandlerContext ctx, String message) {<FILL_FUNCTION_BODY>} @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. Log.error("Exception caught on channel {}", ctx.channel().remoteAddress() == null ? ctx.channel().localAddress() : ctx.channel().localAddress() + "--" + ctx.channel().remoteAddress(), cause); ctx.channel().close(); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { Connection connection = ctx.channel().attr(CONNECTION).get(); if (connection != null) { connection.close(); // clean up resources (connection and session) when channel is unregistered. } super.channelUnregistered(ctx); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (!sslInitDone && evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt; if (e.isSuccess()) { sslInitDone = true; NettyConnection connection = ctx.channel().attr(NettyConnectionHandler.CONNECTION).get(); connection.setEncrypted(true); Log.debug("TLS negotiation was successful on channel {}", ctx.channel().remoteAddress() == null ? ctx.channel().localAddress() : ctx.channel().localAddress() + "--" + ctx.channel().remoteAddress()); ctx.fireChannelActive(); } } super.userEventTriggered(ctx, evt); } /** * Updates the system counter of read bytes. This information is used by the incoming * bytes statistic. * * @param ctx the context for the channel reading bytes */ private void updateReadBytesCounter(ChannelHandlerContext ctx) { ChannelTrafficShapingHandler handler = (ChannelTrafficShapingHandler) ctx.channel().pipeline().get(TRAFFIC_HANDLER_NAME); if (handler != null) { long currentBytes = handler.trafficCounter().currentReadBytes(); Long prevBytes = ctx.channel().attr(READ_BYTES).get(); long delta; if (prevBytes == null) { delta = currentBytes; } else { delta = currentBytes - prevBytes; } ctx.channel().attr(READ_BYTES).set(currentBytes); ctx.channel().attr(IDLE_FLAG).set(null); ServerTrafficCounter.incrementIncomingCounter(delta); } } @Override public String toString() { return "NettyConnectionHandler{" + "sslInitDone=" + sslInitDone + ", configuration=" + configuration + '}'; } }
// Get the parser to use to process stanza. For optimization there is going // to be a parser for each running thread. Each Filter will be executed // by the Executor placed as the first Filter. So we can have a parser associated // to each Thread final XMPPPacketReader parser = PARSER_CACHE.get(); // Update counter of read bytes updateReadBytesCounter(ctx); Log.trace("Handler on {} received: {}", ctx.channel().remoteAddress() == null ? ctx.channel().localAddress() : ctx.channel().localAddress() + "--" + ctx.channel().remoteAddress(), message); // Let the stanza handler process the received stanza try { ctx.channel().attr(HANDLER).get().process(message, parser); } catch (Throwable e) { // Make sure to catch Throwable, not (only) Exception! See OF-2367 Log.error("Closing connection on {} due to error while processing message: {}", ctx.channel().remoteAddress() == null ? ctx.channel().localAddress() : ctx.channel().localAddress() + "--" + ctx.channel().remoteAddress(), message, e); final Connection connection = ctx.channel().attr(CONNECTION).get(); if ( connection != null ) { connection.close(new StreamError(StreamError.Condition.internal_server_error, "An error occurred while processing data raw inbound data.")); } }
1,608
355
1,963
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyConnectionHandlerFactory.java
NettyConnectionHandlerFactory
createConnectionHandler
class NettyConnectionHandlerFactory { /** * Creates a new NettyConnectionHandler based on the type of connection set in the configuration. * @param configuration options for how the connection is configured * @return a new NettyConnectionHandler */ public static NettyConnectionHandler createConnectionHandler(ConnectionConfiguration configuration) {<FILL_FUNCTION_BODY>} }
switch (configuration.getType()) { case SOCKET_S2S: return new NettyServerConnectionHandler(configuration); case SOCKET_C2S: return new NettyClientConnectionHandler(configuration); case COMPONENT: return new NettyComponentConnectionHandler(configuration); case CONNECTION_MANAGER: return new NettyMultiplexerConnectionHandler(configuration); default: throw new IllegalStateException("This implementation does not support the connection type as defined in the provided configuration: " + configuration.getType()); }
92
142
234
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyIdleStateKeepAliveHandler.java
NettyIdleStateKeepAliveHandler
sendPingPacket
class NettyIdleStateKeepAliveHandler extends ChannelDuplexHandler { private final boolean clientConnection; private static final Logger Log = LoggerFactory.getLogger(NettyIdleStateKeepAliveHandler.class); public NettyIdleStateKeepAliveHandler(boolean clientConnection) { this.clientConnection = clientConnection; } /** * Processes IdleStateEvents triggered by an IdleStateHandler. * If the IdleStateEvent is an idle read state, the Netty channel is closed. * If the IdleStateEvent is an idle write state, an XMPP ping request is sent * to the remote entity. * * @param ctx ChannelHandlerContext * @param evt Event caught, expect IdleStateEvent * @throws Exception when attempting to deliver ping packet */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == IdleState.READER_IDLE) { final boolean doPing = ConnectionSettings.Client.KEEP_ALIVE_PING_PROPERTY.getValue() && clientConnection; final Channel channel = ctx.channel(); if (channel.attr(IDLE_FLAG).getAndSet(true) == null) { // Idle flag is now set, but wasn't present before. if (doPing) { sendPingPacket(channel); } } else { // Idle flag already present. Connection has been idle for a while. Close it. final NettyConnection connection = channel.attr(CONNECTION).get(); Log.debug("Closing connection because of inactivity: {}", connection); connection.close(new StreamError(StreamError.Condition.connection_timeout, doPing ? "Connection has been idle and did not respond to a keep-alive check." : "Connection has been idle."), doPing); } } super.userEventTriggered(ctx, evt); } /** * Sends an IQ ping packet on the channel associated with the channel handler context. * * @param channel Channel over which to send a ping. * @throws UnauthorizedException when attempting to deliver ping packet */ private void sendPingPacket(Channel channel) throws UnauthorizedException {<FILL_FUNCTION_BODY>} }
NettyConnection connection = channel.attr(CONNECTION).get(); JID entity = connection.getSession() == null ? null : connection.getSession().getAddress(); if (entity != null) { // Ping the connection to see if it is alive. final IQ pingRequest = new IQ(IQ.Type.get); pingRequest.setChildElement("ping", IQPingHandler.NAMESPACE); pingRequest.setFrom(XMPPServer.getInstance().getServerInfo().getXMPPDomain()); pingRequest.setTo(entity); Log.debug("Pinging connection that has been idle: {}", connection); // OF-1497: Ensure that data sent to the client is processed through LocalClientSession, to avoid // synchronisation issues with stanza counts related to Stream Management (XEP-0198)! LocalClientSession ofSession = (LocalClientSession) SessionManager.getInstance().getSession(entity); if (ofSession == null) { Log.warn("Trying to ping a Netty connection that's idle, but has no corresponding Openfire session. Netty Connection: {}", connection); } else { ofSession.deliver(pingRequest); } }
593
304
897
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyMultiplexerConnectionHandler.java
NettyMultiplexerConnectionHandler
createNettyConnection
class NettyMultiplexerConnectionHandler extends NettyConnectionHandler { /** * Enable / disable backup delivery of stanzas to other connections in the same connection manager when a stanza * failed to be delivered on a multiplexer (connection manager) connection. When disabled, stanzas that can not * be delivered on the connection are discarded. */ public static final SystemProperty<Boolean> BACKUP_PACKET_DELIVERY_ENABLED = SystemProperty.Builder.ofType(Boolean.class) .setKey("xmpp.multiplex.backup-packet-delivery.enabled") .setDefaultValue(true) .setDynamic(true) .build(); public NettyMultiplexerConnectionHandler(ConnectionConfiguration configuration) { super(configuration); } @Override NettyConnection createNettyConnection(ChannelHandlerContext ctx) {<FILL_FUNCTION_BODY>} @Override StanzaHandler createStanzaHandler(NettyConnection connection) { return new MultiplexerStanzaHandler(XMPPServer.getInstance().getPacketRouter(), connection); } @Override public Duration getMaxIdleTime() { return ConnectionSettings.Multiplex.IDLE_TIMEOUT_PROPERTY.getValue(); } @Override public String toString() { return "NettyMultiplexerConnectionHandler{" + "sslInitDone=" + sslInitDone + ", configuration=" + configuration + '}'; } }
final PacketDeliverer backupDeliverer = BACKUP_PACKET_DELIVERY_ENABLED.getValue() ? new MultiplexerPacketDeliverer() : null; return new NettyConnection(ctx, backupDeliverer, configuration);
387
66
453
<methods>public void channelRead0(ChannelHandlerContext, java.lang.String) ,public void channelUnregistered(ChannelHandlerContext) throws java.lang.Exception,public void exceptionCaught(ChannelHandlerContext, java.lang.Throwable) ,public abstract java.time.Duration getMaxIdleTime() ,public void handlerAdded(ChannelHandlerContext) ,public void handlerRemoved(ChannelHandlerContext) ,public java.lang.String toString() ,public void userEventTriggered(ChannelHandlerContext, java.lang.Object) throws java.lang.Exception<variables>public static final AttributeKey<org.jivesoftware.openfire.nio.NettyConnection> CONNECTION,static final AttributeKey<org.jivesoftware.openfire.net.StanzaHandler> HANDLER,public static final AttributeKey<java.lang.Boolean> IDLE_FLAG,private static final Logger Log,protected static final ThreadLocal<org.dom4j.io.XMPPPacketReader> PARSER_CACHE,public static final AttributeKey<java.lang.Long> READ_BYTES,public static final AttributeKey<java.lang.Long> WRITTEN_BYTES,static final AttributeKey<org.jivesoftware.openfire.nio.XMLLightweightParser> XML_PARSER,protected final non-sealed org.jivesoftware.openfire.spi.ConnectionConfiguration configuration,private static XmlPullParserFactory factory,protected boolean sslInitDone
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyServerConnectionHandler.java
NettyServerConnectionHandler
toString
class NettyServerConnectionHandler extends NettyConnectionHandler { private static final Logger Log = LoggerFactory.getLogger(NettyServerConnectionHandler.class); /** * Enable / disable backup delivery of stanzas to the XMPP server itself when a stanza failed to be delivered on a * server-to-server connection. When disabled, stanzas that can not be delivered on the connection are discarded. */ public static final SystemProperty<Boolean> BACKUP_PACKET_DELIVERY_ENABLED = SystemProperty.Builder.ofType(Boolean.class) .setKey("xmpp.server.backup-packet-delivery.enabled") .setDefaultValue(true) .setDynamic(true) .build(); private final boolean directTLS; public NettyServerConnectionHandler(ConnectionConfiguration configuration) { super(configuration); this.directTLS = configuration.getTlsPolicy() == Connection.TLSPolicy.directTLS; } @Override NettyConnection createNettyConnection(ChannelHandlerContext ctx) { final PacketDeliverer backupDeliverer = BACKUP_PACKET_DELIVERY_ENABLED.getValue() ? XMPPServer.getInstance().getPacketDeliverer() : null; return new NettyConnection(ctx, backupDeliverer, configuration); } @Override StanzaHandler createStanzaHandler(NettyConnection connection) { return new ServerStanzaHandler( XMPPServer.getInstance().getPacketRouter(), connection, directTLS); } @Override public void handlerAdded(ChannelHandlerContext ctx) { Log.trace("Adding NettyServerConnectionHandler"); super.handlerAdded(ctx); } public Duration getMaxIdleTime() { return ConnectionSettings.Server.IDLE_TIMEOUT_PROPERTY.getValue(); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "NettyServerConnectionHandler{" + "directTLS=" + directTLS + ", sslInitDone=" + sslInitDone + ", configuration=" + configuration + '}';
500
56
556
<methods>public void channelRead0(ChannelHandlerContext, java.lang.String) ,public void channelUnregistered(ChannelHandlerContext) throws java.lang.Exception,public void exceptionCaught(ChannelHandlerContext, java.lang.Throwable) ,public abstract java.time.Duration getMaxIdleTime() ,public void handlerAdded(ChannelHandlerContext) ,public void handlerRemoved(ChannelHandlerContext) ,public java.lang.String toString() ,public void userEventTriggered(ChannelHandlerContext, java.lang.Object) throws java.lang.Exception<variables>public static final AttributeKey<org.jivesoftware.openfire.nio.NettyConnection> CONNECTION,static final AttributeKey<org.jivesoftware.openfire.net.StanzaHandler> HANDLER,public static final AttributeKey<java.lang.Boolean> IDLE_FLAG,private static final Logger Log,protected static final ThreadLocal<org.dom4j.io.XMPPPacketReader> PARSER_CACHE,public static final AttributeKey<java.lang.Long> READ_BYTES,public static final AttributeKey<java.lang.Long> WRITTEN_BYTES,static final AttributeKey<org.jivesoftware.openfire.nio.XMLLightweightParser> XML_PARSER,protected final non-sealed org.jivesoftware.openfire.spi.ConnectionConfiguration configuration,private static XmlPullParserFactory factory,protected boolean sslInitDone
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyXMPPDecoder.java
NettyXMPPDecoder
decode
class NettyXMPPDecoder extends ByteToMessageDecoder { private static final Logger Log = LoggerFactory.getLogger(NettyXMPPDecoder.class); @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {<FILL_FUNCTION_BODY>} @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { final NettyConnection connection = ctx.channel().attr(CONNECTION).get(); Log.warn("Error occurred while decoding XMPP stanza, closing connection: {}", connection, cause); connection.close(new StreamError(StreamError.Condition.internal_server_error, "An error occurred in XMPP Decoder"), cause instanceof IOException); } }
// Get the XML parser from the channel XMLLightweightParser parser = ctx.channel().attr(NettyConnectionHandler.XML_PARSER).get(); // Check that the stanza constructed by the parser is not bigger than 1 Megabyte. For security reasons // we will abort parsing when 1 Mega of queued chars was found. if (parser.isMaxBufferSizeExceeded()) { // Clear out the buffer to prevent endless exceptions being thrown while the connection is closed. // De-allocation of the buffer from this channel will occur following the channel closure, so there is // no need to call in.release() as this will cause an IllegalReferenceCountException. in.clear(); NettyConnection connection = ctx.channel().attr(CONNECTION).get(); Log.warn("Maximum buffer size was exceeded, closing connection: " + connection); connection.close(new StreamError(StreamError.Condition.policy_violation, "Maximum stanza length exceeded")); return; } // Parse as many stanzas as possible from the received data char[] readChars = in.readCharSequence(in.readableBytes(), CharsetUtil.UTF_8).toString().toCharArray(); parser.read(readChars); // Add any decoded messages to our outbound list to be processed by subsequent channelRead() events if (parser.areThereMsgs()) { out.addAll(Arrays.asList(parser.getMsgs())); }
198
369
567
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/nio/OfflinePacketDeliverer.java
OfflinePacketDeliverer
deliver
class OfflinePacketDeliverer implements PacketDeliverer { private static final Logger Log = LoggerFactory.getLogger(OfflinePacketDeliverer.class); private OfflineMessageStrategy messageStrategy; public OfflinePacketDeliverer() { this.messageStrategy = XMPPServer.getInstance().getOfflineMessageStrategy(); } @Override public void deliver(Packet packet) throws UnauthorizedException, PacketException {<FILL_FUNCTION_BODY>} }
if (packet instanceof Message) { messageStrategy.storeOffline((Message) packet); } else if (packet instanceof Presence) { // presence packets are dropped silently } else if (packet instanceof IQ) { // IQ packets are logged before being dropped Log.warn(LocaleUtils.getLocalizedString("admin.error.routing") + "\n" + packet.toString()); }
130
112
242
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/PendingSubscriptionsCommand.java
PendingSubscriptionsCommand
hasPermission
class PendingSubscriptionsCommand extends AdHocCommand { private PubSubService service; public PendingSubscriptionsCommand(PubSubService service) { this.service = service; } @Override protected void addStageInformation(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); DataForm form = new DataForm(DataForm.Type.form); form.setTitle(LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.title", preferredLocale)); form.addInstruction(LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.instruction", preferredLocale)); FormField formField = form.addField(); formField.setVariable("pubsub#node"); formField.setType(FormField.Type.list_single); formField.setLabel(LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.node", preferredLocale)); for (Node node : service.getNodes()) { if (!node.isCollectionNode() && node.isAdmin(data.getOwner())) { formField.addOption(null, node.getUniqueIdentifier().getNodeId()); } } // Add the form to the command command.add(form.getElement()); } @Override public void execute(@Nonnull final SessionData data, Element command) { final Locale preferredLocale = SessionManager.getInstance().getLocaleForSession(data.getOwner()); Element note = command.addElement("note"); List<String> nodeIDs = data.getData().get("pubsub#node"); if (nodeIDs.isEmpty()) { // No nodeID was provided by the requester note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.error.idrequired", preferredLocale)); } else if (nodeIDs.size() > 1) { // More than one nodeID was provided by the requester note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.error.manyIDs", preferredLocale)); } else { Node node = service.getNode(nodeIDs.get(0)); if (node != null) { if (node.isAdmin(data.getOwner())) { note.addAttribute("type", "info"); note.setText(LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.success", preferredLocale)); for (NodeSubscription subscription : node.getPendingSubscriptions()) { subscription.sendAuthorizationRequest(data.getOwner()); } } else { // Requester is not an admin of the specified node note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.error.forbidden", preferredLocale)); } } else { // Node with the specified nodeID was not found note.addAttribute("type", "error"); note.setText(LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.error.badid", preferredLocale)); } } } @Override public String getCode() { return "http://jabber.org/protocol/pubsub#get-pending"; } @Override public String getDefaultLabel() { return LocaleUtils.getLocalizedString("pubsub.command.pending-subscriptions.label"); } @Override protected List<Action> getActions(@Nonnull final SessionData data) { return Collections.singletonList(Action.complete); } @Override protected Action getExecuteAction(@Nonnull final SessionData data) { return Action.complete; } @Override public int getMaxStages(@Nonnull final SessionData data) { return 1; } @Override public boolean hasPermission(JID requester) {<FILL_FUNCTION_BODY>} }
// User has permission if he is an owner of at least one node or is a sysadmin for (Node node : service.getNodes()) { if (!node.isCollectionNode() && node.isAdmin(requester)) { return true; } } return false;
1,057
73
1,130
<methods>public void <init>() ,public void addNextStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public void addPreviousStageInformation(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract void execute(org.jivesoftware.openfire.commands.SessionData, Element) ,public abstract java.lang.String getCode() ,public abstract java.lang.String getDefaultLabel() ,public java.lang.String getLabel() ,public abstract int getMaxStages(org.jivesoftware.openfire.commands.SessionData) ,public boolean hasPermission(JID) ,public void setLabel(java.lang.String) <variables>private java.lang.String label
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/PubSubPersistenceProviderManager.java
PubSubPersistenceProviderManager
initProvider
class PubSubPersistenceProviderManager { public static final SystemProperty<Class> PROVIDER = SystemProperty.Builder.ofType(Class.class) .setKey("provider.pubsub-persistence.className") .setBaseClass(PubSubPersistenceProvider.class) .setDynamic(false) .build(); private static final Logger Log = LoggerFactory.getLogger( PubSubPersistenceProviderManager.class ); private PubSubPersistenceProvider provider; /** * Instantiates a new instance. * * It is not expected that there ever is more than one instance of the manager, as it's closely coupled to * {@link PubSubModule}. This constructor has 'package' access restrictions to reflect this. */ PubSubPersistenceProviderManager() {} public void initialize() { initProvider(); } public PubSubPersistenceProvider getProvider() { return this.provider; } private void initProvider() {<FILL_FUNCTION_BODY>} public void shutdown() { if ( provider != null ) { provider.shutdown(); provider = null; } } }
Class clazz = PROVIDER.getValue(); if ( clazz == null ) { if ( ClusterManager.isClusteringEnabled() ) { Log.debug("Clustering is enabled. Falling back to non-cached provider"); clazz = DefaultPubSubPersistenceProvider.class; } else { clazz = CachingPubsubPersistenceProvider.class; } } // Check if we need to reset the provider class if (provider == null || !clazz.equals(provider.getClass()) ) { if ( provider != null ) { provider.shutdown(); provider = null; } try { Log.info("Loading PubSub persistence provider: {}.", clazz); provider = (PubSubPersistenceProvider) clazz.newInstance(); provider.initialize(); } catch (Exception e) { Log.error("Error loading PubSub persistence provider: {}. Using default provider instead.", clazz, e); provider = new DefaultPubSubPersistenceProvider(); provider.initialize(); } }
299
271
570
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/AffiliationTask.java
AffiliationTask
toString
class AffiliationTask extends NodeTask { private static final Logger log = LoggerFactory.getLogger(AffiliationTask.class); /** * Address of the entity that needs an update to the affiliation with a pubsub node. */ private JID jid; /** * The new pubsub node affiliation of an entity. */ private NodeAffiliate.Affiliation affiliation; /** * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise. */ public AffiliationTask() { } /** * Constructs a new task that updates the affiliation of a particular entity with a specific pubsub node. * * @param node The pubsub node that this task relates to. * @param jid The address of the entity that has an affiliation with the pubsub node. * @param affiliation The affiliation that the entity has with the pubsub node. */ public AffiliationTask(@Nonnull Node node, @Nonnull JID jid, @Nonnull NodeAffiliate.Affiliation affiliation) { super(node); this.jid = jid; this.affiliation = affiliation; } /** * Provides the address of the entity that has a new affiliation with a pubsub node. * * @return the address of an entity. */ public JID getJID() { return jid; } /** * The new affiliation with a pubsub node. * * @return a pubsub node affiliation. */ public NodeAffiliate.Affiliation getAffiliation() { return affiliation; } @Override public void run() { // Note: this implementation should apply changes in-memory state only. It explicitly needs not update // persisted data storage, as this can be expected to be done by the cluster node that issued this task. // Applying such changes in this task would, at best, needlessly require resources. log.debug("[TASK] New affiliation : {}", toString()); final Optional<Node> optNode = getNodeIfLoaded(); // This will only occur if a PEP service is not loaded on this particular cluster node. We can safely do nothing // in this case since any changes that might have been applied here will also have been applied to the database // by the cluster node where this task originated, meaning that those changes get loaded from the database when // the pubsub node is retrieved from the database in the future (OF-2077) if (!optNode.isPresent()) { return; } final Node node = optNode.get(); // Create a new affiliate if the entity is not an affiliate yet. NodeAffiliate affiliate = node.getAffiliate(jid); if (affiliate == null) { // No existing affiliate: create a new one. affiliate = new NodeAffiliate(node, jid); node.addAffiliate(affiliate); } affiliate.setAffiliation(affiliation); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); ExternalizableUtil.getInstance().writeSerializable(out, jid); ExternalizableUtil.getInstance().writeSerializable(out, affiliation); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); jid = (JID) ExternalizableUtil.getInstance().readSerializable(in); affiliation = (NodeAffiliate.Affiliation) ExternalizableUtil.getInstance().readSerializable(in); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return getClass().getSimpleName() + " [(service=" + serviceId + "), (nodeId=" + nodeId + "), (JID=" + jid + "),(affiliation=" + affiliation + ")]";
979
61
1,040
<methods>public java.lang.String getNodeId() ,public Optional<org.jivesoftware.openfire.pubsub.Node> getNodeIfLoaded() ,public java.lang.Void getResult() ,public Optional<org.jivesoftware.openfire.pubsub.PubSubService> getServiceIfLoaded() ,public org.jivesoftware.openfire.pubsub.Node.UniqueIdentifier getUniqueNodeIdentifier() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>protected java.lang.String nodeId,protected java.lang.String serviceId,protected transient org.jivesoftware.openfire.pubsub.Node.UniqueIdentifier uniqueNodeIdentifier
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/CancelSubscriptionTask.java
CancelSubscriptionTask
run
class CancelSubscriptionTask extends SubscriptionTask { private static final Logger log = LoggerFactory.getLogger(CancelSubscriptionTask.class); /** * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise. */ public CancelSubscriptionTask() { } /** * Constructs a new task that cancels a subscription to a pubsub node. * * @param subscription The to-be-cancelled subscription */ public CancelSubscriptionTask(@Nonnull final NodeSubscription subscription) { super(subscription); } @Override public void run() {<FILL_FUNCTION_BODY>} }
// Note: this implementation should apply changes in-memory state only. It explicitly needs not update // persisted data storage, as this can be expected to be done by the cluster node that issued this task. // Applying such changes in this task would, at best, needlessly require resources. log.debug("[TASK] Cancel Subscription : {}", toString()); final Optional<Node> optNode = getNodeIfLoaded(); final Optional<NodeSubscription> optSubscription = getSubscriptionIfLoaded(); // This will only occur if a PEP service is not loaded on this particular cluster node. We can safely do nothing // in this case since any changes that might have been applied here will also have been applied to the database // by the cluster node where this task originated, meaning that those changes get loaded from the database when // the pubsub node is retrieved from the database in the future (OF-2077) if (!optNode.isPresent() || !optSubscription.isPresent()) { return; } final Node node = optNode.get(); final NodeSubscription subscription = optSubscription.get(); // This method will make a db call, but it will simply do nothing since // the record will already be deleted. // TODO OF-2139 prevent unnecessary database interaction. node.cancelSubscription(subscription, false);
183
331
514
<methods>public void <init>() ,public void <init>(org.jivesoftware.openfire.pubsub.NodeSubscription) ,public JID getOwner() ,public org.jivesoftware.openfire.pubsub.NodeSubscription.State getState() ,public JID getSubscriberJid() ,public java.lang.String getSubscriptionId() ,public Optional<org.jivesoftware.openfire.pubsub.NodeSubscription> getSubscriptionIfLoaded() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public java.lang.String toString() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private JID owner,private org.jivesoftware.openfire.pubsub.NodeSubscription.State state,private java.lang.String subId,private JID subJid
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/FlushTask.java
FlushTask
readExternal
class FlushTask implements ClusterTask<Void> { /** * The unique identifier for the pubsub node that is the subject of the task, in case the task is specific to one * pubsub node. When this task should apply to all nodes, this value will be null. * * @see Node#getUniqueIdentifier() */ @Nullable private Node.UniqueIdentifier uniqueIdentifier; /** * Instantiates a flush task for a specific node. * * @param uniqueIdentifier The identifier of the node to flush. */ public FlushTask(@Nonnull final Node.UniqueIdentifier uniqueIdentifier ) { this.uniqueIdentifier = uniqueIdentifier; } /** * Instantiates a flush task for a system-wide flush of pending changes. */ public FlushTask() { this.uniqueIdentifier = null; } @Override public void run() { final PubSubPersistenceProvider provider = XMPPServer.getInstance().getPubSubModule().getPersistenceProvider(); if ( provider instanceof CachingPubsubPersistenceProvider ) { if ( uniqueIdentifier != null ) { ((CachingPubsubPersistenceProvider) provider).flushPendingChanges(uniqueIdentifier, false ); // just this member } else { ((CachingPubsubPersistenceProvider) provider).flushPendingChanges(false ); // just this member } } } @Override public Void getResult() { return null; } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeBoolean( out, uniqueIdentifier != null); if ( uniqueIdentifier != null ) { ExternalizableUtil.getInstance().writeSerializable( out, uniqueIdentifier ); } } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
if ( ExternalizableUtil.getInstance().readBoolean( in ) ) { uniqueIdentifier = (Node.UniqueIdentifier) ExternalizableUtil.getInstance().readSerializable( in ); } else { this.uniqueIdentifier = null; }
496
64
560
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/ModifySubscriptionTask.java
ModifySubscriptionTask
run
class ModifySubscriptionTask extends SubscriptionTask { private static final Logger log = LoggerFactory.getLogger(ModifySubscriptionTask.class); /** * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise. */ public ModifySubscriptionTask() { } /** * Constructs a new task that modifies a subscription to a pubsub node. * * @param subscription The to-be-modified subscription */ public ModifySubscriptionTask(@Nonnull final NodeSubscription subscription) { super(subscription); } @Override public void run() {<FILL_FUNCTION_BODY>} }
// Note: this implementation should apply changes in-memory state only. It explicitly needs not update // persisted data storage, as this can be expected to be done by the cluster node that issued this task. // Applying such changes in this task would, at best, needlessly require resources. log.debug("[TASK] Modify subscription : {}", toString()); final Optional<Node> optNode = getNodeIfLoaded(); // This will only occur if a PEP service is not loaded on this particular cluster node. We can safely do nothing // in this case since any changes that might have been applied here will also have been applied to the database // by the cluster node where this task originated, meaning that those changes get loaded from the database when // the pubsub node is retrieved from the database in the future (OF-2077) if (!optNode.isPresent()) { return; } final Node node = optNode.get(); // Forcefully (re)load the subscription from the database, which resets any in-memory representation. // TODO OF-2140 Remove database interaction. Instead of reloading, modify the existing in-memory representation with data from this task. XMPPServer.getInstance().getPubSubModule().getPersistenceProvider().loadSubscription(node, getSubscriptionId());
183
319
502
<methods>public void <init>() ,public void <init>(org.jivesoftware.openfire.pubsub.NodeSubscription) ,public JID getOwner() ,public org.jivesoftware.openfire.pubsub.NodeSubscription.State getState() ,public JID getSubscriberJid() ,public java.lang.String getSubscriptionId() ,public Optional<org.jivesoftware.openfire.pubsub.NodeSubscription> getSubscriptionIfLoaded() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public java.lang.String toString() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private JID owner,private org.jivesoftware.openfire.pubsub.NodeSubscription.State state,private java.lang.String subId,private JID subJid
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/NewSubscriptionTask.java
NewSubscriptionTask
run
class NewSubscriptionTask extends SubscriptionTask { private static final Logger log = LoggerFactory.getLogger(NewSubscriptionTask.class); /** * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise. */ public NewSubscriptionTask() { } /** * Constructs a new task that creates a subscription to a pubsub node. * * @param subscription The to-be-created subscription */ public NewSubscriptionTask(@Nonnull final NodeSubscription subscription) { super(subscription); } @Override public void run() {<FILL_FUNCTION_BODY>} }
// Note: this implementation should apply changes in-memory state only. It explicitly needs not update // persisted data storage, as this can be expected to be done by the cluster node that issued this task. // Applying such changes in this task would, at best, needlessly require resources. log.debug("[TASK] New subscription : {}", toString()); final Optional<PubSubService> optService = getServiceIfLoaded(); final Optional<Node> optNode = getNodeIfLoaded(); final Optional<NodeSubscription> optSubscription = getSubscriptionIfLoaded(); // This will only occur if a PEP service is not loaded on this particular cluster node. We can safely do nothing // in this case since any changes that might have been applied here will also have been applied to the database // by the cluster node where this task originated, meaning that those changes get loaded from the database when // the pubsub node is retrieved from the database in the future (OF-2077) if (!optService.isPresent() || !optNode.isPresent() || !optSubscription.isPresent()) { return; } final PubSubService service = optService.get(); final Node node = optNode.get(); final NodeSubscription subscription = optSubscription.get(); if (node.getAffiliate(getOwner()) == null) { // add the missing 'none' affiliation NodeAffiliate affiliate = new NodeAffiliate(node, getOwner()); affiliate.setAffiliation(NodeAffiliate.Affiliation.none); node.addAffiliate(affiliate); } node.addSubscription(subscription); if (node.isPresenceBasedDelivery() && node.getSubscriptions(subscription.getOwner()).size() == 1) { if (subscription.getPresenceStates().isEmpty()) { // Subscribe to the owner's presence since the node is only // sending events to online subscribers and this is the first // subscription of the user and the subscription is not // filtering notifications based on presence show values. service.presenceSubscriptionRequired(node, getOwner()); } }
177
545
722
<methods>public void <init>() ,public void <init>(org.jivesoftware.openfire.pubsub.NodeSubscription) ,public JID getOwner() ,public org.jivesoftware.openfire.pubsub.NodeSubscription.State getState() ,public JID getSubscriberJid() ,public java.lang.String getSubscriptionId() ,public Optional<org.jivesoftware.openfire.pubsub.NodeSubscription> getSubscriptionIfLoaded() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public java.lang.String toString() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private JID owner,private org.jivesoftware.openfire.pubsub.NodeSubscription.State state,private java.lang.String subId,private JID subJid
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/NodeTask.java
NodeTask
getServiceIfLoaded
class NodeTask implements ClusterTask<Void> { /** * The unique identifier for the pubsub node that is the subject of the task. * * This value is a combination of the data that's captured in {@link #nodeId} and {@link #serviceId}, which are * primarily retained in the API for backwards compatibility reasons. * * @see Node#getUniqueIdentifier() */ protected transient Node.UniqueIdentifier uniqueNodeIdentifier; /** * The node identifier, unique in context of the service, for the pubsub node that is the subject of the task. * * The value of this field is combined with that of {@link #serviceId} in {@link #uniqueNodeIdentifier}. To retain * (serialization) compatibility with older versions, the nodeId field is retained. It is, however, advisable to * make use of {@link #uniqueNodeIdentifier} instead, as that is guaranteed to provide a system-wide unique value * (whereas the nodeId value is unique only context of the pubsub service). * * @see Node#getNodeID() */ protected String nodeId; /** * The service identifier for the pubsub node that is the subject of the task. */ protected String serviceId; /** * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise. */ protected NodeTask() { } /** * Constructs a new task for a specific pubsub node. * * @param node The pubsub node that this task operates on. */ protected NodeTask(@Nonnull Node node) { uniqueNodeIdentifier = node.getUniqueIdentifier(); nodeId = node.getUniqueIdentifier().getNodeId(); serviceId = node.getUniqueIdentifier().getServiceIdentifier().getServiceId(); } /** * Returns the unique identifier of the pubsub node that this task aims to update. * * Usage of this method, that provides a system-wide unique value, should generally be preferred over the use of * {@link #getNodeId()}, that returns a value that is unique only context of the pubsub service. * * @return A unique node identifier. * @see Node#getUniqueIdentifier() */ public Node.UniqueIdentifier getUniqueNodeIdentifier() { return uniqueNodeIdentifier; } /** * The node identifier, unique in context of the service, for the pubsub node that is the subject of the task. * * It is advisable to make use of {@link #getUniqueNodeIdentifier()} instead of this method, as that is guaranteed * to provide a system-wide unique value (whereas the nodeId value is unique only context of the pubsub service). * * @return a node identifier * @see #getUniqueNodeIdentifier() * @see Node#getNodeID() */ public String getNodeId() { return nodeId; } /** * Finds the pubsub node that is the subject of this task. * * Note that null, instead of a pubsub node instance, might be returned when the pubsub service is not currently * loaded in-memory on the cluster node that the task is executing on (although there is no guarantee that when this * method returns a non-null pubsub service, it was previously not loaded in-memory)! The rationale for this is that * this cluster tasks does not need to operate on data that is not in memory, as such operations are the * responsibility of the cluster node that initiates the cluster task. * * @return A pubsub node */ @Nonnull public Optional<Node> getNodeIfLoaded() { final Optional<PubSubService> svc = getServiceIfLoaded(); return svc.map(pubSubService -> pubSubService.getNode(nodeId)); } /** * Finds the pubsub service for the pubsub node that is the subject of this task. * * Note that null, instead of a pubsub service instance, might be returned when the pubsub service is not currently * loaded in-memory on the cluster node that the task is executing on (although there is no guarantee that when this * method returns a non-null pubsub service, it was previously not loaded in-memory)! The rationale for this is that * this cluster tasks does not need to operate on data that is not in memory, as such operations are the * responsibility of the cluster node that initiates the cluster task. * * @return A pubsub service */ @Nonnull public Optional<PubSubService> getServiceIfLoaded() {<FILL_FUNCTION_BODY>} @Override public Void getResult() { return null; } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeSafeUTF(out, nodeId); ExternalizableUtil.getInstance().writeSafeUTF(out, serviceId); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { nodeId = ExternalizableUtil.getInstance().readSafeUTF(in); serviceId = ExternalizableUtil.getInstance().readSafeUTF(in); uniqueNodeIdentifier = new Node.UniqueIdentifier( serviceId, nodeId ); } }
if (XMPPServer.getInstance().getPubSubModule().getServiceID().equals(serviceId)) { return Optional.of(XMPPServer.getInstance().getPubSubModule()); } else { PEPServiceManager serviceMgr = XMPPServer.getInstance().getIQPEPHandler().getServiceManager(); JID service = new JID( serviceId ); return serviceMgr.hasCachedService(service) ? Optional.of(serviceMgr.getPEPService(service)) : Optional.empty(); }
1,332
136
1,468
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/RefreshNodeTask.java
RefreshNodeTask
run
class RefreshNodeTask extends NodeTask { private static final Logger log = LoggerFactory.getLogger(RefreshNodeTask.class); /** * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise. */ public RefreshNodeTask() { } /** * Constructs a new task that refreshes a specific pubsub node. * * @param node The pubsub node that this task relates to. */ public RefreshNodeTask(@Nonnull final Node node) { super(node); } @Override public void run() {<FILL_FUNCTION_BODY>} }
// Note: this implementation should apply changes in-memory state only. It explicitly needs not update // persisted data storage, as this can be expected to be done by the cluster node that issued this task. // Applying such changes in this task would, at best, needlessly require resources. log.debug("[TASK] Refreshing node - nodeID: {}", getNodeId()); final Optional<PubSubService> optService = getServiceIfLoaded(); // This will only occur if a PEP service is not loaded on this particular cluster node. We can safely do nothing // in this case since any changes that might have been applied here will also have been applied to the database // by the cluster node where this task originated, meaning that those changes get loaded from the database when // the pubsub node is retrieved from the database in the future (OF-2077) if (!optService.isPresent()) { return; } final PubSubService service = optService.get(); XMPPServer.getInstance().getPubSubModule().getPersistenceProvider().loadNode(service, getUniqueNodeIdentifier());
175
272
447
<methods>public java.lang.String getNodeId() ,public Optional<org.jivesoftware.openfire.pubsub.Node> getNodeIfLoaded() ,public java.lang.Void getResult() ,public Optional<org.jivesoftware.openfire.pubsub.PubSubService> getServiceIfLoaded() ,public org.jivesoftware.openfire.pubsub.Node.UniqueIdentifier getUniqueNodeIdentifier() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>protected java.lang.String nodeId,protected java.lang.String serviceId,protected transient org.jivesoftware.openfire.pubsub.Node.UniqueIdentifier uniqueNodeIdentifier
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/RemoveNodeTask.java
RemoveNodeTask
run
class RemoveNodeTask extends NodeTask { private static final Logger log = LoggerFactory.getLogger(RemoveNodeTask.class); /** * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise. */ public RemoveNodeTask() { } /** * Constructs a new task that removes a specific node from a pubsub node. * * @param node The pubsub node that this task relates to. */ public RemoveNodeTask(@Nonnull final Node node) { super(node); } @Override public void run() {<FILL_FUNCTION_BODY>} }
log.debug("[TASK] Removing node - nodeID: {}", getNodeId()); final Optional<PubSubService> optService = getServiceIfLoaded(); // This will only occur if a PEP service is not loaded on this particular cluster node. We can safely do nothing // in this case since any changes that might have been applied here will also have been applied to the database // by the cluster node where this task originated, meaning that those changes get loaded from the database when // the pubsub node is retrieved from the database in the future (OF-2077) if (!optService.isPresent()) { return; } optService.get().removeNode(getNodeId());
173
175
348
<methods>public java.lang.String getNodeId() ,public Optional<org.jivesoftware.openfire.pubsub.Node> getNodeIfLoaded() ,public java.lang.Void getResult() ,public Optional<org.jivesoftware.openfire.pubsub.PubSubService> getServiceIfLoaded() ,public org.jivesoftware.openfire.pubsub.Node.UniqueIdentifier getUniqueNodeIdentifier() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>protected java.lang.String nodeId,protected java.lang.String serviceId,protected transient org.jivesoftware.openfire.pubsub.Node.UniqueIdentifier uniqueNodeIdentifier
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/cluster/SubscriptionTask.java
SubscriptionTask
toString
class SubscriptionTask extends NodeTask { /** * The ID that uniquely identifies the subscription of the user in the node. * * @see NodeSubscription#getID() */ private String subId; /** * The address of the entity that owns this subscription. * * @see NodeSubscription#getOwner() */ private JID owner; /** * The address that is going to receive the event notifications. * * @see NodeSubscription#getJID() */ private JID subJid; /** * The state of the subscription. * * @see NodeSubscription#getState() */ private NodeSubscription.State state; /** * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise. */ public SubscriptionTask() { } public SubscriptionTask(@Nonnull final NodeSubscription subscription) { super(subscription.getNode()); subId = subscription.getID(); state = subscription.getState(); owner = subscription.getOwner(); subJid = subscription.getJID(); } /** * Returns the ID that uniquely identifies the subscription of the user in the node. * * @return a unique node subscription identifier. * @see NodeSubscription#getID() */ public String getSubscriptionId() { return subId; } /** * Returns the address of the entity that owns this subscription. * * @return The address of the owner of the subscription. * @see NodeSubscription#getOwner() */ public JID getOwner() { return owner; } /** * Returns the address that is going to receive the event notifications. * * @return the address that will receive notifications. * @see NodeSubscription#getJID() */ public JID getSubscriberJid() { return subJid; } /** * Returns the state of the subscription. * * @return subscription state * @see NodeSubscription#getState() */ public NodeSubscription.State getState() { return state; } /** * Finds the pubsub node subscription that is the subject of this task. * * Note that null, instead of a pubsub node subscription instance, might be returned when the pubsub service is not * currently loaded in-memory on the cluster node that the task is executing on (although there is no guarantee that * when this method returns a non-null node subscription, it was previously not loaded in-memory)! The rationale for * this is that this cluster tasks does not need to operate on data that is not in memory, as such operations are the * responsibility of the cluster node that initiates the cluster task. * * @return a pubsub node subscription */ @Nonnull public Optional<NodeSubscription> getSubscriptionIfLoaded() { final Optional<Node> node = getNodeIfLoaded(); // When this cluster node does not have the pubsub node loaded in memory, no updates are needed (OF-2077). return node.map(value -> new NodeSubscription(value, owner, subJid, state, subId)); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); ExternalizableUtil.getInstance().writeSafeUTF(out, subId); ExternalizableUtil.getInstance().writeSerializable(out, owner); ExternalizableUtil.getInstance().writeSerializable(out, subJid); ExternalizableUtil.getInstance().writeSerializable(out, state); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); subId = ExternalizableUtil.getInstance().readSafeUTF(in); owner = (JID) ExternalizableUtil.getInstance().readSerializable(in); subJid = (JID) ExternalizableUtil.getInstance().readSerializable(in); state = (State) ExternalizableUtil.getInstance().readSerializable(in); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return getClass().getSimpleName() + " [(service=" + serviceId + "), (nodeId=" + nodeId + "), (owner=" + owner + "),(subscriber=" + subJid + "),(state=" + state + "),(id=" + subId + ")]";
1,093
78
1,171
<methods>public java.lang.String getNodeId() ,public Optional<org.jivesoftware.openfire.pubsub.Node> getNodeIfLoaded() ,public java.lang.Void getResult() ,public Optional<org.jivesoftware.openfire.pubsub.PubSubService> getServiceIfLoaded() ,public org.jivesoftware.openfire.pubsub.Node.UniqueIdentifier getUniqueNodeIdentifier() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>protected java.lang.String nodeId,protected java.lang.String serviceId,protected transient org.jivesoftware.openfire.pubsub.Node.UniqueIdentifier uniqueNodeIdentifier
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/models/AccessModel.java
AccessModel
valueOf
class AccessModel implements Serializable { public static final AccessModel whitelist = new WhitelistAccess(); public static final AccessModel open = new OpenAccess(); public static final AccessModel authorize = new AuthorizeAccess(); public static final AccessModel presence = new PresenceAccess(); public static final AccessModel roster = new RosterAccess(); /** * Returns the specific subclass of AccessModel as specified by the access * model name. If an unknown name is specified then an IllegalArgumentException * is going to be thrown. * * @param name the name of the subsclass. * @return the specific subclass of AccessModel as specified by the access * model name. */ public static AccessModel valueOf(String name) {<FILL_FUNCTION_BODY>} /** * Returns the name as defined by the JEP-60 spec. * * @return the name as defined by the JEP-60 spec. */ public abstract String getName(); /** * Returns true if the entity is allowed to subscribe to the specified node. * * @param node the node that the subscriber is trying to subscribe to. * @param owner the JID of the owner of the subscription. * @param subscriber the JID of the subscriber. * @return true if the subscriber is allowed to subscribe to the specified node. */ public abstract boolean canSubscribe(Node node, JID owner, JID subscriber); /** * Returns true if the entity is allowed to get the node published items. * * @param node the node that the entity is trying to get the node's items. * @param owner the JID of the owner of the subscription. * @param subscriber the JID of the subscriber. * @return true if the subscriber is allowed to get the node's published items. */ public abstract boolean canAccessItems(Node node, JID owner, JID subscriber); /** * Returns the error condition that should be returned to the subscriber when * subscription is not allowed. * * @return the error condition that should be returned to the subscriber when * subscription is not allowed. */ public abstract PacketError.Condition getSubsriptionError(); /** * Returns the error element that should be returned to the subscriber as * error detail when subscription is not allowed. The returned element is created * each time this message is sent so it is safe to include the returned element in * the parent element. * * @return the error element that should be returned to the subscriber as * error detail when subscription is not allowed. */ public abstract Element getSubsriptionErrorDetail(); /** * Returns true if the new subscription should be authorized by a node owner. * * @return true if the new subscription should be authorized by a node owner. */ public abstract boolean isAuthorizationRequired(); }
if ("open".equals(name)) { return open; } else if ("whitelist".equals(name)) { return whitelist; } else if ("authorize".equals(name)) { return authorize; } else if ("presence".equals(name)) { return presence; } else if ("roster".equals(name)) { return roster; } throw new IllegalArgumentException("Unknown access model: " + name);
731
127
858
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/models/AuthorizeAccess.java
AuthorizeAccess
canAccessItems
class AuthorizeAccess extends AccessModel { AuthorizeAccess() { } @Override public boolean canSubscribe(Node node, JID owner, JID subscriber) { return true; } @Override public boolean canAccessItems(Node node, JID owner, JID subscriber) {<FILL_FUNCTION_BODY>} @Override public String getName() { return "authorize"; } @Override public PacketError.Condition getSubsriptionError() { return PacketError.Condition.not_authorized; } @Override public Element getSubsriptionErrorDetail() { return DocumentHelper.createElement(QName.get("not-subscribed", "http://jabber.org/protocol/pubsub#errors")); } @Override public boolean isAuthorizationRequired() { return true; } }
// Let node owners and sysadmins always get node items if (node.isAdmin(owner)) { return true; } NodeAffiliate nodeAffiliate = node.getAffiliate(owner); if (nodeAffiliate == null) { // This is an unknown entity to the node so deny access return false; } // Any subscription of this entity that was approved will give him access // to retrieve the node items for (NodeSubscription subscription : nodeAffiliate.getSubscriptions()) { if (subscription.isActive()) { return true; } } // No approved subscription was found so deny access return false;
234
177
411
<methods>public non-sealed void <init>() ,public abstract boolean canAccessItems(org.jivesoftware.openfire.pubsub.Node, JID, JID) ,public abstract boolean canSubscribe(org.jivesoftware.openfire.pubsub.Node, JID, JID) ,public abstract java.lang.String getName() ,public abstract PacketError.Condition getSubsriptionError() ,public abstract Element getSubsriptionErrorDetail() ,public abstract boolean isAuthorizationRequired() ,public static org.jivesoftware.openfire.pubsub.models.AccessModel valueOf(java.lang.String) <variables>public static final org.jivesoftware.openfire.pubsub.models.AccessModel authorize,public static final org.jivesoftware.openfire.pubsub.models.AccessModel open,public static final org.jivesoftware.openfire.pubsub.models.AccessModel presence,public static final org.jivesoftware.openfire.pubsub.models.AccessModel roster,public static final org.jivesoftware.openfire.pubsub.models.AccessModel whitelist
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/models/OnlyPublishers.java
OnlyPublishers
canPublish
class OnlyPublishers extends PublisherModel { @Override public boolean canPublish(Node node, JID entity) {<FILL_FUNCTION_BODY>} @Override public String getName() { return "publishers"; } }
NodeAffiliate nodeAffiliate = node.getAffiliate(entity); return nodeAffiliate != null && ( nodeAffiliate.getAffiliation() == NodeAffiliate.Affiliation.publisher || nodeAffiliate.getAffiliation() == NodeAffiliate.Affiliation.owner);
68
92
160
<methods>public non-sealed void <init>() ,public abstract boolean canPublish(org.jivesoftware.openfire.pubsub.Node, JID) ,public abstract java.lang.String getName() ,public static org.jivesoftware.openfire.pubsub.models.PublisherModel valueOf(java.lang.String) <variables>public static final org.jivesoftware.openfire.pubsub.models.PublisherModel open,public static final org.jivesoftware.openfire.pubsub.models.PublisherModel publishers,public static final org.jivesoftware.openfire.pubsub.models.PublisherModel subscribers
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/models/OnlySubscribers.java
OnlySubscribers
canPublish
class OnlySubscribers extends PublisherModel { @Override public boolean canPublish(Node node, JID entity) {<FILL_FUNCTION_BODY>} @Override public String getName() { return "subscribers"; } }
NodeAffiliate nodeAffiliate = node.getAffiliate(entity); // Deny access if user does not have any relation with the node or is an outcast if (nodeAffiliate == null || nodeAffiliate.getAffiliation() == NodeAffiliate.Affiliation.outcast) { return false; } // Grant access if user is an owner of publisher if (nodeAffiliate.getAffiliation() == NodeAffiliate.Affiliation.publisher || nodeAffiliate.getAffiliation() == NodeAffiliate.Affiliation.owner) { return true; } // Grant access if at least one subscription of this user was approved for (NodeSubscription subscription : nodeAffiliate.getSubscriptions()) { if (subscription.isActive()) { return true; } } return false;
72
233
305
<methods>public non-sealed void <init>() ,public abstract boolean canPublish(org.jivesoftware.openfire.pubsub.Node, JID) ,public abstract java.lang.String getName() ,public static org.jivesoftware.openfire.pubsub.models.PublisherModel valueOf(java.lang.String) <variables>public static final org.jivesoftware.openfire.pubsub.models.PublisherModel open,public static final org.jivesoftware.openfire.pubsub.models.PublisherModel publishers,public static final org.jivesoftware.openfire.pubsub.models.PublisherModel subscribers
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/models/PresenceAccess.java
PresenceAccess
canSubscribe
class PresenceAccess extends AccessModel { private static final Logger Log = LoggerFactory.getLogger(PresenceAccess.class); PresenceAccess() { } @Override public boolean canSubscribe(Node node, JID owner, JID subscriber) {<FILL_FUNCTION_BODY>} @Override public boolean canAccessItems(Node node, JID owner, JID subscriber) { return canSubscribe(node, owner, subscriber); } @Override public String getName() { return "presence"; } @Override public PacketError.Condition getSubsriptionError() { return PacketError.Condition.not_authorized; } @Override public Element getSubsriptionErrorDetail() { return DocumentHelper.createElement(QName.get("presence-subscription-required", "http://jabber.org/protocol/pubsub#errors")); } @Override public boolean isAuthorizationRequired() { return false; } }
// Let node owners and sysadmins always subcribe to the node if (node.isAdmin(owner)) { return true; } XMPPServer server = XMPPServer.getInstance(); for (JID nodeOwner : node.getOwners()) { // Give access to the owner of the roster :) if (nodeOwner.equals(owner)) { return true; } // Check that the node owner is a local user if (server.isLocal(nodeOwner)) { try { Roster roster = server.getRosterManager().getRoster(nodeOwner.getNode()); RosterItem item = roster.getRosterItem(owner); // Check that the subscriber is subscribe to the node owner's presence return item != null && (RosterItem.SUB_BOTH == item.getSubStatus() || RosterItem.SUB_FROM == item.getSubStatus()); } catch (UserNotFoundException e) { // Do nothing } } else { // Owner of the node is a remote user. This should never happen. Log.warn("Node with access model Presence has a remote user as owner: {}",node.getUniqueIdentifier()); } } return false;
268
318
586
<methods>public non-sealed void <init>() ,public abstract boolean canAccessItems(org.jivesoftware.openfire.pubsub.Node, JID, JID) ,public abstract boolean canSubscribe(org.jivesoftware.openfire.pubsub.Node, JID, JID) ,public abstract java.lang.String getName() ,public abstract PacketError.Condition getSubsriptionError() ,public abstract Element getSubsriptionErrorDetail() ,public abstract boolean isAuthorizationRequired() ,public static org.jivesoftware.openfire.pubsub.models.AccessModel valueOf(java.lang.String) <variables>public static final org.jivesoftware.openfire.pubsub.models.AccessModel authorize,public static final org.jivesoftware.openfire.pubsub.models.AccessModel open,public static final org.jivesoftware.openfire.pubsub.models.AccessModel presence,public static final org.jivesoftware.openfire.pubsub.models.AccessModel roster,public static final org.jivesoftware.openfire.pubsub.models.AccessModel whitelist
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/models/PublisherModel.java
PublisherModel
valueOf
class PublisherModel implements Serializable { public final static PublisherModel open = new OpenPublisher(); public final static PublisherModel publishers = new OnlyPublishers(); public final static PublisherModel subscribers = new OnlySubscribers(); /** * Returns the specific subclass of PublisherModel as specified by the publisher * model name. If an unknown name is specified then an IllegalArgumentException * is going to be thrown. * * @param name the name of the subsclass. * @return the specific subclass of PublisherModel as specified by the access * model name. */ public static PublisherModel valueOf(String name) {<FILL_FUNCTION_BODY>} /** * Returns the name as defined by the JEP-60 spec. * * @return the name as defined by the JEP-60 spec. */ public abstract String getName(); /** * Returns true if the entity is allowed to publish items to the specified node. * * @param node the node that may get a new published item by the specified entity. * @param entity the JID of the entity that wants to publish an item to the node. * @return true if the subscriber is allowed to publish items to the specified node. */ public abstract boolean canPublish(Node node, JID entity); }
if ("open".equals(name)) { return open; } else if ("publishers".equals(name)) { return publishers; } else if ("subscribers".equals(name)) { return subscribers; } throw new IllegalArgumentException("Unknown publisher model: " + name);
338
83
421
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/models/RosterAccess.java
RosterAccess
canSubscribe
class RosterAccess extends AccessModel { private static final Logger Log = LoggerFactory.getLogger(RosterAccess.class); RosterAccess() { } @Override public boolean canSubscribe(Node node, JID owner, JID subscriber) {<FILL_FUNCTION_BODY>} @Override public boolean canAccessItems(Node node, JID owner, JID subscriber) { return canSubscribe(node, owner, subscriber); } @Override public String getName() { return "roster"; } @Override public PacketError.Condition getSubsriptionError() { return PacketError.Condition.not_authorized; } @Override public Element getSubsriptionErrorDetail() { return DocumentHelper.createElement( QName.get("not-in-roster-group", "http://jabber.org/protocol/pubsub#errors")); } @Override public boolean isAuthorizationRequired() { return false; } }
// Let node owners and sysadmins always subscribe to the node if (node.isAdmin(owner)) { return true; } for (JID nodeOwner : node.getOwners()) { if (nodeOwner.equals(owner)) { return true; } } // Check that the subscriber is a local user XMPPServer server = XMPPServer.getInstance(); if (server.isLocal(owner)) { GroupManager gMgr = GroupManager.getInstance(); Collection<String> nodeGroups = node.getRosterGroupsAllowed(); for (String groupName : nodeGroups) { try { Group group = gMgr.getGroup(groupName); // access allowed if the node group is visible to the subscriber if (server.getRosterManager().isGroupVisible(group, owner)) { return true; } } catch (GroupNotFoundException gnfe){ // ignore } } } else { // Subscriber is a remote user. This should never happen. Log.warn("Node with access model Roster has a remote user as subscriber: {}", node.getUniqueIdentifier()); } return false;
269
304
573
<methods>public non-sealed void <init>() ,public abstract boolean canAccessItems(org.jivesoftware.openfire.pubsub.Node, JID, JID) ,public abstract boolean canSubscribe(org.jivesoftware.openfire.pubsub.Node, JID, JID) ,public abstract java.lang.String getName() ,public abstract PacketError.Condition getSubsriptionError() ,public abstract Element getSubsriptionErrorDetail() ,public abstract boolean isAuthorizationRequired() ,public static org.jivesoftware.openfire.pubsub.models.AccessModel valueOf(java.lang.String) <variables>public static final org.jivesoftware.openfire.pubsub.models.AccessModel authorize,public static final org.jivesoftware.openfire.pubsub.models.AccessModel open,public static final org.jivesoftware.openfire.pubsub.models.AccessModel presence,public static final org.jivesoftware.openfire.pubsub.models.AccessModel roster,public static final org.jivesoftware.openfire.pubsub.models.AccessModel whitelist
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/pubsub/models/WhitelistAccess.java
WhitelistAccess
canSubscribe
class WhitelistAccess extends AccessModel { WhitelistAccess() { } @Override public boolean canSubscribe(Node node, JID owner, JID subscriber) {<FILL_FUNCTION_BODY>} @Override public boolean canAccessItems(Node node, JID owner, JID subscriber) { return canSubscribe(node, owner, subscriber); } @Override public String getName() { return "whitelist"; } @Override public PacketError.Condition getSubsriptionError() { return PacketError.Condition.not_allowed; } @Override public Element getSubsriptionErrorDetail() { return DocumentHelper.createElement( QName.get("closed-node", "http://jabber.org/protocol/pubsub#errors")); } @Override public boolean isAuthorizationRequired() { return false; } }
// Let node owners and sysadmins always subcribe to the node if (node.isAdmin(owner)) { return true; } // User is in the whitelist if he has an affiliation and it is not of type outcast NodeAffiliate nodeAffiliate = node.getAffiliate(owner); return nodeAffiliate != null && nodeAffiliate.getAffiliation() != NodeAffiliate.Affiliation.outcast;
244
127
371
<methods>public non-sealed void <init>() ,public abstract boolean canAccessItems(org.jivesoftware.openfire.pubsub.Node, JID, JID) ,public abstract boolean canSubscribe(org.jivesoftware.openfire.pubsub.Node, JID, JID) ,public abstract java.lang.String getName() ,public abstract PacketError.Condition getSubsriptionError() ,public abstract Element getSubsriptionErrorDetail() ,public abstract boolean isAuthorizationRequired() ,public static org.jivesoftware.openfire.pubsub.models.AccessModel valueOf(java.lang.String) <variables>public static final org.jivesoftware.openfire.pubsub.models.AccessModel authorize,public static final org.jivesoftware.openfire.pubsub.models.AccessModel open,public static final org.jivesoftware.openfire.pubsub.models.AccessModel presence,public static final org.jivesoftware.openfire.pubsub.models.AccessModel roster,public static final org.jivesoftware.openfire.pubsub.models.AccessModel whitelist
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/roster/RosterEventDispatcher.java
RosterEventDispatcher
rosterLoaded
class RosterEventDispatcher { private static final Logger Log = LoggerFactory.getLogger(RosterEventDispatcher.class); private static List<RosterEventListener> listeners = new CopyOnWriteArrayList<>(); /** * Registers a listener to receive events. * * @param listener the listener. */ public static void addListener(RosterEventListener listener) { if (listener == null) { throw new NullPointerException(); } listeners.add(listener); } /** * Unregisters a listener to receive events. * * @param listener the listener. */ public static void removeListener(RosterEventListener listener) { listeners.remove(listener); } /** * Notifies the listeners that a roster has just been loaded. * * @param roster the loaded roster. */ public static void rosterLoaded(Roster roster) {<FILL_FUNCTION_BODY>} /** * Notifies listeners that a contact is about to be added to a roster. New contacts * may be persisted to the database or not. Listeners may indicate that contact about * to be persisted should not be persisted. Only one listener is needed to return * {@code false} so that the contact is not persisted. * * @param roster the roster that was updated. * @param item the new roster item. * @param persistent true if the new contact is going to be saved to the database. * @return false if the contact should not be persisted to the database. */ public static boolean addingContact(Roster roster, RosterItem item, boolean persistent) { boolean answer = persistent; if (!listeners.isEmpty()) { for (RosterEventListener listener : listeners) { try { if (!listener.addingContact(roster, item, persistent)) { answer = false; } } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'addingContact' event!", e); } } } return answer; } /** * Notifies the listeners that a contact has been added to a roster. * * @param roster the roster that was updated. * @param item the new roster item. */ public static void contactAdded(Roster roster, RosterItem item) { if (!listeners.isEmpty()) { for (RosterEventListener listener : listeners) { try { listener.contactAdded(roster, item); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'contactAdded' event!", e); } } } } /** * Notifies the listeners that a contact has been updated. * * @param roster the roster that was updated. * @param item the updated roster item. */ public static void contactUpdated(Roster roster, RosterItem item) { if (!listeners.isEmpty()) { for (RosterEventListener listener : listeners) { try { listener.contactUpdated(roster, item); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'contactUpdated' event!", e); } } } } /** * Notifies the listeners that a contact has been deleted from a roster. * * @param roster the roster that was updated. * @param item the roster item that was deleted. */ public static void contactDeleted(Roster roster, RosterItem item) { if (!listeners.isEmpty()) { for (RosterEventListener listener : listeners) { try { listener.contactDeleted(roster, item); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'contactDeleted' event!", e); } } } } }
if (!listeners.isEmpty()) { for (RosterEventListener listener : listeners) { try { listener.rosterLoaded(roster); } catch (Exception e) { Log.warn("An exception occurred while dispatching a 'rosterLoaded' event!", e); } } }
1,007
84
1,091
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/sasl/AnonymousSaslServer.java
AnonymousSaslServer
getNegotiatedProperty
class AnonymousSaslServer implements SaslServer { public static final SystemProperty<Boolean> ENABLED = SystemProperty.Builder.ofType(Boolean.class) .setKey("xmpp.auth.anonymous") .setDefaultValue(Boolean.FALSE) .setDynamic(Boolean.TRUE) .build(); public static final String NAME = "ANONYMOUS"; private boolean complete = false; private LocalSession session; public AnonymousSaslServer( LocalSession session ) { this.session = session; } @Override public String getMechanismName() { return NAME; } @Override public byte[] evaluateResponse( byte[] response ) throws SaslException { if ( isComplete() ) { throw new IllegalStateException( "Authentication exchange already completed." ); } complete = true; // Verify server-wide policy. if (!ENABLED.getValue()) { throw new SaslException( "Authentication failed" ); } // Verify that client can connect from his IP address. final Connection connection = session.getConnection(); assert connection != null; // While the peer is performing a SASL negotiation, the connection can't be null. final boolean forbidAccess = !LocalClientSession.isAllowedAnonymous(connection); if ( forbidAccess ) { throw new SaslException( "Authentication failed" ); } // Just accept the authentication :) return null; } @Override public boolean isComplete() { return complete; } @Override public String getAuthorizationID() { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } return null; // Anonymous! } @Override public byte[] unwrap( byte[] incoming, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); } @Override public byte[] wrap( byte[] outgoing, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); } @Override public Object getNegotiatedProperty( String propName ) {<FILL_FUNCTION_BODY>} @Override public void dispose() throws SaslException { complete = false; session = null; } }
if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } if ( propName.equals( Sasl.QOP ) ) { return "auth"; } else { return null; }
740
77
817
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/sasl/ExternalClientSaslServer.java
ExternalClientSaslServer
evaluateResponse
class ExternalClientSaslServer implements SaslServer { public static final SystemProperty<Boolean> PROPERTY_SASL_EXTERNAL_CLIENT_SUPPRESS_MATCHING_REALMNAME = SystemProperty.Builder .ofType( Boolean.class ) .setKey( "xmpp.auth.sasl.external.client.suppress-matching-realmname" ) .setDefaultValue( true ) .setDynamic( true ) .build(); public static final Logger Log = LoggerFactory.getLogger( ExternalClientSaslServer.class ); public static final String NAME = "EXTERNAL"; private boolean complete = false; private String authorizationID = null; private LocalClientSession session; public ExternalClientSaslServer( LocalClientSession session ) throws SaslException { this.session = session; } @Override public String getMechanismName() { return NAME; } @Override public byte[] evaluateResponse( @Nonnull final byte[] response ) throws SaslException {<FILL_FUNCTION_BODY>} @Override public boolean isComplete() { return complete; } @Override public String getAuthorizationID() { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } return authorizationID; } @Override public byte[] unwrap( byte[] incoming, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); } @Override public byte[] wrap( byte[] outgoing, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); } @Override public Object getNegotiatedProperty( String propName ) { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } if ( propName.equals( Sasl.QOP ) ) { return "auth"; } else { return null; } } @Override public void dispose() throws SaslException { complete = false; authorizationID = null; session = null; } }
if ( isComplete() ) { throw new IllegalStateException( "Authentication exchange already completed." ); } if (response.length == 0 && session.getSessionData(SASLAuthentication.SASL_LAST_RESPONSE_WAS_PROVIDED_BUT_EMPTY) != null) { // No initial response. Send a challenge to get one, per RFC 4422 appendix-A. return new byte[ 0 ]; } // There will be no further steps. Either authentication succeeds or fails, but in any case, we're done. complete = true; final Connection connection = session.getConnection(); assert connection != null; // While the peer is performing a SASL negotiation, the connection can't be null. Certificate[] peerCertificates = connection.getPeerCertificates(); if ( peerCertificates == null || peerCertificates.length < 1 ) { throw new SaslException( "No peer certificates." ); } final X509Certificate trusted; if ( SASLAuthentication.SKIP_PEER_CERT_REVALIDATION_CLIENT.getValue() ) { // Trust that the peer certificate has been validated when TLS got established. trusted = (X509Certificate) peerCertificates[0]; } else { // Re-evaluate the validity of the peer certificate. final TrustStore trustStore = connection.getConfiguration().getTrustStore(); trusted = trustStore.getEndEntityCertificate( peerCertificates ); } if ( trusted == null ) { throw new SaslException( "Certificate chain of peer is not trusted." ); } // Process client authentication identities / principals. final ArrayList<String> authenticationIdentities = new ArrayList<>(); authenticationIdentities.addAll( CertificateManager.getClientIdentities( trusted ) ); String authenticationIdentity; switch ( authenticationIdentities.size() ) { case 0: authenticationIdentity = ""; break; default: Log.debug( "More than one authentication identity found, using the first one." ); // intended fall-through; case 1: authenticationIdentity = authenticationIdentities.get( 0 ); break; } // Process requested username to act as. String authorizationIdentity; if ( response.length > 0 ) { authorizationIdentity = new String( response, StandardCharsets.UTF_8 ); if( PROPERTY_SASL_EXTERNAL_CLIENT_SUPPRESS_MATCHING_REALMNAME.getValue() && authorizationIdentity.contains("@") ) { String authzUser = authorizationIdentity.substring(0,authorizationIdentity.lastIndexOf("@")); String authzRealm = authorizationIdentity.substring((authorizationIdentity.lastIndexOf("@")+1)); if ( XMPPServer.getInstance().getServerInfo().getXMPPDomain().equals( authzRealm ) ) { authorizationIdentity = authzUser; } } } else { authorizationIdentity = null; } if ( authorizationIdentity == null || authorizationIdentity.length() == 0 ) { // No authorization identity was provided, according to XEP-0178 we need to: // * attempt to get it from the cert first // * have the server assign one // There shouldn't be more than a few authentication identities in here. One ideally. We set authcid to the // first one in the list to have a sane default. If this list is empty, then the cert had no identity at all, which will // cause an authorization failure. for ( String authcid : authenticationIdentities ) { final String mappedUsername = AuthorizationManager.map( authcid ); if ( !mappedUsername.equals( authcid ) ) { authorizationIdentity = mappedUsername; authenticationIdentity = authcid; break; } } if ( authorizationIdentity == null || authorizationIdentity.length() == 0 ) { // Still no username to act as. Punt. authorizationIdentity = authenticationIdentity; } Log.debug( "No username requested, using: {}", authorizationIdentity ); } // It's possible that either/both authzid and authcid are null here. The providers should not allow a null authorization. if ( AuthorizationManager.authorize( authorizationIdentity, authenticationIdentity ) ) { Log.debug( "Authcid {} authorized to authzid (username) {}", authenticationIdentity, authorizationIdentity ); authorizationID = authorizationIdentity; return null; // Success! } throw new SaslException();
716
1,189
1,905
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/sasl/ExternalServerSaslServer.java
ExternalServerSaslServer
evaluateResponse
class ExternalServerSaslServer implements SaslServer { private static final Logger Log = LoggerFactory.getLogger(ExternalServerSaslServer.class); /** * This property controls if the inbound connection is required to provide an authorization identity in the SASL * EXTERNAL handshake (as part of an `auth` element). In older XMPP specifications, it was not required to have a * `from` attribute on the stream, making the authzid a required part of the handshake. * * @see <a href="https://igniterealtime.atlassian.net/browse/OF-2639">Issue OF-2639</a> */ public static final SystemProperty<Boolean> PROPERTY_SASL_EXTERNAL_SERVER_REQUIRE_AUTHZID = SystemProperty.Builder .ofType( Boolean.class ) .setKey( "xmpp.auth.sasl.external.server.require-authzid" ) .setDefaultValue( false ) .setDynamic( true ) .build(); public static final String NAME = "EXTERNAL"; private boolean complete = false; private String authorizationID = null; private LocalIncomingServerSession session; public ExternalServerSaslServer( LocalIncomingServerSession session ) throws SaslException { this.session = session; } @Override public String getMechanismName() { return NAME; } @Override public byte[] evaluateResponse( @Nonnull final byte[] response ) throws SaslException {<FILL_FUNCTION_BODY>} @Override public boolean isComplete() { return complete; } @Override public String getAuthorizationID() { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } return authorizationID; } @Override public byte[] unwrap( byte[] incoming, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); } @Override public byte[] wrap( byte[] outgoing, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); } @Override public Object getNegotiatedProperty( String propName ) { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } if ( propName.equals( Sasl.QOP ) ) { return "auth"; } else { return null; } } @Override public void dispose() throws SaslException { complete = false; authorizationID = null; session = null; } }
if ( isComplete() ) { throw new IllegalStateException( "Authentication exchange already completed." ); } // The value as sent to us in the 'from' attribute of the stream element sent by the remote server. final String defaultIdentity = session.getDefaultIdentity(); // RFC 6120 Section 4.7.1: // "Because a server is a "public entity" on the XMPP network, it MUST include the 'from' attribute after the // confidentiality and integrity of the stream are protected via TLS or an equivalent security layer." // // When doing SASL EXTERNAL, TLS must already have been negotiated, which means that the 'from' attribute must have been set. if (defaultIdentity == null || defaultIdentity.isEmpty()) { throw new SaslFailureException(Failure.NOT_AUTHORIZED, "Peer does not provide 'from' attribute value on stream."); } final String requestedId; if (response.length == 0 && session.getSessionData(SASLAuthentication.SASL_LAST_RESPONSE_WAS_PROVIDED_BUT_EMPTY) == null) { if (PROPERTY_SASL_EXTERNAL_SERVER_REQUIRE_AUTHZID.getValue()) { // No initial response. Send a challenge to get one, per RFC 4422 appendix-A. return new byte[0]; } else { requestedId = defaultIdentity; } } else { requestedId = new String( response, StandardCharsets.UTF_8 ); } complete = true; Log.trace("Completing handshake with '{}' using authzid value: '{}'", defaultIdentity, requestedId); // Added for backwards compatibility. Not required by XMPP, but versions of Openfire prior to 4.8.0 did require the authzid to be present. if (SASLAuthentication.EXTERNAL_S2S_REQUIRE_AUTHZID.getValue() && requestedId.isEmpty()) { throw new SaslFailureException(Failure.INVALID_AUTHZID, "Peer does not provide authzid, which is required by configuration."); } // When an authorization identity is provided, make sure that it matches the 'from' value from the session stream. if (!requestedId.isEmpty() && !requestedId.equals(defaultIdentity)) { throw new SaslFailureException(Failure.INVALID_AUTHZID, "Stream 'from' attribute value '" + defaultIdentity + "' does not equal SASL authzid '" + requestedId + "'"); } if (!SASLAuthentication.verifyCertificates(session.getConnection().getPeerCertificates(), defaultIdentity, true)) { throw new SaslFailureException(Failure.NOT_AUTHORIZED, "Server-to-Server certificate verification failed."); } authorizationID = defaultIdentity; Log.trace("Successfully authenticated '{}'", authorizationID); return null; // Success!
847
761
1,608
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/sasl/JiveSharedSecretSaslServer.java
JiveSharedSecretSaslServer
getNegotiatedProperty
class JiveSharedSecretSaslServer implements SaslServer { public static final String NAME = "JIVE-SHAREDSECRET"; private boolean complete = false; @Override public String getMechanismName() { return NAME; } @Override public byte[] evaluateResponse( byte[] response ) throws SaslException { if ( isComplete() ) { throw new IllegalStateException( "Authentication exchange already completed." ); } if ( response == null || response.length == 0 ) { // No info was provided so send a challenge to get it. return new byte[ 0 ]; } complete = true; // Parse data and obtain username & password. final StringTokenizer tokens = new StringTokenizer( new String( response, StandardCharsets.UTF_8 ), "\0" ); tokens.nextToken(); final String secretDigest = tokens.nextToken(); if ( authenticateSharedSecret( secretDigest ) ) { return null; // Success! } else { // Otherwise, authentication failed. throw new SaslException( "Authentication failed" ); } } @Override public boolean isComplete() { return complete; } @Override public String getAuthorizationID() { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } return null; // Anonymous! } @Override public byte[] unwrap( byte[] incoming, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); } @Override public byte[] wrap( byte[] outgoing, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); } @Override public Object getNegotiatedProperty( String propName ) {<FILL_FUNCTION_BODY>} @Override public void dispose() throws SaslException { complete = false; } /** * Returns true if the supplied digest matches the shared secret value. The digest must be an MD5 hash of the secret * key, encoded as hex. This value is supplied by clients attempting shared secret authentication. * * @param digest the MD5 hash of the secret key, encoded as hex. * @return true if authentication succeeds. */ public static boolean authenticateSharedSecret( String digest ) { if ( !isSharedSecretAllowed() ) { return false; } return StringUtils.hash( getSharedSecret() ).equals( digest ); } /** * Returns true if shared secret authentication is enabled. Shared secret authentication creates an anonymous * session, but requires that the authenticating entity know a shared secret key. The client sends a digest of the * secret key, which is compared against a digest of the local shared key. * * @return true if shared secret authentication is enabled. */ public static boolean isSharedSecretAllowed() { return JiveGlobals.getBooleanProperty( "xmpp.auth.sharedSecretEnabled" ); } /** * Returns the shared secret value, or {@code null} if shared secret authentication is disabled. If this is the * first time the shared secret value has been requested (and shared secret auth is enabled), the key will be * randomly generated and stored in the property {@code xmpp.auth.sharedSecret}. * * @return the shared secret value. */ public static String getSharedSecret() { if ( !isSharedSecretAllowed() ) { return null; } String sharedSecret = JiveGlobals.getProperty( "xmpp.auth.sharedSecret" ); if ( sharedSecret == null ) { sharedSecret = StringUtils.randomString( 8 ); JiveGlobals.setProperty( "xmpp.auth.sharedSecret", sharedSecret ); } return sharedSecret; } /** * Sets whether shared secret authentication is enabled. Shared secret authentication creates an anonymous session, * but requires that the authenticating entity know a shared secret key. The client sends a digest of the secret * key, which is compared against a digest of the local shared key. * * @param sharedSecretAllowed true if shared secret authentication should be enabled. */ public static void setSharedSecretAllowed( boolean sharedSecretAllowed ) { JiveGlobals.setProperty( "xmpp.auth.sharedSecretEnabled", sharedSecretAllowed ? "true" : "false" ); } }
if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } if ( propName.equals( Sasl.QOP ) ) { return "auth"; } else { return null; }
1,280
77
1,357
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/sasl/SaslServerFactoryImpl.java
SaslServerFactoryImpl
createSaslServer
class SaslServerFactoryImpl implements SaslServerFactory { private final static Logger Log = LoggerFactory.getLogger( SaslServerFactoryImpl.class ); /** * All mechanisms provided by this factory. */ private final Set<Mechanism> allMechanisms; public SaslServerFactoryImpl() { allMechanisms = new HashSet<>(); allMechanisms.add( new Mechanism( "ANONYMOUS", true, true ) ); allMechanisms.add( new Mechanism( "PLAIN", false, true ) ); allMechanisms.add( new Mechanism( "SCRAM-SHA-1", false, false ) ); allMechanisms.add( new Mechanism( "JIVE-SHAREDSECRET", true, false ) ); allMechanisms.add( new Mechanism( "EXTERNAL", false, false ) ); } @Override public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException {<FILL_FUNCTION_BODY>} @Override public String[] getMechanismNames( Map<String, ?> props ) { final Set<String> result = new HashSet<>(); for ( final Mechanism mechanism : allMechanisms ) { if ( props != null ) { if ( mechanism.allowsAnonymous && props.containsKey( Sasl.POLICY_NOANONYMOUS ) && Boolean.parseBoolean( (String) props.get( Sasl.POLICY_NOANONYMOUS ) ) ) { // Do not include a mechanism that allows anonymous authentication when the 'no anonymous' policy is set. continue; } if ( mechanism.isPlaintext && props.containsKey( Sasl.POLICY_NOPLAINTEXT ) && Boolean.parseBoolean( (String) props.get( Sasl.POLICY_NOPLAINTEXT ) ) ) { // Do not include a mechanism that is susceptible to simple plain passive attacks when the 'no plaintext' policy is set. continue; } } // Mechanism passed all filters. It should be part of the result. result.add( mechanism.name ); } return result.toArray( new String[ result.size() ] ); } private static class Mechanism { final String name; final boolean allowsAnonymous; final boolean isPlaintext; private Mechanism( String name, boolean allowsAnonymous, boolean isPlaintext ) { this.name = name; this.allowsAnonymous = allowsAnonymous; this.isPlaintext = isPlaintext; } } }
if ( !Arrays.asList( getMechanismNames( props )).contains( mechanism ) ) { Log.debug( "This implementation is unable to create a SaslServer instance for the {} mechanism using the provided properties.", mechanism ); return null; } switch ( mechanism.toUpperCase() ) { case "PLAIN": if ( cbh == null ) { Log.debug( "Unable to instantiate {} SaslServer: A callbackHandler with support for Password, Name, and AuthorizeCallback required.", mechanism ); return null; } return new SaslServerPlainImpl( protocol, serverName, props, cbh ); case "SCRAM-SHA-1": return new ScramSha1SaslServer(); case "ANONYMOUS": if ( !props.containsKey( LocalSession.class.getCanonicalName() ) ) { Log.debug( "Unable to instantiate {} SaslServer: Provided properties do not contain a LocalSession instance.", mechanism ); return null; } else { final LocalSession session = (LocalSession) props.get( LocalSession.class.getCanonicalName() ); return new AnonymousSaslServer( session ); } case "EXTERNAL": if ( !props.containsKey( LocalSession.class.getCanonicalName() ) ) { Log.debug( "Unable to instantiate {} SaslServer: Provided properties do not contain a LocalSession instance.", mechanism ); return null; } else { final Object session = props.get( LocalSession.class.getCanonicalName() ); if ( session instanceof LocalClientSession ) { return new ExternalClientSaslServer( (LocalClientSession) session ); } if ( session instanceof LocalIncomingServerSession ) { return new ExternalServerSaslServer( (LocalIncomingServerSession) session ); } Log.debug( "Unable to instantiate {} Sasl Server: Provided properties contains neither LocalClientSession nor LocalIncomingServerSession instance.", mechanism ); return null; } case JiveSharedSecretSaslServer.NAME: return new JiveSharedSecretSaslServer(); default: throw new IllegalStateException(); // Fail fast - this should not be possible, as the first check in this method already verifies wether the mechanism is supported. }
713
613
1,326
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/sasl/SaslServerPlainImpl.java
SaslServerPlainImpl
evaluateResponse
class SaslServerPlainImpl implements SaslServer { /** * Authentication identity (identity whose password will be used). */ private String authcid; /** * Authorization identity (identity to act as). Derived from principal if not specifically set by the peer. */ private String authzid; private String password; private CallbackHandler cbh; private boolean completed; private boolean aborted; private int counter; public SaslServerPlainImpl(String protocol, String serverFqdn, Map props, CallbackHandler cbh) throws SaslException { this.cbh = cbh; this.completed = false; this.counter = 0; } /** * Returns the IANA-registered mechanism name of this SASL server. * ("PLAIN"). * @return A non-null string representing the IANA-registered mechanism name. */ @Override public String getMechanismName() { return "PLAIN"; } /** * Evaluates the response data and generates a challenge. * * If a response is received from the client during the authentication * process, this method is called to prepare an appropriate next * challenge to submit to the client. The challenge is null if the * authentication has succeeded and no more challenge data is to be sent * to the client. It is non-null if the authentication must be continued * by sending a challenge to the client, or if the authentication has * succeeded but challenge data needs to be processed by the client. * {@code isComplete()} should be called * after each call to {@code evaluateResponse()},to determine if any further * response is needed from the client. * * @param response The non-null (but possibly empty) response sent * by the client. * * @return The possibly null challenge to send to the client. * It is null if the authentication has succeeded and there is * no more challenge data to be sent to the client. * @exception SaslException If an error occurred while processing * the response or generating a challenge. */ @Override public byte[] evaluateResponse(byte[] response) throws SaslException {<FILL_FUNCTION_BODY>} /** * Determines whether the authentication exchange has completed. * This method is typically called after each invocation of * {@code evaluateResponse()} to determine whether the * authentication has completed successfully or should be continued. * @return true if the authentication exchange has completed; false otherwise. */ @Override public boolean isComplete() { return completed; } /** * Reports the authorization ID in effect for the client of this * session. * This method can only be called if isComplete() returns true. * @return The authorization ID of the client. * @exception IllegalStateException if this authentication session has not completed */ @Override public String getAuthorizationID() { if (completed) { return authzid; } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Unwraps a byte array received from the client. PLAIN supports no security layer. * * @throws SaslException if attempted to use this method. */ @Override public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException { if(completed) { throw new IllegalStateException("PLAIN does not support integrity or privacy"); } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Wraps a byte array to be sent to the client. PLAIN supports no security layer. * * @throws SaslException if attempted to use this method. */ @Override public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException { if(completed) { throw new IllegalStateException("PLAIN does not support integrity or privacy"); } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Retrieves the negotiated property. * This method can be called only after the authentication exchange has * completed (i.e., when {@code isComplete()} returns true); otherwise, an * {@code IllegalStateException} is thrown. * * @param propName the property * @return The value of the negotiated property. If null, the property was * not negotiated or is not applicable to this mechanism. * @exception IllegalStateException if this authentication exchange has not completed */ @Override public Object getNegotiatedProperty(String propName) { if (completed) { if (propName.equals(Sasl.QOP)) { return "auth"; } else { return null; } } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Disposes of any system resources or security-sensitive information * the SaslServer might be using. Invoking this method invalidates * the SaslServer instance. This method is idempotent. * @throws SaslException If a problem was encountered while disposing * the resources. */ @Override public void dispose() throws SaslException { password = null; authzid = null; authcid = null; completed = false; } }
if (completed) { throw new IllegalStateException("PLAIN authentication already completed"); } if (aborted) { throw new IllegalStateException("PLAIN authentication previously aborted due to error"); } try { if(response.length != 0) { String data = new String(response, StandardCharsets.UTF_8); StringTokenizer tokens = new StringTokenizer(data, "\0"); if (tokens.countTokens() > 2) { authzid = tokens.nextToken(); // identity to act as authcid = tokens.nextToken(); // identity whose password will be used } else { // The client does not provide an authorization identity when it wishes the server to derive an // identity from the credentials and use that as the authorization identity. authcid = tokens.nextToken(); // identity whose password will be used authzid = AuthorizationManager.map(authcid); // identity to act as. } password = tokens.nextToken(); NameCallback ncb = new NameCallback("PLAIN authentication ID: ", authcid); VerifyPasswordCallback vpcb = new VerifyPasswordCallback(password.toCharArray()); cbh.handle(new Callback[]{ncb,vpcb}); if (vpcb.getVerified()) { vpcb.clearPassword(); AuthorizeCallback acb = new AuthorizeCallback(authcid, authzid); cbh.handle(new Callback[]{acb}); if(acb.isAuthorized()) { authzid = acb.getAuthorizedID(); completed = true; } else { completed = true; authzid = null; throw new SaslException("PLAIN: user not authorized: "+ authcid); } } else { throw new SaslException("PLAIN: user not authorized: "+ authcid); } } else { //Client gave no initial response if( counter++ > 1 ) { throw new SaslException("PLAIN expects a response"); } return null; } } catch (UnsupportedCallbackException | IOException | NoSuchElementException e) { aborted = true; throw new SaslException("PLAIN authentication failed for: "+ authzid, e); } return null;
1,402
581
1,983
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/sasl/VerifyPasswordCallback.java
VerifyPasswordCallback
clearPassword
class VerifyPasswordCallback implements Callback, Serializable { private static final long serialVersionUID = -6393402725550707836L; private char[] password; private boolean verified; /** * Construct a <code>VerifyPasswordCallback</code>. * @param password the password to verify. */ public VerifyPasswordCallback(char[] password) { this.password = (password == null ? null : password.clone()); this.verified = false; } /** * Get the retrieved password. * @return the retrieved password, which may be null. */ public char[] getPassword() { return (password == null ? null : password.clone()); } /** * Clear the retrieved password. */ public void clearPassword() {<FILL_FUNCTION_BODY>} /** * Indicate if this password is verified. * @param verified true if the password is verified; false otherwise */ public void setVerified(boolean verified) { this.verified = verified; } /** * Determines wether the password is verified. * @return true if the password is verified; false otherwise */ public boolean getVerified() { return verified; } }
if (password != null) { Arrays.fill(password, ' '); password = null; }
340
34
374
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/security/SecurityAuditManager.java
SecurityAuditManagerContainer
getEvents
class SecurityAuditManagerContainer { private static SecurityAuditManager instance = new SecurityAuditManager(); } /** * Returns the currently-installed SecurityAuditProvider. <b>Warning:</b> in virtually all * cases the security audit provider should not be used directly. Instead, the appropriate * methods in SecurityAuditManager should be called. Direct access to the security audit * provider is only provided for special-case logic. * * @return the current SecurityAuditProvider. */ public static SecurityAuditProvider getSecurityAuditProvider() { return SecurityAuditManagerContainer.instance.provider; } /** * Returns a singleton instance of SecurityAuditManager. * * @return a SecurityAuditManager instance. */ public static SecurityAuditManager getInstance() { return SecurityAuditManagerContainer.instance; } private static SecurityAuditProvider provider; /** * Constructs a SecurityAuditManager, setting up the provider, and a listener. */ private SecurityAuditManager() { // Load an security audit provider. initProvider(AUDIT_PROVIDER.getValue()); } /** * Initializes the server's security audit provider, based on configuration and defaults to * DefaultSecurityAuditProvider if the specified provider is not valid or not specified. */ private static void initProvider(final Class clazz) { if (provider == null || !clazz.equals(provider.getClass())) { try { provider = (SecurityAuditProvider) clazz.newInstance(); } catch (Exception e) { Log.error("Error loading security audit provider: " + clazz.getName(), e); provider = new DefaultSecurityAuditProvider(); } } } /** * Records a security event in the audit logs. * * @param username Username of user who performed the security event. * @param summary Short description of the event, similar to a subject. * @param details Detailed description of the event, can be null if not desired. */ public void logEvent(String username, String summary, String details) { provider.logEvent(username, summary, details); } /** * Retrieves security events that have occurred, filtered by the parameters passed. * The events will be in order of most recent to least recent. * * Any parameters that are left null are to be ignored. In other words, if username is null, * then no specific username is being searched for. * * @param username Username of user to look up. Can be null for no username filtering. * @param skipEvents Number of events to skip past (typically for paging). Can be null for first page. * @param numEvents Number of events to retrieve. Can be null for "all" events. * @param startTime Oldest date of range of events to retrieve. Can be null for forever. * @param endTime Most recent date of range of events to retrieve. Can be null for "now". * @return Array of security events. * @throws AuditWriteOnlyException if provider can not be read from. */ public List<SecurityAuditEvent> getEvents(String username, Integer skipEvents, Integer numEvents, Date startTime, Date endTime) throws AuditWriteOnlyException {<FILL_FUNCTION_BODY>
if (provider.isWriteOnly()) { throw new AuditWriteOnlyException(); } return provider.getEvents(username, skipEvents, numEvents, startTime, endTime);
854
49
903
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/server/OutgoingServerSocketReader.java
OutgoingServerSocketReader
init
class OutgoingServerSocketReader { private static final Logger Log = LoggerFactory.getLogger(OutgoingServerSocketReader.class); private OutgoingServerSession session; private boolean open = true; private XMPPPacketReader reader = null; /** * Queue that holds the elements read by the XMPPPacketReader. */ private BlockingQueue<Element> elements = new LinkedBlockingQueue<>(10000); public OutgoingServerSocketReader(XMPPPacketReader reader) { this.reader = reader; init(); } /** * Returns the OutgoingServerSession for which this reader is working for or {@code null} if * a OutgoingServerSession was not created yet. While the OutgoingServerSession is being * created it is possible to have a reader with no session. * * @return the OutgoingServerSession for which this reader is working for or {@code null} if * a OutgoingServerSession was not created yet. */ public OutgoingServerSession getSession() { return session; } /** * Sets the OutgoingServerSession for which this reader is working for. * * @param session the OutgoingServerSession for which this reader is working for */ public void setSession(OutgoingServerSession session) { this.session = session; } /** * Retrieves and removes the first received element that was stored in the queue, waiting * if necessary up to the specified wait time if no elements are present on this queue. * * @param timeout how long to wait before giving up, in units of {@code unit}. * @param unit a {@code TimeUnit} determining how to interpret the {@code timeout} parameter. * @return the head of this queue, or {@code null} if the specified waiting time elapses * before an element is present. * @throws InterruptedException if interrupted while waiting. */ public Element getElement(long timeout, TimeUnit unit) throws InterruptedException { return elements.poll(timeout, unit); } private void init() {<FILL_FUNCTION_BODY>} public boolean isOpen() { return open; } private void closeSession() { open = false; if (session != null) { session.close(); } } }
// Create a thread that will read and store DOM Elements. Thread thread = new Thread("Outgoing Server Reader") { @Override public void run() { while (open) { Element doc; try { doc = reader.parseDocument().getRootElement(); if (doc == null) { // Stop reading the stream since the remote server has sent an end of // stream element and probably closed the connection. closeSession(); } else { elements.add(doc); } } catch (IOException e) { String message = "Finishing Outgoing Server Reader. "; if (session != null) { message = message + "Closing session: " + session.toString(); } else { message = message + "No session to close."; } Log.debug("OutgoingServerSocketReader: "+message, e); closeSession(); } catch (Exception e) { String message = "Finishing Outgoing Server Reader. "; if (session != null) { message = message + "Closing session: " + session.toString(); } else { message = message + "No session to close."; } Log.error(message, e); closeSession(); } } } }; thread.setDaemon(true); thread.start();
592
348
940
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/server/RemoteServerConfiguration.java
RemoteServerConfiguration
getCachedSize
class RemoteServerConfiguration implements Cacheable, Externalizable { private String domain; private Permission permission; private int remotePort; public RemoteServerConfiguration() { } public RemoteServerConfiguration(String domain) { this.domain = domain; } public String getDomain() { return domain; } public Permission getPermission() { return permission; } public void setPermission(Permission permission) { this.permission = permission; } public int getRemotePort() { return remotePort; } public void setRemotePort(int remotePort) { this.remotePort = remotePort; } @Override public int getCachedSize() {<FILL_FUNCTION_BODY>} @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeSafeUTF(out, domain); ExternalizableUtil.getInstance().writeBoolean(out, permission != null); if (permission != null) { ExternalizableUtil.getInstance().writeInt(out, permission.ordinal()); } ExternalizableUtil.getInstance().writeInt(out, remotePort); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { domain = ExternalizableUtil.getInstance().readSafeUTF(in); if (ExternalizableUtil.getInstance().readBoolean(in)) { permission = Permission.values()[ExternalizableUtil.getInstance().readInt(in)]; } remotePort = ExternalizableUtil.getInstance().readInt(in); } public enum Permission { /** * The XMPP entity is allowed to connect to the server. */ allowed, /** * The XMPP entity is NOT allowed to connect to the server. */ blocked; } }
// Approximate the size of the object in bytes by calculating the size // of each field. int size = 0; size += CacheSizes.sizeOfObject(); // overhead of object size += CacheSizes.sizeOfString(domain); // domain size += CacheSizes.sizeOfInt(); // remotePort return size;
477
89
566
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/server/ServerDialbackErrorException.java
ServerDialbackErrorException
toXML
class ServerDialbackErrorException extends Exception { private final String from; private final String to; private final PacketError error; public ServerDialbackErrorException(String from, String to, PacketError error) { super(); this.from = from; this.to = to; this.error = error; } public ServerDialbackErrorException(String from, String to, PacketError error, Throwable e) { super(e); this.from = from; this.to = to; this.error = error; } public String getFrom() { return from; } public String getTo() { return to; } public PacketError getError() { return error; } public Element toXML() {<FILL_FUNCTION_BODY>} }
final Namespace ns = Namespace.get("db", "jabber:server:dialback"); final Document outbound = DocumentHelper.createDocument(); final Element root = outbound.addElement("root"); root.add(ns); final Element result = root.addElement(QName.get("result", ns)); result.addAttribute("from", from); result.addAttribute("to", to); result.addAttribute("type", "error"); result.add(error.getElement()); return result;
238
133
371
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/server/ServerDialbackKeyInvalidException.java
ServerDialbackKeyInvalidException
toXML
class ServerDialbackKeyInvalidException extends Exception { private final String from; private final String to; public ServerDialbackKeyInvalidException(String from, String to) { super(); this.from = from; this.to = to; } public String getFrom() { return from; } public String getTo() { return to; } public Element toXML() {<FILL_FUNCTION_BODY>} }
final Namespace ns = Namespace.get("db", "jabber:server:dialback"); final Document outbound = DocumentHelper.createDocument(); final Element root = outbound.addElement("root"); root.add(ns); final Element result = root.addElement(QName.get("result", ns)); result.addAttribute("from", from); result.addAttribute("to", to); result.addAttribute("type", "invalid"); return result;
132
123
255
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/ClientSessionInfo.java
ClientSessionInfo
readExternal
class ClientSessionInfo implements Externalizable { private Presence presence; private String defaultList; private String activeList; private boolean offlineFloodStopped; private boolean messageCarbonsEnabled; private boolean hasRequestedBlocklist; private NodeID nodeID; private boolean anonymous; public ClientSessionInfo() { } public ClientSessionInfo(LocalClientSession session) { presence = session.getPresence(); defaultList = session.getDefaultList() != null ? session.getDefaultList().getName() : null; activeList = session.getActiveList() != null ? session.getActiveList().getName() : null; offlineFloodStopped = session.isOfflineFloodStopped(); messageCarbonsEnabled = session.isMessageCarbonsEnabled(); hasRequestedBlocklist = session.hasRequestedBlocklist(); nodeID = XMPPServer.getInstance().getNodeID(); anonymous = session.isAnonymousUser(); } public Presence getPresence() { return presence; } public String getDefaultList() { return defaultList; } public String getActiveList() { return activeList; } public boolean isOfflineFloodStopped() { return offlineFloodStopped; } public boolean hasRequestedBlocklist() { return hasRequestedBlocklist; } public boolean isMessageCarbonsEnabled() { return messageCarbonsEnabled; } public NodeID getNodeID() { return nodeID; } public boolean isAnonymous() { return anonymous; } @Override public void writeExternal(ObjectOutput out) throws IOException { ExternalizableUtil.getInstance().writeSerializable(out, (DefaultElement) presence.getElement()); ExternalizableUtil.getInstance().writeBoolean(out, defaultList != null); if (defaultList != null) { ExternalizableUtil.getInstance().writeSafeUTF(out, defaultList); } ExternalizableUtil.getInstance().writeBoolean(out, activeList != null); if (activeList != null) { ExternalizableUtil.getInstance().writeSafeUTF(out, activeList); } ExternalizableUtil.getInstance().writeBoolean(out, offlineFloodStopped); ExternalizableUtil.getInstance().writeBoolean(out, messageCarbonsEnabled); ExternalizableUtil.getInstance().writeBoolean(out, hasRequestedBlocklist); ExternalizableUtil.getInstance().writeSerializable(out, nodeID); ExternalizableUtil.getInstance().writeBoolean(out, anonymous); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
Element packetElement = (Element) ExternalizableUtil.getInstance().readSerializable(in); presence = new Presence(packetElement, true); if (ExternalizableUtil.getInstance().readBoolean(in)) { defaultList = ExternalizableUtil.getInstance().readSafeUTF(in); } if (ExternalizableUtil.getInstance().readBoolean(in)) { activeList = ExternalizableUtil.getInstance().readSafeUTF(in); } offlineFloodStopped = ExternalizableUtil.getInstance().readBoolean(in); messageCarbonsEnabled = ExternalizableUtil.getInstance().readBoolean(in); hasRequestedBlocklist = ExternalizableUtil.getInstance().readBoolean(in); nodeID = (NodeID) ExternalizableUtil.getInstance().readSerializable(in); anonymous = ExternalizableUtil.getInstance().readBoolean(in);
693
211
904
<no_super_class>
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/ClientSessionTask.java
ClientSessionTask
run
class ClientSessionTask extends RemoteSessionTask { private static Logger logger = LoggerFactory.getLogger(ClientSessionTask.class); private JID address; private transient Session session; public ClientSessionTask() { super(); } public ClientSessionTask(JID address, Operation operation) { super(operation); this.address = address; } Session getSession() { if (session == null) { session = XMPPServer.getInstance().getRoutingTable().getClientRoute(address); } return session; } public void run() {<FILL_FUNCTION_BODY>} public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); ExternalizableUtil.getInstance().writeSerializable(out, address); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); address = (JID) ExternalizableUtil.getInstance().readSerializable(in); } public String toString() { return super.toString() + " operation: " + operation + " address: " + address; } }
if (getSession() == null || getSession().isClosed()) { logger.error("Session not found for JID: " + address); return; } super.run(); ClientSession session = (ClientSession) getSession(); if (session instanceof RemoteClientSession) { // The session is being hosted by other cluster node so log this unexpected case Cache<String, ClientRoute> usersCache = CacheFactory.createCache(RoutingTableImpl.C2S_CACHE_NAME); ClientRoute route = usersCache.get(address.toString()); byte[] nodeIDByte = route != null ? route.getNodeID().toByteArray() : new byte[0]; logger.warn("Found remote session instead of local session. JID: {} found in Node: {} and local node is: {}", address, nodeIDByte, XMPPServer.getInstance().getNodeID().toByteArray()); } if (operation == Operation.isInitialized) { if (session instanceof RemoteClientSession) { // Something is wrong since the session should be local instead of remote // Assume some default value result = true; } else { result = session.isInitialized(); } } else if (operation == Operation.incrementConflictCount) { if (session instanceof RemoteClientSession) { // Something is wrong since the session should be local instead of remote // Assume some default value result = 2; } else { result = session.incrementConflictCount(); } } else if (operation == Operation.hasRequestedBlocklist) { if (session instanceof RemoteClientSession) { // Something is wrong since the session should be local instead of remote // Assume some default value result = false; } else { result = session.hasRequestedBlocklist(); } }
298
462
760
<methods>public void <init>() ,public java.lang.Object getResult() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void run() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private static final Logger Log,protected org.jivesoftware.openfire.session.RemoteSessionTask.Operation operation,protected java.lang.Object result
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/session/ComponentSessionTask.java
ComponentSessionTask
run
class ComponentSessionTask extends RemoteSessionTask { private JID address; public ComponentSessionTask() { } protected ComponentSessionTask(JID address, Operation operation) { super(operation); this.address = address; } Session getSession() { return SessionManager.getInstance().getComponentSession(address.getDomain()); } public void run() {<FILL_FUNCTION_BODY>} public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); ExternalizableUtil.getInstance().writeSerializable(out, address); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); address = (JID) ExternalizableUtil.getInstance().readSerializable(in); } public String toString() { return super.toString() + " operation: " + operation + " address: " + address; } }
super.run(); if (operation == Operation.getType) { result = ((ComponentSession) getSession()).getExternalComponent().getType(); } else if (operation == Operation.getCategory) { result = ((ComponentSession) getSession()).getExternalComponent().getCategory(); } else if (operation == Operation.getInitialSubdomain) { result = ((ComponentSession) getSession()).getExternalComponent().getInitialSubdomain(); } else if (operation == Operation.getSubdomains) { result = ((ComponentSession) getSession()).getExternalComponent().getSubdomains(); } else if (operation == Operation.getName) { result = ((ComponentSession) getSession()).getExternalComponent().getName(); } else if (operation == Operation.getDescription) { result = ((ComponentSession) getSession()).getExternalComponent().getDescription(); } else if (operation == Operation.start) { ((ComponentSession) getSession()).getExternalComponent().start(); } else if (operation == Operation.shutdown) { ((ComponentSession) getSession()).getExternalComponent().shutdown(); }
242
280
522
<methods>public void <init>() ,public java.lang.Object getResult() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void run() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private static final Logger Log,protected org.jivesoftware.openfire.session.RemoteSessionTask.Operation operation,protected java.lang.Object result