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( 207 "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'/>"); 208 onStreamOpen(parser); 209 } catch (XmlPullParserException | IOException e) { 210 throw new AssertionError("Failed to setup stream environment", e); 211 } 212 } 213 214 @Override 215 public boolean isSecureConnection() { 216 // TODO: Implement SSL usage 217 return false; 218 } 219 220 @Override 221 public boolean isUsingCompression() { 222 // TODO: Implement compression 223 return false; 224 } 225 226 @Override 227 protected void loginInternal(String username, String password, Resourcepart resource) throws XMPPException, 228 SmackException, IOException, InterruptedException { 229 // Authenticate using SASL 230 authenticate(username, password, config.getAuthzid(), null); 231 232 bindResourceAndEstablishSession(resource); 233 234 afterSuccessfulLogin(false); 235 } 236 237 @Override 238 public void sendNonza(Nonza element) throws NotConnectedException { 239 if (done) { 240 throw new NotConnectedException(); 241 } 242 sendElement(element); 243 } 244 245 @Override 246 protected void sendStanzaInternal(Stanza packet) throws NotConnectedException { 247 sendElement(packet); 248 } 249 250 private void sendElement(Element element) { 251 try { 252 send(ComposableBody.builder().setPayloadXML(element.toXML(BOSH_URI).toString()).build()); 253 if (element instanceof Stanza) { 254 firePacketSendingListeners((Stanza) element); 255 } 256 } 257 catch (BOSHException e) { 258 LOGGER.log(Level.SEVERE, "BOSHException in sendStanzaInternal", e); 259 } 260 } 261 262 /** 263 * Closes the connection by setting presence to unavailable and closing the 264 * HTTP client. The shutdown logic will be used during a planned disconnection or when 265 * dealing with an unexpected disconnection. Unlike {@link #disconnect()} the connection's 266 * BOSH stanza reader will not be removed; thus connection's state is kept. 267 * 268 */ 269 @Override 270 protected void shutdown() { 271 272 if (client != null) { 273 try { 274 client.disconnect(); 275 } catch (Exception e) { 276 LOGGER.log(Level.WARNING, "shutdown", e); 277 } 278 client = null; 279 } 280 281 instantShutdown(); 282 } 283 284 @Override 285 public void instantShutdown() { 286 setWasAuthenticated(); 287 sessionID = null; 288 done = true; 289 authenticated = false; 290 connected = false; 291 isFirstInitialization = false; 292 293 // Close down the readers and writers. 294 CloseableUtil.maybeClose(readerPipe, LOGGER); 295 CloseableUtil.maybeClose(reader, LOGGER); 296 CloseableUtil.maybeClose(writer, LOGGER); 297 298 readerPipe = null; 299 reader = null; 300 writer = null; 301 readerConsumer = null; 302 } 303 304 /** 305 * Send a HTTP request to the connection manager with the provided body element. 306 * 307 * @param body the body which will be sent. 308 * @throws BOSHException if an BOSH (Bidirectional-streams Over Synchronous HTTP, XEP-0124) related error occurs 309 */ 310 protected void send(ComposableBody body) throws BOSHException { 311 if (!connected) { 312 throw new IllegalStateException("Not connected to a server!"); 313 } 314 if (body == null) { 315 throw new NullPointerException("Body mustn't be null!"); 316 } 317 if (sessionID != null) { 318 body = body.rebuild().setAttribute( 319 BodyQName.create(BOSH_URI, "sid"), sessionID).build(); 320 } 321 client.send(body); 322 } 323 324 /** 325 * Initialize the SmackDebugger which allows to log and debug XML traffic. 326 */ 327 @Override 328 protected void initDebugger() { 329 // TODO: Maybe we want to extend the SmackDebugger for simplification 330 // and a performance boost. 331 332 // Initialize a empty writer which discards all data. 333 writer = new Writer() { 334 @Override 335 public void write(char[] cbuf, int off, int len) { 336 /* ignore */ } 337 338 @Override 339 public void close() { 340 /* ignore */ } 341 342 @Override 343 public void flush() { 344 /* ignore */ } 345 }; 346 347 // Initialize a pipe for received raw data. 348 try { 349 readerPipe = new PipedWriter(); 350 reader = new PipedReader(readerPipe); 351 } 352 catch (IOException e) { 353 // Ignore 354 } 355 356 // Call the method from the parent class which initializes the debugger. 357 super.initDebugger(); 358 359 // Add listeners for the received and sent raw data. 360 client.addBOSHClientResponseListener(new BOSHClientResponseListener() { 361 @Override 362 public void responseReceived(BOSHMessageEvent event) { 363 if (event.getBody() != null) { 364 try { 365 readerPipe.write(event.getBody().toXML()); 366 readerPipe.flush(); 367 } catch (Exception e) { 368 // Ignore 369 } 370 } 371 } 372 }); 373 client.addBOSHClientRequestListener(new BOSHClientRequestListener() { 374 @Override 375 public void requestSent(BOSHMessageEvent event) { 376 if (event.getBody() != null) { 377 try { 378 writer.write(event.getBody().toXML()); 379 } catch (Exception e) { 380 // Ignore 381 } 382 } 383 } 384 }); 385 386 // Create and start a thread which discards all read data. 387 readerConsumer = new Thread() { 388 private Thread thread = this; 389 private int bufferLength = 1024; 390 391 @Override 392 public void run() { 393 try { 394 char[] cbuf = new char[bufferLength]; 395 while (readerConsumer == thread && !done) { 396 reader.read(cbuf, 0, bufferLength); 397 } 398 } catch (IOException e) { 399 // Ignore 400 } 401 } 402 }; 403 readerConsumer.setDaemon(true); 404 readerConsumer.start(); 405 } 406 407 @Override 408 protected void afterSaslAuthenticationSuccess() 409 throws NotConnectedException, InterruptedException, SmackWrappedException { 410 // XMPP over BOSH is unusual when it comes to SASL authentication: Instead of sending a new stream open, it 411 // requires a special XML element ot be send after successful SASL authentication. 412 // See XEP-0206 ยง 5., especially the following is example 5 of XEP-0206. 413 ComposableBody composeableBody = ComposableBody.builder().setNamespaceDefinition("xmpp", 414 XMPPBOSHConnection.XMPP_BOSH_NS).setAttribute( 415 BodyQName.createWithPrefix(XMPPBOSHConnection.XMPP_BOSH_NS, "restart", 416 "xmpp"), "true").setAttribute( 417 BodyQName.create(XMPPBOSHConnection.BOSH_URI, "to"), getXMPPServiceDomain().toString()).build(); 418 419 try { 420 send(composeableBody); 421 } catch (BOSHException e) { 422 // jbosh's exception API does not really match the one of Smack. 423 throw new SmackException.SmackWrappedException(e); 424 } 425 } 426 427 /** 428 * A listener class which listen for a successfully established connection 429 * and connection errors and notifies the BOSHConnection. 430 * 431 * @author Guenther Niess 432 */ 433 private class BOSHConnectionListener implements BOSHClientConnListener { 434 435 /** 436 * Notify the BOSHConnection about connection state changes. 437 * Process the connection listeners and try to login if the 438 * connection was formerly authenticated and is now reconnected. 439 */ 440 @Override 441 public void connectionEvent(BOSHClientConnEvent connEvent) { 442 try { 443 if (connEvent.isConnected()) { 444 connected = true; 445 if (isFirstInitialization) { 446 isFirstInitialization = false; 447 } 448 else { 449 if (wasAuthenticated) { 450 try { 451 login(); 452 } 453 catch (Exception e) { 454 throw new RuntimeException(e); 455 } 456 } 457 } 458 } 459 else { 460 if (connEvent.isError()) { 461 // TODO Check why jbosh's getCause returns Throwable here. This is very 462 // unusual and should be avoided if possible 463 Throwable cause = connEvent.getCause(); 464 Exception e; 465 if (cause instanceof Exception) { 466 e = (Exception) cause; 467 } else { 468 e = new Exception(cause); 469 } 470 notifyConnectionError(e); 471 } 472 connected = false; 473 } 474 } 475 finally { 476 notified = true; 477 synchronized (XMPPBOSHConnection.this) { 478 XMPPBOSHConnection.this.notifyAll(); 479 } 480 } 481 } 482 } 483 484 /** 485 * Listens for XML traffic from the BOSH connection manager and parses it into 486 * stanza objects. 487 * 488 * @author Guenther Niess 489 */ 490 private class BOSHPacketReader implements BOSHClientResponseListener { 491 492 /** 493 * Parse the received packets and notify the corresponding connection. 494 * 495 * @param event the BOSH client response which includes the received packet. 496 */ 497 @Override 498 public void responseReceived(BOSHMessageEvent event) { 499 AbstractBody body = event.getBody(); 500 if (body != null) { 501 try { 502 if (sessionID == null) { 503 sessionID = body.getAttribute(BodyQName.create(XMPPBOSHConnection.BOSH_URI, "sid")); 504 } 505 if (streamId == null) { 506 streamId = body.getAttribute(BodyQName.create(XMPPBOSHConnection.BOSH_URI, "authid")); 507 } 508 final XmlPullParser parser = PacketParserUtils.getParserFor(body.toXML()); 509 510 XmlPullParser.Event eventType = parser.getEventType(); 511 do { 512 eventType = parser.next(); 513 switch (eventType) { 514 case START_ELEMENT: 515 String name = parser.getName(); 516 switch (name) { 517 case Message.ELEMENT: 518 case IQ.IQ_ELEMENT: 519 case Presence.ELEMENT: 520 parseAndProcessStanza(parser); 521 break; 522 case "features": 523 parseFeaturesAndNotify(parser); 524 break; 525 case "error": 526 // Some BOSH error isn't stream error. 527 if ("urn:ietf:params:xml:ns:xmpp-streams".equals(parser.getNamespace(null))) { 528 throw new StreamErrorException(PacketParserUtils.parseStreamError(parser)); 529 } else { 530 StanzaError stanzaError = PacketParserUtils.parseError(parser); 531 throw new XMPPException.XMPPErrorException(null, stanzaError); 532 } 533 default: 534 parseAndProcessNonza(parser); 535 break; 536 } 537 break; 538 default: 539 // Catch all for incomplete switch (MissingCasesInEnumSwitch) statement. 540 break; 541 } 542 } 543 while (eventType != XmlPullParser.Event.END_DOCUMENT); 544 } 545 catch (Exception e) { 546 if (isConnected()) { 547 notifyConnectionError(e); 548 } 549 } 550 } 551 } 552 } 553}