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.StringReader; 024import java.io.Writer; 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.ConnectionException; 031import org.jivesoftware.smack.SmackException.NotConnectedException; 032import org.jivesoftware.smack.XMPPConnection; 033import org.jivesoftware.smack.XMPPException; 034import org.jivesoftware.smack.XMPPException.StreamErrorException; 035import org.jivesoftware.smack.packet.Element; 036import org.jivesoftware.smack.packet.IQ; 037import org.jivesoftware.smack.packet.Message; 038import org.jivesoftware.smack.packet.Nonza; 039import org.jivesoftware.smack.packet.Presence; 040import org.jivesoftware.smack.packet.Stanza; 041import org.jivesoftware.smack.packet.XMPPError; 042import org.jivesoftware.smack.sasl.packet.SaslStreamElements.SASLFailure; 043import org.jivesoftware.smack.sasl.packet.SaslStreamElements.Success; 044import org.jivesoftware.smack.util.PacketParserUtils; 045 046import org.igniterealtime.jbosh.AbstractBody; 047import org.igniterealtime.jbosh.BOSHClient; 048import org.igniterealtime.jbosh.BOSHClientConfig; 049import org.igniterealtime.jbosh.BOSHClientConnEvent; 050import org.igniterealtime.jbosh.BOSHClientConnListener; 051import org.igniterealtime.jbosh.BOSHClientRequestListener; 052import org.igniterealtime.jbosh.BOSHClientResponseListener; 053import org.igniterealtime.jbosh.BOSHException; 054import org.igniterealtime.jbosh.BOSHMessageEvent; 055import org.igniterealtime.jbosh.BodyQName; 056import org.igniterealtime.jbosh.ComposableBody; 057 058import org.jxmpp.jid.DomainBareJid; 059import org.jxmpp.jid.parts.Resourcepart; 060import org.xmlpull.v1.XmlPullParser; 061import org.xmlpull.v1.XmlPullParserFactory; 062 063/** 064 * Creates a connection to an XMPP server via HTTP binding. 065 * This is specified in the XEP-0206: XMPP Over BOSH. 066 * 067 * @see XMPPConnection 068 * @author Guenther Niess 069 */ 070public class XMPPBOSHConnection extends AbstractXMPPConnection { 071 private static final Logger LOGGER = Logger.getLogger(XMPPBOSHConnection.class.getName()); 072 073 /** 074 * The XMPP Over Bosh namespace. 075 */ 076 public static final String XMPP_BOSH_NS = "urn:xmpp:xbosh"; 077 078 /** 079 * The BOSH namespace from XEP-0124. 080 */ 081 public static final String BOSH_URI = "http://jabber.org/protocol/httpbind"; 082 083 /** 084 * The used BOSH client from the jbosh library. 085 */ 086 private BOSHClient client; 087 088 /** 089 * Holds the initial configuration used while creating the connection. 090 */ 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 @Override 141 protected void connectInternal() throws SmackException, InterruptedException { 142 done = false; 143 notified = false; 144 try { 145 // Ensure a clean starting state 146 if (client != null) { 147 client.close(); 148 client = null; 149 } 150 sessionID = null; 151 152 // Initialize BOSH client 153 BOSHClientConfig.Builder cfgBuilder = BOSHClientConfig.Builder 154 .create(config.getURI(), config.getXMPPServiceDomain().toString()); 155 if (config.isProxyEnabled()) { 156 cfgBuilder.setProxy(config.getProxyAddress(), config.getProxyPort()); 157 } 158 client = BOSHClient.create(cfgBuilder.build()); 159 160 client.addBOSHClientConnListener(new BOSHConnectionListener()); 161 client.addBOSHClientResponseListener(new BOSHPacketReader()); 162 163 // Initialize the debugger 164 if (config.isDebuggerEnabled()) { 165 initDebugger(); 166 if (isFirstInitialization) { 167 if (debugger.getReaderListener() != null) { 168 addAsyncStanzaListener(debugger.getReaderListener(), null); 169 } 170 if (debugger.getWriterListener() != null) { 171 addStanzaSendingListener(debugger.getWriterListener(), null); 172 } 173 } 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 ConnectionException(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(errorMessage); 203 } 204 } 205 206 @Override 207 public boolean isSecureConnection() { 208 // TODO: Implement SSL usage 209 return false; 210 } 211 212 @Override 213 public boolean isUsingCompression() { 214 // TODO: Implement compression 215 return false; 216 } 217 218 @Override 219 protected void loginInternal(String username, String password, Resourcepart resource) throws XMPPException, 220 SmackException, IOException, InterruptedException { 221 // Authenticate using SASL 222 saslAuthentication.authenticate(username, password, config.getAuthzid(), null); 223 224 bindResourceAndEstablishSession(resource); 225 226 afterSuccessfulLogin(false); 227 } 228 229 @Override 230 public void sendNonza(Nonza element) throws NotConnectedException { 231 if (done) { 232 throw new NotConnectedException(); 233 } 234 sendElement(element); 235 } 236 237 @Override 238 protected void sendStanzaInternal(Stanza packet) throws NotConnectedException { 239 sendElement(packet); 240 } 241 242 private void sendElement(Element element) { 243 try { 244 send(ComposableBody.builder().setPayloadXML(element.toXML().toString()).build()); 245 if (element instanceof Stanza) { 246 firePacketSendingListeners((Stanza) element); 247 } 248 } 249 catch (BOSHException e) { 250 LOGGER.log(Level.SEVERE, "BOSHException in sendStanzaInternal", e); 251 } 252 } 253 254 /** 255 * Closes the connection by setting presence to unavailable and closing the 256 * HTTP client. The shutdown logic will be used during a planned disconnection or when 257 * dealing with an unexpected disconnection. Unlike {@link #disconnect()} the connection's 258 * BOSH stanza(/packet) reader will not be removed; thus connection's state is kept. 259 * 260 */ 261 @Override 262 protected void shutdown() { 263 setWasAuthenticated(); 264 sessionID = null; 265 done = true; 266 authenticated = false; 267 connected = false; 268 isFirstInitialization = false; 269 270 // Close down the readers and writers. 271 if (readerPipe != null) { 272 try { 273 readerPipe.close(); 274 } 275 catch (Throwable ignore) { /* ignore */ } 276 reader = null; 277 } 278 if (reader != null) { 279 try { 280 reader.close(); 281 } 282 catch (Throwable ignore) { /* ignore */ } 283 reader = null; 284 } 285 if (writer != null) { 286 try { 287 writer.close(); 288 } 289 catch (Throwable ignore) { /* ignore */ } 290 writer = null; 291 } 292 293 readerConsumer = null; 294 } 295 296 /** 297 * Send a HTTP request to the connection manager with the provided body element. 298 * 299 * @param body the body which will be sent. 300 * @throws BOSHException 301 */ 302 protected void send(ComposableBody body) throws BOSHException { 303 if (!connected) { 304 throw new IllegalStateException("Not connected to a server!"); 305 } 306 if (body == null) { 307 throw new NullPointerException("Body mustn't be null!"); 308 } 309 if (sessionID != null) { 310 body = body.rebuild().setAttribute( 311 BodyQName.create(BOSH_URI, "sid"), sessionID).build(); 312 } 313 client.send(body); 314 } 315 316 /** 317 * Initialize the SmackDebugger which allows to log and debug XML traffic. 318 */ 319 @Override 320 protected void initDebugger() { 321 // TODO: Maybe we want to extend the SmackDebugger for simplification 322 // and a performance boost. 323 324 // Initialize a empty writer which discards all data. 325 writer = new Writer() { 326 @Override 327 public void write(char[] cbuf, int off, int len) { 328 /* ignore */ } 329 330 @Override 331 public void close() { 332 /* ignore */ } 333 334 @Override 335 public void flush() { 336 /* ignore */ } 337 }; 338 339 // Initialize a pipe for received raw data. 340 try { 341 readerPipe = new PipedWriter(); 342 reader = new PipedReader(readerPipe); 343 } 344 catch (IOException e) { 345 // Ignore 346 } 347 348 // Call the method from the parent class which initializes the debugger. 349 super.initDebugger(); 350 351 // Add listeners for the received and sent raw data. 352 client.addBOSHClientResponseListener(new BOSHClientResponseListener() { 353 @Override 354 public void responseReceived(BOSHMessageEvent event) { 355 if (event.getBody() != null) { 356 try { 357 readerPipe.write(event.getBody().toXML()); 358 readerPipe.flush(); 359 } catch (Exception e) { 360 // Ignore 361 } 362 } 363 } 364 }); 365 client.addBOSHClientRequestListener(new BOSHClientRequestListener() { 366 @Override 367 public void requestSent(BOSHMessageEvent event) { 368 if (event.getBody() != null) { 369 try { 370 writer.write(event.getBody().toXML()); 371 } catch (Exception e) { 372 // Ignore 373 } 374 } 375 } 376 }); 377 378 // Create and start a thread which discards all read data. 379 readerConsumer = new Thread() { 380 private Thread thread = this; 381 private int bufferLength = 1024; 382 383 @Override 384 public void run() { 385 try { 386 char[] cbuf = new char[bufferLength]; 387 while (readerConsumer == thread && !done) { 388 reader.read(cbuf, 0, bufferLength); 389 } 390 } catch (IOException e) { 391 // Ignore 392 } 393 } 394 }; 395 readerConsumer.setDaemon(true); 396 readerConsumer.start(); 397 } 398 399 /** 400 * Sends out a notification that there was an error with the connection 401 * and closes the connection. 402 * 403 * @param e the exception that causes the connection close event. 404 */ 405 protected void notifyConnectionError(Exception e) { 406 // Closes the connection temporary. A reconnection is possible 407 shutdown(); 408 callConnectionClosedOnErrorListener(e); 409 } 410 411 /** 412 * A listener class which listen for a successfully established connection 413 * and connection errors and notifies the BOSHConnection. 414 * 415 * @author Guenther Niess 416 */ 417 private class BOSHConnectionListener implements BOSHClientConnListener { 418 419 /** 420 * Notify the BOSHConnection about connection state changes. 421 * Process the connection listeners and try to login if the 422 * connection was formerly authenticated and is now reconnected. 423 */ 424 @Override 425 public void connectionEvent(BOSHClientConnEvent connEvent) { 426 try { 427 if (connEvent.isConnected()) { 428 connected = true; 429 if (isFirstInitialization) { 430 isFirstInitialization = false; 431 } 432 else { 433 if (wasAuthenticated) { 434 try { 435 login(); 436 } 437 catch (Exception e) { 438 throw new RuntimeException(e); 439 } 440 } 441 } 442 } 443 else { 444 if (connEvent.isError()) { 445 // TODO Check why jbosh's getCause returns Throwable here. This is very 446 // unusual and should be avoided if possible 447 Throwable cause = connEvent.getCause(); 448 Exception e; 449 if (cause instanceof Exception) { 450 e = (Exception) cause; 451 } else { 452 e = new Exception(cause); 453 } 454 notifyConnectionError(e); 455 } 456 connected = false; 457 } 458 } 459 finally { 460 notified = true; 461 synchronized (XMPPBOSHConnection.this) { 462 XMPPBOSHConnection.this.notifyAll(); 463 } 464 } 465 } 466 } 467 468 /** 469 * Listens for XML traffic from the BOSH connection manager and parses it into 470 * stanza(/packet) objects. 471 * 472 * @author Guenther Niess 473 */ 474 private class BOSHPacketReader implements BOSHClientResponseListener { 475 476 /** 477 * Parse the received packets and notify the corresponding connection. 478 * 479 * @param event the BOSH client response which includes the received packet. 480 */ 481 @Override 482 public void responseReceived(BOSHMessageEvent event) { 483 AbstractBody body = event.getBody(); 484 if (body != null) { 485 try { 486 if (sessionID == null) { 487 sessionID = body.getAttribute(BodyQName.create(XMPPBOSHConnection.BOSH_URI, "sid")); 488 } 489 if (streamId == null) { 490 streamId = body.getAttribute(BodyQName.create(XMPPBOSHConnection.BOSH_URI, "authid")); 491 } 492 final XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); 493 parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); 494 parser.setInput(new StringReader(body.toXML())); 495 int eventType = parser.getEventType(); 496 do { 497 eventType = parser.next(); 498 switch (eventType) { 499 case XmlPullParser.START_TAG: 500 String name = parser.getName(); 501 switch (name) { 502 case Message.ELEMENT: 503 case IQ.IQ_ELEMENT: 504 case Presence.ELEMENT: 505 parseAndProcessStanza(parser); 506 break; 507 case "challenge": 508 // The server is challenging the SASL authentication 509 // made by the client 510 final String challengeData = parser.nextText(); 511 getSASLAuthentication().challengeReceived(challengeData); 512 break; 513 case "success": 514 send(ComposableBody.builder().setNamespaceDefinition("xmpp", 515 XMPPBOSHConnection.XMPP_BOSH_NS).setAttribute( 516 BodyQName.createWithPrefix(XMPPBOSHConnection.XMPP_BOSH_NS, "restart", 517 "xmpp"), "true").setAttribute( 518 BodyQName.create(XMPPBOSHConnection.BOSH_URI, "to"), getXMPPServiceDomain().toString()).build()); 519 Success success = new Success(parser.nextText()); 520 getSASLAuthentication().authenticated(success); 521 break; 522 case "features": 523 parseFeatures(parser); 524 break; 525 case "failure": 526 if ("urn:ietf:params:xml:ns:xmpp-sasl".equals(parser.getNamespace(null))) { 527 final SASLFailure failure = PacketParserUtils.parseSASLFailure(parser); 528 getSASLAuthentication().authenticationFailed(failure); 529 } 530 break; 531 case "error": 532 // Some BOSH error isn't stream error. 533 if ("urn:ietf:params:xml:ns:xmpp-streams".equals(parser.getNamespace(null))) { 534 throw new StreamErrorException(PacketParserUtils.parseStreamError(parser)); 535 } else { 536 XMPPError.Builder builder = PacketParserUtils.parseError(parser); 537 throw new XMPPException.XMPPErrorException(null, builder.build()); 538 } 539 } 540 break; 541 } 542 } 543 while (eventType != XmlPullParser.END_DOCUMENT); 544 } 545 catch (Exception e) { 546 if (isConnected()) { 547 notifyConnectionError(e); 548 } 549 } 550 } 551 } 552 } 553}