001/** 002 * 003 * Copyright 2009 Jive Software. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.jivesoftware.smack.bosh; 019 020import java.io.IOException; 021import java.io.PipedReader; 022import java.io.PipedWriter; 023import java.io.Writer; 024import java.util.Map; 025import java.util.logging.Level; 026import java.util.logging.Logger; 027 028import org.jivesoftware.smack.AbstractXMPPConnection; 029import org.jivesoftware.smack.SmackException; 030import org.jivesoftware.smack.SmackException.GenericConnectionException; 031import org.jivesoftware.smack.SmackException.NotConnectedException; 032import org.jivesoftware.smack.SmackException.SmackWrappedException; 033import org.jivesoftware.smack.XMPPConnection; 034import org.jivesoftware.smack.XMPPException; 035import org.jivesoftware.smack.XMPPException.StreamErrorException; 036import org.jivesoftware.smack.packet.Element; 037import org.jivesoftware.smack.packet.IQ; 038import org.jivesoftware.smack.packet.Message; 039import org.jivesoftware.smack.packet.Nonza; 040import org.jivesoftware.smack.packet.Presence; 041import org.jivesoftware.smack.packet.Stanza; 042import org.jivesoftware.smack.packet.StanzaError; 043import org.jivesoftware.smack.util.CloseableUtil; 044import org.jivesoftware.smack.util.PacketParserUtils; 045import org.jivesoftware.smack.xml.XmlPullParser; 046import org.jivesoftware.smack.xml.XmlPullParserException; 047 048import org.igniterealtime.jbosh.AbstractBody; 049import org.igniterealtime.jbosh.BOSHClient; 050import org.igniterealtime.jbosh.BOSHClientConfig; 051import org.igniterealtime.jbosh.BOSHClientConnEvent; 052import org.igniterealtime.jbosh.BOSHClientConnListener; 053import org.igniterealtime.jbosh.BOSHClientRequestListener; 054import org.igniterealtime.jbosh.BOSHClientResponseListener; 055import org.igniterealtime.jbosh.BOSHException; 056import org.igniterealtime.jbosh.BOSHMessageEvent; 057import org.igniterealtime.jbosh.BodyQName; 058import org.igniterealtime.jbosh.ComposableBody; 059import org.jxmpp.jid.DomainBareJid; 060import org.jxmpp.jid.parts.Resourcepart; 061 062/** 063 * Creates a connection to an XMPP server via HTTP binding. 064 * This is specified in the XEP-0206: XMPP Over BOSH. 065 * 066 * @see XMPPConnection 067 * @author Guenther Niess 068 */ 069public class XMPPBOSHConnection extends AbstractXMPPConnection { 070 private static final Logger LOGGER = Logger.getLogger(XMPPBOSHConnection.class.getName()); 071 072 /** 073 * The XMPP Over Bosh namespace. 074 */ 075 public static final String XMPP_BOSH_NS = "urn:xmpp:xbosh"; 076 077 /** 078 * The BOSH namespace from XEP-0124. 079 */ 080 public static final String BOSH_URI = "http://jabber.org/protocol/httpbind"; 081 082 /** 083 * The used BOSH client from the jbosh library. 084 */ 085 private BOSHClient client; 086 087 /** 088 * Holds the initial configuration used while creating the connection. 089 */ 090 @SuppressWarnings("HidingField") 091 private final BOSHConfiguration config; 092 093 // Some flags which provides some info about the current state. 094 private boolean isFirstInitialization = true; 095 private boolean done = false; 096 097 // The readerPipe and consumer thread are used for the debugger. 098 private PipedWriter readerPipe; 099 private Thread readerConsumer; 100 101 /** 102 * The session ID for the BOSH session with the connection manager. 103 */ 104 protected String sessionID = null; 105 106 private boolean notified; 107 108 /** 109 * Create a HTTP Binding connection to an XMPP server. 110 * 111 * @param username the username to use. 112 * @param password the password to use. 113 * @param https true if you want to use SSL 114 * (e.g. false for http://domain.lt:7070/http-bind). 115 * @param host the hostname or IP address of the connection manager 116 * (e.g. domain.lt for http://domain.lt:7070/http-bind). 117 * @param port the port of the connection manager 118 * (e.g. 7070 for http://domain.lt:7070/http-bind). 119 * @param filePath the file which is described by the URL 120 * (e.g. /http-bind for http://domain.lt:7070/http-bind). 121 * @param xmppServiceDomain the XMPP service name 122 * (e.g. domain.lt for the user alice@domain.lt) 123 */ 124 public XMPPBOSHConnection(String username, String password, boolean https, String host, int port, String filePath, DomainBareJid xmppServiceDomain) { 125 this(BOSHConfiguration.builder().setUseHttps(https).setHost(host) 126 .setPort(port).setFile(filePath).setXmppDomain(xmppServiceDomain) 127 .setUsernameAndPassword(username, password).build()); 128 } 129 130 /** 131 * Create a HTTP Binding connection to an XMPP server. 132 * 133 * @param config The configuration which is used for this connection. 134 */ 135 public XMPPBOSHConnection(BOSHConfiguration config) { 136 super(config); 137 this.config = config; 138 } 139 140 @SuppressWarnings("deprecation") 141 @Override 142 protected void connectInternal() throws SmackException, InterruptedException { 143 done = false; 144 notified = false; 145 try { 146 // Ensure a clean starting state 147 if (client != null) { 148 client.close(); 149 client = null; 150 } 151 sessionID = null; 152 153 // Initialize BOSH client 154 BOSHClientConfig.Builder cfgBuilder = BOSHClientConfig.Builder 155 .create(config.getURI(), config.getXMPPServiceDomain().toString()); 156 if (config.isProxyEnabled()) { 157 cfgBuilder.setProxy(config.getProxyAddress(), config.getProxyPort()); 158 } 159 160 cfgBuilder.setCompressionEnabled(config.isCompressionEnabled()); 161 162 for (Map.Entry<String, String> h : config.getHttpHeaders().entrySet()) { 163 cfgBuilder.addHttpHeader(h.getKey(), h.getValue()); 164 } 165 166 client = BOSHClient.create(cfgBuilder.build()); 167 168 client.addBOSHClientConnListener(new BOSHConnectionListener()); 169 client.addBOSHClientResponseListener(new BOSHPacketReader()); 170 171 // Initialize the debugger 172 if (debugger != null) { 173 initDebugger(); 174 } 175 176 // Send the session creation request 177 client.send(ComposableBody.builder() 178 .setNamespaceDefinition("xmpp", XMPP_BOSH_NS) 179 .setAttribute(BodyQName.createWithPrefix(XMPP_BOSH_NS, "version", "xmpp"), "1.0") 180 .build()); 181 } catch (Exception e) { 182 throw new GenericConnectionException(e); 183 } 184 185 // Wait for the response from the server 186 synchronized (this) { 187 if (!connected) { 188 final long deadline = System.currentTimeMillis() + getReplyTimeout(); 189 while (!notified) { 190 final long now = System.currentTimeMillis(); 191 if (now >= deadline) break; 192 wait(deadline - now); 193 } 194 } 195 } 196 197 // If there is no feedback, throw an remote server timeout error 198 if (!connected && !done) { 199 done = true; 200 String errorMessage = "Timeout reached for the connection to " 201 + getHost() + ":" + getPort() + "."; 202 throw new SmackException.SmackMessageException(errorMessage); 203 } 204 205 try { 206 XmlPullParser parser = PacketParserUtils.getParserFor("<stream:stream xmlns='jabber:client'/>"); 207 onStreamOpen(parser); 208 } catch (XmlPullParserException | IOException e) { 209 throw new AssertionError("Failed to setup stream environment", e); 210 } 211 } 212 213 @Override 214 public boolean isSecureConnection() { 215 // TODO: Implement SSL usage 216 return false; 217 } 218 219 @Override 220 public boolean isUsingCompression() { 221 // TODO: Implement compression 222 return false; 223 } 224 225 @Override 226 protected void loginInternal(String username, String password, Resourcepart resource) throws XMPPException, 227 SmackException, IOException, InterruptedException { 228 // Authenticate using SASL 229 authenticate(username, password, config.getAuthzid(), null); 230 231 bindResourceAndEstablishSession(resource); 232 233 afterSuccessfulLogin(false); 234 } 235 236 @Override 237 public void sendNonza(Nonza element) throws NotConnectedException { 238 if (done) { 239 throw new NotConnectedException(); 240 } 241 sendElement(element); 242 } 243 244 @Override 245 protected void sendStanzaInternal(Stanza packet) throws NotConnectedException { 246 sendElement(packet); 247 } 248 249 private void sendElement(Element element) { 250 try { 251 send(ComposableBody.builder().setPayloadXML(element.toXML(BOSH_URI).toString()).build()); 252 if (element instanceof Stanza) { 253 firePacketSendingListeners((Stanza) element); 254 } 255 } 256 catch (BOSHException e) { 257 LOGGER.log(Level.SEVERE, "BOSHException in sendStanzaInternal", e); 258 } 259 } 260 261 /** 262 * Closes the connection by setting presence to unavailable and closing the 263 * HTTP client. The shutdown logic will be used during a planned disconnection or when 264 * dealing with an unexpected disconnection. Unlike {@link #disconnect()} the connection's 265 * BOSH stanza reader will not be removed; thus connection's state is kept. 266 * 267 */ 268 @Override 269 protected void shutdown() { 270 271 if (client != null) { 272 try { 273 client.disconnect(); 274 } catch (Exception e) { 275 LOGGER.log(Level.WARNING, "shutdown", e); 276 } 277 client = null; 278 } 279 280 instantShutdown(); 281 } 282 283 @Override 284 public void instantShutdown() { 285 setWasAuthenticated(); 286 sessionID = null; 287 done = true; 288 authenticated = false; 289 connected = false; 290 isFirstInitialization = false; 291 292 // Close down the readers and writers. 293 CloseableUtil.maybeClose(readerPipe, LOGGER); 294 CloseableUtil.maybeClose(reader, LOGGER); 295 CloseableUtil.maybeClose(writer, LOGGER); 296 297 readerPipe = null; 298 reader = null; 299 writer = null; 300 readerConsumer = null; 301 } 302 303 /** 304 * Send a HTTP request to the connection manager with the provided body element. 305 * 306 * @param body the body which will be sent. 307 * @throws BOSHException if an BOSH (Bidirectional-streams Over Synchronous HTTP, XEP-0124) related error occurs 308 */ 309 protected void send(ComposableBody body) throws BOSHException { 310 if (!connected) { 311 throw new IllegalStateException("Not connected to a server!"); 312 } 313 if (body == null) { 314 throw new NullPointerException("Body mustn't be null!"); 315 } 316 if (sessionID != null) { 317 body = body.rebuild().setAttribute( 318 BodyQName.create(BOSH_URI, "sid"), sessionID).build(); 319 } 320 client.send(body); 321 } 322 323 /** 324 * Initialize the SmackDebugger which allows to log and debug XML traffic. 325 */ 326 @Override 327 protected void initDebugger() { 328 // TODO: Maybe we want to extend the SmackDebugger for simplification 329 // and a performance boost. 330 331 // Initialize a empty writer which discards all data. 332 writer = new Writer() { 333 @Override 334 public void write(char[] cbuf, int off, int len) { 335 /* ignore */ } 336 337 @Override 338 public void close() { 339 /* ignore */ } 340 341 @Override 342 public void flush() { 343 /* ignore */ } 344 }; 345 346 // Initialize a pipe for received raw data. 347 try { 348 readerPipe = new PipedWriter(); 349 reader = new PipedReader(readerPipe); 350 } 351 catch (IOException e) { 352 // Ignore 353 } 354 355 // Call the method from the parent class which initializes the debugger. 356 super.initDebugger(); 357 358 // Add listeners for the received and sent raw data. 359 client.addBOSHClientResponseListener(new BOSHClientResponseListener() { 360 @Override 361 public void responseReceived(BOSHMessageEvent event) { 362 if (event.getBody() != null) { 363 try { 364 readerPipe.write(event.getBody().toXML()); 365 readerPipe.flush(); 366 } catch (Exception e) { 367 // Ignore 368 } 369 } 370 } 371 }); 372 client.addBOSHClientRequestListener(new BOSHClientRequestListener() { 373 @Override 374 public void requestSent(BOSHMessageEvent event) { 375 if (event.getBody() != null) { 376 try { 377 writer.write(event.getBody().toXML()); 378 } catch (Exception e) { 379 // Ignore 380 } 381 } 382 } 383 }); 384 385 // Create and start a thread which discards all read data. 386 readerConsumer = new Thread() { 387 private Thread thread = this; 388 private int bufferLength = 1024; 389 390 @Override 391 public void run() { 392 try { 393 char[] cbuf = new char[bufferLength]; 394 while (readerConsumer == thread && !done) { 395 reader.read(cbuf, 0, bufferLength); 396 } 397 } catch (IOException e) { 398 // Ignore 399 } 400 } 401 }; 402 readerConsumer.setDaemon(true); 403 readerConsumer.start(); 404 } 405 406 @Override 407 protected void afterSaslAuthenticationSuccess() 408 throws NotConnectedException, InterruptedException, SmackWrappedException { 409 // XMPP over BOSH is unusual when it comes to SASL authentication: Instead of sending a new stream open, it 410 // requires a special XML element ot be send after successful SASL authentication. 411 // See XEP-0206 ยง 5., especially the following is example 5 of XEP-0206. 412 ComposableBody composeableBody = ComposableBody.builder().setNamespaceDefinition("xmpp", 413 XMPPBOSHConnection.XMPP_BOSH_NS).setAttribute( 414 BodyQName.createWithPrefix(XMPPBOSHConnection.XMPP_BOSH_NS, "restart", 415 "xmpp"), "true").setAttribute( 416 BodyQName.create(XMPPBOSHConnection.BOSH_URI, "to"), getXMPPServiceDomain().toString()).build(); 417 418 try { 419 send(composeableBody); 420 } catch (BOSHException e) { 421 // jbosh's exception API does not really match the one of Smack. 422 throw new SmackException.SmackWrappedException(e); 423 } 424 } 425 426 /** 427 * A listener class which listen for a successfully established connection 428 * and connection errors and notifies the BOSHConnection. 429 * 430 * @author Guenther Niess 431 */ 432 private class BOSHConnectionListener implements BOSHClientConnListener { 433 434 /** 435 * Notify the BOSHConnection about connection state changes. 436 * Process the connection listeners and try to login if the 437 * connection was formerly authenticated and is now reconnected. 438 */ 439 @Override 440 public void connectionEvent(BOSHClientConnEvent connEvent) { 441 try { 442 if (connEvent.isConnected()) { 443 connected = true; 444 if (isFirstInitialization) { 445 isFirstInitialization = false; 446 } 447 else { 448 if (wasAuthenticated) { 449 try { 450 login(); 451 } 452 catch (Exception e) { 453 throw new RuntimeException(e); 454 } 455 } 456 } 457 } 458 else { 459 if (connEvent.isError()) { 460 // TODO Check why jbosh's getCause returns Throwable here. This is very 461 // unusual and should be avoided if possible 462 Throwable cause = connEvent.getCause(); 463 Exception e; 464 if (cause instanceof Exception) { 465 e = (Exception) cause; 466 } else { 467 e = new Exception(cause); 468 } 469 notifyConnectionError(e); 470 } 471 connected = false; 472 } 473 } 474 finally { 475 notified = true; 476 synchronized (XMPPBOSHConnection.this) { 477 XMPPBOSHConnection.this.notifyAll(); 478 } 479 } 480 } 481 } 482 483 /** 484 * Listens for XML traffic from the BOSH connection manager and parses it into 485 * stanza objects. 486 * 487 * @author Guenther Niess 488 */ 489 private class BOSHPacketReader implements BOSHClientResponseListener { 490 491 /** 492 * Parse the received packets and notify the corresponding connection. 493 * 494 * @param event the BOSH client response which includes the received packet. 495 */ 496 @Override 497 public void responseReceived(BOSHMessageEvent event) { 498 AbstractBody body = event.getBody(); 499 if (body != null) { 500 try { 501 if (sessionID == null) { 502 sessionID = body.getAttribute(BodyQName.create(XMPPBOSHConnection.BOSH_URI, "sid")); 503 } 504 if (streamId == null) { 505 streamId = body.getAttribute(BodyQName.create(XMPPBOSHConnection.BOSH_URI, "authid")); 506 } 507 final XmlPullParser parser = PacketParserUtils.getParserFor(body.toXML()); 508 509 XmlPullParser.Event eventType = parser.getEventType(); 510 do { 511 eventType = parser.next(); 512 switch (eventType) { 513 case START_ELEMENT: 514 String name = parser.getName(); 515 switch (name) { 516 case Message.ELEMENT: 517 case IQ.IQ_ELEMENT: 518 case Presence.ELEMENT: 519 parseAndProcessStanza(parser); 520 break; 521 case "features": 522 parseFeaturesAndNotify(parser); 523 break; 524 case "error": 525 // Some BOSH error isn't stream error. 526 if ("urn:ietf:params:xml:ns:xmpp-streams".equals(parser.getNamespace(null))) { 527 throw new StreamErrorException(PacketParserUtils.parseStreamError(parser)); 528 } else { 529 StanzaError stanzaError = PacketParserUtils.parseError(parser); 530 throw new XMPPException.XMPPErrorException(null, stanzaError); 531 } 532 default: 533 parseAndProcessNonza(parser); 534 break; 535 } 536 break; 537 default: 538 // Catch all for incomplete switch (MissingCasesInEnumSwitch) statement. 539 break; 540 } 541 } 542 while (eventType != XmlPullParser.Event.END_DOCUMENT); 543 } 544 catch (Exception e) { 545 if (isConnected()) { 546 notifyConnectionError(e); 547 } 548 } 549 } 550 } 551 } 552}