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.StanzaError; 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 @SuppressWarnings("HidingField") 092 private final BOSHConfiguration config; 093 094 // Some flags which provides some info about the current state. 095 private boolean isFirstInitialization = true; 096 private boolean done = false; 097 098 // The readerPipe and consumer thread are used for the debugger. 099 private PipedWriter readerPipe; 100 private Thread readerConsumer; 101 102 /** 103 * The session ID for the BOSH session with the connection manager. 104 */ 105 protected String sessionID = null; 106 107 private boolean notified; 108 109 /** 110 * Create a HTTP Binding connection to an XMPP server. 111 * 112 * @param username the username to use. 113 * @param password the password to use. 114 * @param https true if you want to use SSL 115 * (e.g. false for http://domain.lt:7070/http-bind). 116 * @param host the hostname or IP address of the connection manager 117 * (e.g. domain.lt for http://domain.lt:7070/http-bind). 118 * @param port the port of the connection manager 119 * (e.g. 7070 for http://domain.lt:7070/http-bind). 120 * @param filePath the file which is described by the URL 121 * (e.g. /http-bind for http://domain.lt:7070/http-bind). 122 * @param xmppServiceDomain the XMPP service name 123 * (e.g. domain.lt for the user alice@domain.lt) 124 */ 125 public XMPPBOSHConnection(String username, String password, boolean https, String host, int port, String filePath, DomainBareJid xmppServiceDomain) { 126 this(BOSHConfiguration.builder().setUseHttps(https).setHost(host) 127 .setPort(port).setFile(filePath).setXmppDomain(xmppServiceDomain) 128 .setUsernameAndPassword(username, password).build()); 129 } 130 131 /** 132 * Create a HTTP Binding connection to an XMPP server. 133 * 134 * @param config The configuration which is used for this connection. 135 */ 136 public XMPPBOSHConnection(BOSHConfiguration config) { 137 super(config); 138 this.config = config; 139 } 140 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 client = BOSHClient.create(cfgBuilder.build()); 160 161 client.addBOSHClientConnListener(new BOSHConnectionListener()); 162 client.addBOSHClientResponseListener(new BOSHPacketReader()); 163 164 // Initialize the debugger 165 if (debugger != null) { 166 initDebugger(); 167 } 168 169 // Send the session creation request 170 client.send(ComposableBody.builder() 171 .setNamespaceDefinition("xmpp", XMPP_BOSH_NS) 172 .setAttribute(BodyQName.createWithPrefix(XMPP_BOSH_NS, "version", "xmpp"), "1.0") 173 .build()); 174 } catch (Exception e) { 175 throw new ConnectionException(e); 176 } 177 178 // Wait for the response from the server 179 synchronized (this) { 180 if (!connected) { 181 final long deadline = System.currentTimeMillis() + getReplyTimeout(); 182 while (!notified) { 183 final long now = System.currentTimeMillis(); 184 if (now >= deadline) break; 185 wait(deadline - now); 186 } 187 } 188 } 189 190 // If there is no feedback, throw an remote server timeout error 191 if (!connected && !done) { 192 done = true; 193 String errorMessage = "Timeout reached for the connection to " 194 + getHost() + ":" + getPort() + "."; 195 throw new SmackException(errorMessage); 196 } 197 } 198 199 @Override 200 public boolean isSecureConnection() { 201 // TODO: Implement SSL usage 202 return false; 203 } 204 205 @Override 206 public boolean isUsingCompression() { 207 // TODO: Implement compression 208 return false; 209 } 210 211 @Override 212 protected void loginInternal(String username, String password, Resourcepart resource) throws XMPPException, 213 SmackException, IOException, InterruptedException { 214 // Authenticate using SASL 215 saslAuthentication.authenticate(username, password, config.getAuthzid(), null); 216 217 bindResourceAndEstablishSession(resource); 218 219 afterSuccessfulLogin(false); 220 } 221 222 @Override 223 public void sendNonza(Nonza element) throws NotConnectedException { 224 if (done) { 225 throw new NotConnectedException(); 226 } 227 sendElement(element); 228 } 229 230 @Override 231 protected void sendStanzaInternal(Stanza packet) throws NotConnectedException { 232 sendElement(packet); 233 } 234 235 private void sendElement(Element element) { 236 try { 237 send(ComposableBody.builder().setPayloadXML(element.toXML(BOSH_URI).toString()).build()); 238 if (element instanceof Stanza) { 239 firePacketSendingListeners((Stanza) element); 240 } 241 } 242 catch (BOSHException e) { 243 LOGGER.log(Level.SEVERE, "BOSHException in sendStanzaInternal", e); 244 } 245 } 246 247 /** 248 * Closes the connection by setting presence to unavailable and closing the 249 * HTTP client. The shutdown logic will be used during a planned disconnection or when 250 * dealing with an unexpected disconnection. Unlike {@link #disconnect()} the connection's 251 * BOSH stanza reader will not be removed; thus connection's state is kept. 252 * 253 */ 254 @Override 255 protected void shutdown() { 256 setWasAuthenticated(); 257 sessionID = null; 258 done = true; 259 authenticated = false; 260 connected = false; 261 isFirstInitialization = false; 262 263 // Close down the readers and writers. 264 if (readerPipe != null) { 265 try { 266 readerPipe.close(); 267 } 268 catch (Throwable ignore) { /* ignore */ } 269 reader = null; 270 } 271 if (reader != null) { 272 try { 273 reader.close(); 274 } 275 catch (Throwable ignore) { /* ignore */ } 276 reader = null; 277 } 278 if (writer != null) { 279 try { 280 writer.close(); 281 } 282 catch (Throwable ignore) { /* ignore */ } 283 writer = null; 284 } 285 286 readerConsumer = null; 287 } 288 289 /** 290 * Send a HTTP request to the connection manager with the provided body element. 291 * 292 * @param body the body which will be sent. 293 * @throws BOSHException 294 */ 295 protected void send(ComposableBody body) throws BOSHException { 296 if (!connected) { 297 throw new IllegalStateException("Not connected to a server!"); 298 } 299 if (body == null) { 300 throw new NullPointerException("Body mustn't be null!"); 301 } 302 if (sessionID != null) { 303 body = body.rebuild().setAttribute( 304 BodyQName.create(BOSH_URI, "sid"), sessionID).build(); 305 } 306 client.send(body); 307 } 308 309 /** 310 * Initialize the SmackDebugger which allows to log and debug XML traffic. 311 */ 312 @Override 313 protected void initDebugger() { 314 // TODO: Maybe we want to extend the SmackDebugger for simplification 315 // and a performance boost. 316 317 // Initialize a empty writer which discards all data. 318 writer = new Writer() { 319 @Override 320 public void write(char[] cbuf, int off, int len) { 321 /* ignore */ } 322 323 @Override 324 public void close() { 325 /* ignore */ } 326 327 @Override 328 public void flush() { 329 /* ignore */ } 330 }; 331 332 // Initialize a pipe for received raw data. 333 try { 334 readerPipe = new PipedWriter(); 335 reader = new PipedReader(readerPipe); 336 } 337 catch (IOException e) { 338 // Ignore 339 } 340 341 // Call the method from the parent class which initializes the debugger. 342 super.initDebugger(); 343 344 // Add listeners for the received and sent raw data. 345 client.addBOSHClientResponseListener(new BOSHClientResponseListener() { 346 @Override 347 public void responseReceived(BOSHMessageEvent event) { 348 if (event.getBody() != null) { 349 try { 350 readerPipe.write(event.getBody().toXML()); 351 readerPipe.flush(); 352 } catch (Exception e) { 353 // Ignore 354 } 355 } 356 } 357 }); 358 client.addBOSHClientRequestListener(new BOSHClientRequestListener() { 359 @Override 360 public void requestSent(BOSHMessageEvent event) { 361 if (event.getBody() != null) { 362 try { 363 writer.write(event.getBody().toXML()); 364 } catch (Exception e) { 365 // Ignore 366 } 367 } 368 } 369 }); 370 371 // Create and start a thread which discards all read data. 372 readerConsumer = new Thread() { 373 private Thread thread = this; 374 private int bufferLength = 1024; 375 376 @Override 377 public void run() { 378 try { 379 char[] cbuf = new char[bufferLength]; 380 while (readerConsumer == thread && !done) { 381 reader.read(cbuf, 0, bufferLength); 382 } 383 } catch (IOException e) { 384 // Ignore 385 } 386 } 387 }; 388 readerConsumer.setDaemon(true); 389 readerConsumer.start(); 390 } 391 392 /** 393 * Sends out a notification that there was an error with the connection 394 * and closes the connection. 395 * 396 * @param e the exception that causes the connection close event. 397 */ 398 protected void notifyConnectionError(Exception e) { 399 // Closes the connection temporary. A reconnection is possible 400 shutdown(); 401 callConnectionClosedOnErrorListener(e); 402 } 403 404 /** 405 * A listener class which listen for a successfully established connection 406 * and connection errors and notifies the BOSHConnection. 407 * 408 * @author Guenther Niess 409 */ 410 private class BOSHConnectionListener implements BOSHClientConnListener { 411 412 /** 413 * Notify the BOSHConnection about connection state changes. 414 * Process the connection listeners and try to login if the 415 * connection was formerly authenticated and is now reconnected. 416 */ 417 @Override 418 public void connectionEvent(BOSHClientConnEvent connEvent) { 419 try { 420 if (connEvent.isConnected()) { 421 connected = true; 422 if (isFirstInitialization) { 423 isFirstInitialization = false; 424 } 425 else { 426 if (wasAuthenticated) { 427 try { 428 login(); 429 } 430 catch (Exception e) { 431 throw new RuntimeException(e); 432 } 433 } 434 } 435 } 436 else { 437 if (connEvent.isError()) { 438 // TODO Check why jbosh's getCause returns Throwable here. This is very 439 // unusual and should be avoided if possible 440 Throwable cause = connEvent.getCause(); 441 Exception e; 442 if (cause instanceof Exception) { 443 e = (Exception) cause; 444 } else { 445 e = new Exception(cause); 446 } 447 notifyConnectionError(e); 448 } 449 connected = false; 450 } 451 } 452 finally { 453 notified = true; 454 synchronized (XMPPBOSHConnection.this) { 455 XMPPBOSHConnection.this.notifyAll(); 456 } 457 } 458 } 459 } 460 461 /** 462 * Listens for XML traffic from the BOSH connection manager and parses it into 463 * stanza objects. 464 * 465 * @author Guenther Niess 466 */ 467 private class BOSHPacketReader implements BOSHClientResponseListener { 468 469 /** 470 * Parse the received packets and notify the corresponding connection. 471 * 472 * @param event the BOSH client response which includes the received packet. 473 */ 474 @Override 475 public void responseReceived(BOSHMessageEvent event) { 476 AbstractBody body = event.getBody(); 477 if (body != null) { 478 try { 479 if (sessionID == null) { 480 sessionID = body.getAttribute(BodyQName.create(XMPPBOSHConnection.BOSH_URI, "sid")); 481 } 482 if (streamId == null) { 483 streamId = body.getAttribute(BodyQName.create(XMPPBOSHConnection.BOSH_URI, "authid")); 484 } 485 final XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); 486 parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); 487 parser.setInput(new StringReader(body.toXML())); 488 int eventType = parser.getEventType(); 489 do { 490 eventType = parser.next(); 491 switch (eventType) { 492 case XmlPullParser.START_TAG: 493 String name = parser.getName(); 494 switch (name) { 495 case Message.ELEMENT: 496 case IQ.IQ_ELEMENT: 497 case Presence.ELEMENT: 498 parseAndProcessStanza(parser); 499 break; 500 case "challenge": 501 // The server is challenging the SASL authentication 502 // made by the client 503 final String challengeData = parser.nextText(); 504 getSASLAuthentication().challengeReceived(challengeData); 505 break; 506 case "success": 507 send(ComposableBody.builder().setNamespaceDefinition("xmpp", 508 XMPPBOSHConnection.XMPP_BOSH_NS).setAttribute( 509 BodyQName.createWithPrefix(XMPPBOSHConnection.XMPP_BOSH_NS, "restart", 510 "xmpp"), "true").setAttribute( 511 BodyQName.create(XMPPBOSHConnection.BOSH_URI, "to"), getXMPPServiceDomain().toString()).build()); 512 Success success = new Success(parser.nextText()); 513 getSASLAuthentication().authenticated(success); 514 break; 515 case "features": 516 parseFeatures(parser); 517 break; 518 case "failure": 519 if ("urn:ietf:params:xml:ns:xmpp-sasl".equals(parser.getNamespace(null))) { 520 final SASLFailure failure = PacketParserUtils.parseSASLFailure(parser); 521 getSASLAuthentication().authenticationFailed(failure); 522 } 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.Builder builder = PacketParserUtils.parseError(parser); 530 throw new XMPPException.XMPPErrorException(null, builder.build()); 531 } 532 } 533 break; 534 } 535 } 536 while (eventType != XmlPullParser.END_DOCUMENT); 537 } 538 catch (Exception e) { 539 if (isConnected()) { 540 notifyConnectionError(e); 541 } 542 } 543 } 544 } 545 } 546}