BaseTransport.java 52.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/**
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2006 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

package org.jivesoftware.wildfire.gateway;

13
import org.dom4j.DocumentHelper;
14
import org.dom4j.Element;
15
import org.dom4j.QName;
16 17
import org.jivesoftware.util.Log;
import org.jivesoftware.util.NotFoundException;
18
import org.jivesoftware.wildfire.XMPPServer;
19
import org.jivesoftware.wildfire.SessionManager;
20
import org.jivesoftware.wildfire.container.PluginManager;
21
import org.jivesoftware.wildfire.roster.*;
22 23
import org.jivesoftware.wildfire.roster.Roster;
import org.jivesoftware.wildfire.user.UserAlreadyExistsException;
24
import org.jivesoftware.wildfire.user.UserNotFoundException;
25 26
import org.xmpp.component.Component;
import org.xmpp.component.ComponentManager;
27 28
import org.xmpp.forms.DataForm;
import org.xmpp.forms.FormField;
29
import org.xmpp.packet.*;
30
import org.xmpp.packet.PacketError.Condition;
31 32

import java.util.*;
33 34 35 36 37 38 39 40 41 42 43

/**
 * Base class of all transport implementations.
 *
 * Handles all transport non-specific tasks and provides the glue that holds
 * together server interactions and the legacy service.  Does the bulk of
 * the XMPP related work.  Also note that this represents the transport
 * itself, not an individual session with the transport.
 *
 * @author Daniel Henninger
 */
44
public abstract class BaseTransport implements Component, RosterEventListener {
45 46 47

    /**
     * Create a new BaseTransport instance.
Daniel Henninger's avatar
Daniel Henninger committed
48 49 50 51 52 53 54
     */
    public BaseTransport() {
        // We've got nothing to do here.
    }

    /**
     * Set up the transport instance.
55 56
     *
     * @param type Type of the transport.
Daniel Henninger's avatar
Daniel Henninger committed
57
     * @param description Description of the transport (for Disco).
58
     */
Daniel Henninger's avatar
Daniel Henninger committed
59
    public void setup(TransportType type, String description) {
60 61 62 63
        this.description = description;
        this.transportType = type;
    }

Daniel Henninger's avatar
Daniel Henninger committed
64 65 66 67 68 69
    /**
     * Handles initialization of the transport.
     */
    public void initialize(JID jid, ComponentManager componentManager) {
        this.jid = jid;
        this.componentManager = componentManager;
70 71 72 73
    }

    /**
     * Manages all active sessions.
74
     * @see org.jivesoftware.wildfire.gateway.TransportSessionManager
75
     */
76
    public final TransportSessionManager sessionManager = new TransportSessionManager(this);
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

    /**
     * Manages registration information.
     * @see org.jivesoftware.wildfire.gateway.RegistrationManager
     */
    public final RegistrationManager registrationManager = new RegistrationManager();

    /**
     * JID of the transport in question.
     */
    public JID jid = null;

    /**
     * Description of the transport in question.
     */
    public String description = null;

    /**
     * Component Manager associated with transport.
     */
    public ComponentManager componentManager = null;

99 100 101 102 103
    /**
     * Manager component for user rosters.
     */
    public final RosterManager rosterManager = new RosterManager();

104 105 106 107 108 109 110 111
    /**
     * Type of the transport in question.
     * @see org.jivesoftware.wildfire.gateway.TransportType
     */
    public TransportType transportType = null;

    private final String DISCO_INFO = "http://jabber.org/protocol/disco#info";
    private final String DISCO_ITEMS = "http://jabber.org/protocol/disco#items";
112
    private final String IQ_GATEWAY = "jabber:iq:gateway";
113
    private final String IQ_REGISTER = "jabber:iq:register";
114
    private final String IQ_VERSION = "jabber:iq:version";
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

    /**
     * Handles all incoming XMPP stanzas, passing them to individual
     * packet type handlers.
     *
     * @param packet The packet to be processed.
     */
    public void processPacket(Packet packet) {
        try {
            List<Packet> reply = new ArrayList<Packet>();
            if (packet instanceof IQ) {
                reply.addAll(processPacket((IQ)packet));
            }
            else if (packet instanceof Presence) {
                reply.addAll(processPacket((Presence)packet));
            }
            else if (packet instanceof Message) {
                reply.addAll(processPacket((Message)packet));
            }
            else {
                Log.info("Received an unhandled packet: " + packet.toString());
            }
137 138 139 140 141 142

            if (reply.size() > 0) {
                for (Packet p : reply) {
                    this.sendPacket(p);
                }
            }
143 144
        }
        catch (Exception e) {
145
            Log.error("Error occured while processing packet:", e);
146 147 148 149 150 151 152 153 154 155 156 157 158
        }
    }

    /**
     * Handles all incoming message stanzas.
     *
     * @param packet The message packet to be processed.
     */
    private List<Packet> processPacket(Message packet) {
        List<Packet> reply = new ArrayList<Packet>();
        JID from = packet.getFrom();
        JID to = packet.getTo();

159 160
        if (to.getNode() == null) {
            // Message to gateway itself.  Throw away for now.
161 162 163 164 165 166 167 168
            try {
                TransportSession session = sessionManager.getSession(from);
                session.sendServerMessage(packet.getBody());
            }
            catch (NotFoundException e) {
                // TODO: Should return an error packet here
                Log.debug("Unable to find session.");
            }
169
        }
170 171 172 173 174 175 176 177 178
        else {
            try {
                TransportSession session = sessionManager.getSession(from);
                session.sendMessage(to, packet.getBody());
            }
            catch (NotFoundException e) {
                // TODO: Should return an error packet here
                Log.debug("Unable to find session.");
            }
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        }

        return reply;
    }

    /**
     * Handles all incoming presence stanzas.
     *
     * @param packet The presence packet to be processed.
     */
    private List<Packet> processPacket(Presence packet) {
        List<Packet> reply = new ArrayList<Packet>();
        JID from = packet.getFrom();
        JID to = packet.getTo();

        if (packet.getType() == Presence.Type.error) {
            // We don't want to do anything with this.  Ignore it.
            return reply;
        }

        try {
            if (to.getNode() == null) {
                Collection<Registration> registrations = registrationManager.getRegistrations(from, this.transportType);
202
                if (registrations.isEmpty()) {
203
                    // User is not registered with us.
204
                    Log.debug("Unable to find registration.");
205 206 207
                    return reply;
                }
                Registration registration = registrations.iterator().next();
208

209 210
                // This packet is to the transport itself.
                if (packet.getType() == null) {
211
                    // A user's resource has come online.
212
                    TransportSession session;
213 214
                    try {
                        session = sessionManager.getSession(from);
215

216
                        if (session.hasResource(from.getResource())) {
217 218
                            Log.debug("An existing resource has changed status: " + from);

219 220 221
                            if (session.getPriority(from.getResource()) != packet.getPriority()) {
                                session.updatePriority(from.getResource(), packet.getPriority());
                            }
222 223 224 225
                            if (session.isHighestPriority(from.getResource())) {
                                // Well, this could represent a status change.
                                session.updateStatus(getPresenceType(packet), packet.getStatus());
                            }
226 227
                        }
                        else {
228 229
                            Log.debug("A new resource has come online: " + from);

230 231 232 233 234 235 236 237 238
                            // This is a new resource, lets send them what we know.
                            session.addResource(from.getResource(), packet.getPriority());
                            // Tell the new resource what the state of their buddy list is.
                            session.resendContactStatuses(from);
                            // If this priority is the highest, treat it's status as golden
                            if (session.isHighestPriority(from.getResource())) {
                                session.updateStatus(getPresenceType(packet), packet.getStatus());
                            }
                        }
239 240
                    }
                    catch (NotFoundException e) {
241 242
                        Log.debug("A new session has come online: " + from);

243 244 245
                        session = this.registrationLoggedIn(registration, from, getPresenceType(packet), packet.getStatus(), packet.getPriority());
                        sessionManager.storeSession(from, session);

246 247 248
                    }
                }
                else if (packet.getType() == Presence.Type.unavailable) {
249
                    // A user's resource has gone offline.
250
                    TransportSession session;
251 252
                    try {
                        session = sessionManager.getSession(from);
253 254 255 256 257
                        if (session.getResourceCount() > 1) {
                            String resource = from.getResource();

                            // Just one of the resources, lets adjust accordingly.
                            if (session.isHighestPriority(resource)) {
258 259
                                Log.debug("A high priority resource (of multiple) has gone offline: " + from);

260 261 262 263 264 265 266 267 268 269
                                // Ooh, the highest resource went offline, drop to next highest.
                                session.removeResource(resource);

                                // Lets ask the next highest resource what it's presence is.
                                Presence p = new Presence(Presence.Type.probe);
                                p.setTo(session.getJIDWithHighestPriority());
                                p.setFrom(this.getJID());
                                sendPacket(p);
                            }
                            else {
270 271
                                Log.debug("A low priority resource (of multiple) has gone offline: " + from);

272 273 274
                                // Meh, lower priority, big whoop.
                                session.removeResource(resource);
                            }
275
                        }
276
                        else {
277 278
                            Log.debug("A final resource has gone offline: " + from);

279 280 281 282
                            // No more resources, byebye.
                            if (session.isLoggedIn()) {
                                this.registrationLoggedOut(session);
                            }
283

284 285
                            sessionManager.removeSession(from);
                        }
286 287 288
                    }
                    catch (NotFoundException e) {
                        Log.debug("Ignoring unavailable presence for inactive seession.");
289 290
                    }
                }
291 292
                else if (packet.getType() == Presence.Type.probe) {
                    // Client is asking for presence status.
293
                    TransportSession session;
294 295 296 297 298 299 300 301 302 303 304 305 306
                    try {
                        session = sessionManager.getSession(from);
                        if (session.isLoggedIn()) {
                            Presence p = new Presence();
                            p.setTo(from);
                            p.setFrom(to);
                            this.sendPacket(p);
                        }
                    }
                    catch (NotFoundException e) {
                        Log.debug("Ignoring probe presence for inactive session.");
                    }
                }
307
                else {
308
                    Log.debug("Ignoring this packet:" + packet.toString());
309 310 311 312 313
                    // Anything else we will ignore for now.
                }
            }
            else {
                // This packet is to a user at the transport.
314 315
                try {
                    TransportSession session = sessionManager.getSession(from);
316

317 318
                    if (packet.getType() == Presence.Type.probe) {
                        // Presence probe, lets try to tell them.
319
                        session.retrieveContactStatus(to);
320 321 322
                    }
                    else if (packet.getType() == Presence.Type.subscribe) {
                        // User wants to add someone to their legacy roster.
323 324
                        // TODO: experimenting with doing this a different way
                        //session.addContact(packet.getTo());
325 326 327
                    }
                    else if (packet.getType() == Presence.Type.unsubscribe) {
                        // User wants to remove someone from their legacy roster.
328 329
                        // TODO: experimenting with doing this a different way
                        //session.removeContact(packet.getTo());
330 331 332 333
                    }
                    else {
                        // Anything else we will ignore for now.
                    }
334
                }
335 336
                catch (NotFoundException e) {
                    // Well we just don't care then.
337 338 339
                }
            }
        }
340
        catch (Exception e) {
341
            Log.error("Exception while processing packet: ", e);
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
        }

        return reply;
    }

    /**
     * Handles all incoming iq stanzas.
     *
     * @param packet The iq packet to be processed.
     */
    private List<Packet> processPacket(IQ packet) {
        List<Packet> reply = new ArrayList<Packet>();

        if (packet.getType() == IQ.Type.error) {
            // Lets not start a loop.  Ignore.
            return reply;
        }

        String xmlns = null;
361
        Element child = (packet).getChildElement();
362 363 364 365 366 367
        if (child != null) {
            xmlns = child.getNamespaceURI();
        }

        if (xmlns == null) {
            // No namespace defined.
368
            Log.debug("No XMLNS:" + packet.toString());
369 370 371
            IQ error = IQ.createResultIQ(packet);
            error.setError(Condition.bad_request);
            reply.add(error);
372 373 374 375
            return reply;
        }

        if (xmlns.equals(DISCO_INFO)) {
376
            reply.addAll(handleDiscoInfo(packet));
377 378
        }
        else if (xmlns.equals(DISCO_ITEMS)) {
379
            reply.addAll(handleDiscoItems(packet));
380
        }
381 382 383
        else if (xmlns.equals(IQ_GATEWAY)) {
            reply.addAll(handleIQGateway(packet));
        }
384
        else if (xmlns.equals(IQ_REGISTER)) {
385
            reply.addAll(handleIQRegister(packet));
386
        }
387 388 389
        else if (xmlns.equals(IQ_VERSION)) {
            reply.addAll(handleIQVersion(packet));
        }
390
        else {
391 392 393 394
            Log.debug("Unable to handle iq request:" + xmlns);
            IQ error = IQ.createResultIQ(packet);
            error.setError(Condition.bad_request);
            reply.add(error);
395
        }
396 397 398 399 400 401 402 403

        return reply;
    }

    /**
     * Handle service discovery info request.
     *
     * @param packet An IQ packet in the disco info namespace.
404
     * @return A list of IQ packets to be returned to the user.
405
     */
406 407 408 409 410 411 412 413 414 415 416
    private List<Packet> handleDiscoInfo(IQ packet) {
        List<Packet> reply = new ArrayList<Packet>();

        if (packet.getTo().getNode() == null) {
            // Requested info from transport itself.
            IQ result = IQ.createResultIQ(packet);
            Element response = DocumentHelper.createElement(QName.get("query", DISCO_INFO));
            response.addElement("identity")
                    .addAttribute("category", "gateway")
                    .addAttribute("type", this.transportType.toString())
                    .addAttribute("name", this.description);
417 418
            response.addElement("feature")
                    .addAttribute("var", IQ_GATEWAY);
419 420
            response.addElement("feature")
                    .addAttribute("var", IQ_REGISTER);
421 422
            response.addElement("feature")
                    .addAttribute("var", IQ_VERSION);
423 424 425 426
            result.setChildElement(response);
            reply.add(result);
        }

427 428 429 430 431 432 433
        return reply;
    }

    /**
     * Handle service discovery items request.
     *
     * @param packet An IQ packet in the disco items namespace.
434
     * @return A list of IQ packets to be returned to the user.
435
     */
436 437 438 439
    private List<Packet> handleDiscoItems(IQ packet) {
        List<Packet> reply = new ArrayList<Packet>();
        IQ result = IQ.createResultIQ(packet);
        reply.add(result);
440 441 442
        return reply;
    }

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    /**
     * Handle gateway translation service request.
     *
     * @param packet An IQ packet in the iq gateway namespace.
     * @return A list of IQ packets to be returned to the user.
     */
    private List<Packet> handleIQGateway(IQ packet) {
        List<Packet> reply = new ArrayList<Packet>();

        if (packet.getType() == IQ.Type.get) {
            IQ result = IQ.createResultIQ(packet);
            Element query = DocumentHelper.createElement(QName.get("query", IQ_GATEWAY));
            query.addElement("desc").addText("Please enter the person's "+this.getName()+" username.");
            query.addElement("prompt");
            result.setChildElement(query);
            reply.add(result);
        }
        else if (packet.getType() == IQ.Type.set) {
            IQ result = IQ.createResultIQ(packet);
            String prompt = null;
            Element promptEl = packet.getChildElement().element("prompt");
            if (promptEl != null) {
                prompt = promptEl.getTextTrim();
            }
            if (prompt == null) {
                result.setError(Condition.bad_request);
            }
            else {
                JID jid = this.convertIDToJID(prompt);
                Element query = DocumentHelper.createElement(QName.get("query", IQ_GATEWAY));
                // This is what Psi expects
                query.addElement("prompt").addText(jid.toString());
                // This is JEP complient
                query.addElement("jid").addText(jid.toString());
                result.setChildElement(query);
            }
            reply.add(result);
        }
481

482 483 484
        return reply;
    }

485 486 487 488
    /**
     * Handle registration request.
     *
     * @param packet An IQ packet in the iq registration namespace.
489
     * @return A list of IQ packets to be returned to the user.
490
     */
491 492
    private List<Packet> handleIQRegister(IQ packet) {
        List<Packet> reply = new ArrayList<Packet>();
493 494
        JID from = packet.getFrom();
        JID to = packet.getTo();
495 496 497 498 499 500 501 502 503

        Element remove = packet.getChildElement().element("remove");
        if (remove != null) {
            // User wants to unregister.  =(
            // this.convinceNotToLeave() ... kidding.
            IQ result = IQ.createResultIQ(packet);

            // Tell the end user the transport went byebye.
            Presence unavailable = new Presence(Presence.Type.unavailable);
504 505
            unavailable.setTo(from);
            unavailable.setFrom(to);
506 507 508
            reply.add(unavailable);

            try {
509
                this.deleteRegistration(from);
510 511
            }
            catch (UserNotFoundException e) {
512
                Log.error("Error cleaning up contact list of: " + from);
513 514 515 516 517 518 519 520 521
                result.setError(Condition.bad_request);
            }

            reply.add(result);
        }
        else {
            // User wants to register with the transport.
            String username = null;
            String password = null;
522
            String nickname = null;
523

524 525 526 527 528 529 530 531 532 533 534
            try {
                DataForm form = new DataForm(packet.getChildElement().element("x"));
                List<FormField> fields = form.getFields();
                for (FormField field : fields) {
                    String var = field.getVariable();
                    if (var.equals("username")) {
                        username = field.getValues().get(0);
                    }
                    else if (var.equals("password")) {
                        password = field.getValues().get(0);
                    }
535
                    else if (var.equals("nick")) {
536 537 538
                        nickname = field.getValues().get(0);
                    }

539 540 541 542 543 544
                }
            }
            catch (Exception e) {
                // No with data form apparantly
            }

545 546 547
            if (packet.getType() == IQ.Type.set) {
                Element userEl = packet.getChildElement().element("username");
                Element passEl = packet.getChildElement().element("password");
548
                Element nickEl = packet.getChildElement().element("nick");
549 550 551 552 553 554 555 556 557

                if (userEl != null) {
                    username = userEl.getTextTrim();
                }

                if (passEl != null) {
                    password = passEl.getTextTrim();
                }

558 559 560
                if (nickEl != null) {
                    nickname = nickEl.getTextTrim();
                }
561

562 563 564
                username = (username == null || username.equals("")) ? null : username;
                password = (password == null || password.equals("")) ? null : password;
                nickname = (nickname == null || nickname.equals("")) ? null : nickname;
565 566

                if (username == null || (isPasswordRequired() && password == null) || (isNicknameRequired() && nickname == null)) {
567 568 569 570 571 572 573 574 575 576 577 578 579
                    // Found nothing from stanza, lets yell.
                    IQ result = IQ.createResultIQ(packet);
                    result.setError(Condition.bad_request);
                    reply.add(result);
                }
                else {
                    Log.info("Registered " + packet.getFrom() + " as " + username);
                    IQ result = IQ.createResultIQ(packet);
                    Element response = DocumentHelper.createElement(QName.get("query", IQ_REGISTER));
                    result.setChildElement(response);
                    reply.add(result);

                    try {
580
                        this.addNewRegistration(from, username, password, nickname);
581 582
                    }
                    catch (UserNotFoundException e) {
583
                        Log.error("Someone attempted to register with the gateway who is not registered with the server: " + from);
584 585 586 587
                        IQ eresult = IQ.createResultIQ(packet);
                        eresult.setError(Condition.bad_request);
                        reply.add(eresult);
                    }
588 589 590 591

                    // Lets ask them what their presence is, maybe log
                    // them in immediately.
                    Presence p = new Presence(Presence.Type.probe);
592 593
                    p.setTo(from);
                    p.setFrom(to);
594
                    reply.add(p);
595 596 597 598 599 600
                }
            }
            else if (packet.getType() == IQ.Type.get) {
                Element response = DocumentHelper.createElement(QName.get("query", IQ_REGISTER));
                IQ result = IQ.createResultIQ(packet);

601 602 603 604 605 606 607 608 609 610 611 612 613
                String curUsername = null;
                String curPassword = null;
                String curNickname = null;
                Boolean registered = false;
                Collection<Registration> registrations = registrationManager.getRegistrations(from, this.transportType);
                if (registrations.iterator().hasNext()) {
                    Registration registration = registrations.iterator().next();
                    curUsername = registration.getUsername();
                    curPassword = registration.getPassword();
                    curNickname = registration.getNickname();
                    registered = true;
                }

614
                DataForm form = new DataForm(DataForm.Type.form);
615
                form.addInstruction(getTerminologyRegistration());
616 617

                FormField usernameField = form.addField();
618
                usernameField.setLabel(getTerminologyUsername());
619 620
                usernameField.setVariable("username");
                usernameField.setType(FormField.Type.text_single);
621 622 623
                if (curUsername != null) {
                    usernameField.addValue(curUsername);
                }
624 625

                FormField passwordField = form.addField();
626
                passwordField.setLabel(getTerminologyPassword());
627 628
                passwordField.setVariable("password");
                passwordField.setType(FormField.Type.text_private);
629 630 631
                if (curPassword != null) {
                    passwordField.addValue(curPassword);
                }
632

633 634 635 636 637 638
                String nicknameTerm = getTerminologyNickname();
                if (nicknameTerm != null) {
                    FormField nicknameField = form.addField();
                    nicknameField.setLabel(nicknameTerm);
                    nicknameField.setVariable("nick");
                    nicknameField.setType(FormField.Type.text_single);
639 640 641
                    if (curNickname != null) {
                        nicknameField.addValue(curNickname);
                    }
642 643
                }

644 645 646
                response.add(form.getElement());

                response.addElement("instructions").addText(getTerminologyRegistration());
647
                if (registered) {
648
                    response.addElement("registered");
649 650 651 652 653 654 655
                    response.addElement("username").addText(curUsername);
                    if (curPassword == null) {
                        response.addElement("password");
                    }
                    else {
                        response.addElement("password").addText(curPassword);
                    }
656
                    if (nicknameTerm != null) {
657 658 659 660 661 662
                        if (curNickname == null) {
                            response.addElement("nick");
                        }
                        else {
                            response.addElement("nick").addText(curNickname);
                        }
663
                    }
664 665 666 667
                }
                else {
                    response.addElement("username");
                    response.addElement("password");
668
                    if (nicknameTerm != null) {
669
                        response.addElement("nick");
670
                    }
671
                }
672 673 674 675 676 677 678

                result.setChildElement(response);

                reply.add(result);
            }
        }

679 680 681
        return reply;
    }

682 683 684 685 686 687 688 689 690 691 692 693 694
    /**
     * Handle version request.
     *
     * @param packet An IQ packet in the iq version namespace.
     * @return A list of IQ packets to be returned to the user.
     */
    private List<Packet> handleIQVersion(IQ packet) {
        List<Packet> reply = new ArrayList<Packet>();

        if (packet.getType() == IQ.Type.get) {
            IQ result = IQ.createResultIQ(packet);
            Element query = DocumentHelper.createElement(QName.get("query", IQ_VERSION));
            query.addElement("name").addText("Wildfire " + this.getDescription());
695
            query.addElement("version").addText(XMPPServer.getInstance().getServerInfo().getVersion().getVersionString() + " - " + this.getVersionString());
696 697 698 699
            query.addElement("os").addText(System.getProperty("os.name"));
            result.setChildElement(query);
            reply.add(result);
        }
700

701 702 703
        return reply;
    }

704 705 706 707 708 709 710
    /**
     * Converts a legacy username to a JID.
     *
     * @param username Username to be converted to a JID.
     * @return The legacy username as a JID.
     */
    public JID convertIDToJID(String username) {
711
        return new JID(username.replace('@', '%').replace(" ", ""), this.jid.getDomain(), null);
712 713 714 715 716 717 718 719 720 721
    }

    /**
     * Converts a JID to a legacy username.
     *
     * @param jid JID to be converted to a legacy username.
     * @return THe legacy username as a String.
     */
    public String convertJIDToID(JID jid) {
        return jid.getNode().replace('%', '@');
722 723
    }

724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
    /**
     * Gets an easy to use presence type from a presence packet.
     *
     * @param packet A presence packet from which the type will be pulled.
     */
    public PresenceType getPresenceType(Presence packet) {
        Presence.Type ptype = packet.getType();
        Presence.Show stype = packet.getShow();

        if (stype == Presence.Show.chat) {
            return PresenceType.chat;
        }
        else if (stype == Presence.Show.away) {
            return PresenceType.away;
        }
        else if (stype == Presence.Show.xa) {
            return PresenceType.xa;
        }
        else if (stype == Presence.Show.dnd) {
            return PresenceType.dnd;
        }
        else if (ptype == Presence.Type.unavailable) {
            return PresenceType.unavailable;
        }
        else if (packet.isAvailable()) {
            return PresenceType.available;
        }
        else {
            return PresenceType.unknown;
        }
    }

756 757 758 759
    /**
     * Handles startup of the transport.
     */
    public void start() {
760 761 762 763 764 765 766 767 768 769
        RosterEventDispatcher.addListener(this);
        // Probe all registered users [if they are logged in] to auto-log them in
        for (Registration registration : registrationManager.getRegistrations()) {
            if (SessionManager.getInstance().getSessionCount(registration.getJID().getNode()) > 0) {
                Presence p = new Presence(Presence.Type.probe);
                p.setFrom(this.getJID());
                p.setTo(registration.getJID());
                sendPacket(p);
            }
        }
770 771 772 773 774 775 776 777
    }

    /**
     * Handles shutdown of the transport.
     *
     * Cleans up all active sessions.
     */
    public void shutdown() {
778 779 780 781
        RosterEventDispatcher.removeListener(this);
        // Disconnect everyone's session
        for (TransportSession session : sessionManager.getSessions()) {
            registrationLoggedOut(session);
782
            session.removeAllResources();
783
        }
784
        sessionManager.shutdown();
785 786 787
    }

    /**
788 789 790 791 792 793
     * Returns the jid of the transport.
     */
    public JID getJID() {
        return this.jid;
    }

794 795 796 797 798 799 800
    /**
     * Returns the roster manager for the transport.
     */
    public RosterManager getRosterManager() {
        return this.rosterManager;
    }

801 802
    /**
     * Returns the name (type) of the transport.
803 804 805 806 807
     */
    public String getName() {
        return transportType.toString();
    }

808 809 810 811 812 813 814
    /**
     * Returns the type of the transport.
     */
    public TransportType getType() {
        return transportType;
    }

815 816 817 818 819 820 821 822 823 824 825 826 827 828
    /**
     * Returns the description of the transport.
     */
    public String getDescription() {
        return description;
    }

    /**
     * Returns the component manager of the transport.
     */
    public ComponentManager getComponentManager() {
        return componentManager;
    }

829 830 831 832 833 834 835 836 837 838 839 840 841 842
    /**
     * Returns the registration manager of the transport.
     */
    public RegistrationManager getRegistrationManager() {
        return registrationManager;
    }

    /**
     * Returns the session manager of the transport.
     */
    public TransportSessionManager getSessionManager() {
        return sessionManager;
    }

843 844 845 846 847
    /**
     * Retains the version string for later requests.
     */
    private String versionString = null;

848 849 850 851
    /**
     * Returns the version string of the gateway.
     */
    public String getVersionString() {
852 853 854 855 856
        if (versionString == null) {
            PluginManager pluginManager = XMPPServer.getInstance().getPluginManager();
            versionString = pluginManager.getVersion(pluginManager.getPlugin("gateway"));
        }
        return versionString;
857 858
    }

859 860 861
    /**
     * Either updates or adds a JID to a user's roster.
     *
862 863
     * Tries to only edit the roster if it has to.
     *
864 865 866
     * @param userjid JID of user to have item added to their roster.
     * @param contactjid JID to add to roster.
     * @param nickname Nickname of item. (can be null)
867
     * @param groups List of group the item is to be placed in. (can be null)
868 869
     * @throws UserNotFoundException if userjid not found.
     */
870
    public void addOrUpdateRosterItem(JID userjid, JID contactjid, String nickname, ArrayList<String> groups) throws UserNotFoundException {
871 872 873 874
        try {
            Roster roster = rosterManager.getRoster(userjid.getNode());
            try {
                RosterItem gwitem = roster.getRosterItem(contactjid);
875
                Boolean changed = false;
876 877
                if (gwitem.getSubStatus() != RosterItem.SUB_BOTH) {
                    gwitem.setSubStatus(RosterItem.SUB_BOTH);
878
                    changed = true;
879 880 881
                }
                if (gwitem.getAskStatus() != RosterItem.ASK_NONE) {
                    gwitem.setAskStatus(RosterItem.ASK_NONE);
882 883
                    changed = true;
                }
884
                if (nickname != null && !(gwitem.getNickname() != null) && !gwitem.getNickname().equals(nickname)) {
885 886
                    gwitem.setNickname(nickname);
                    changed = true;
887
                }
888 889 890 891 892 893 894 895 896
                List<String> curgroups = gwitem.getGroups();
                if (curgroups != groups) {
                    try {
                        gwitem.setGroups(groups);
                        changed = true;
                    }
                    catch (Exception ee) {
                        // Oooookay, ignore then.
                    }
897
                }
898 899
                if (changed) {
                    roster.updateRosterItem(gwitem);
900 901 902 903
                }
            }
            catch (UserNotFoundException e) {
                try {
904 905 906 907
                    // Create new roster item for the gateway service or legacy contact. Only
                    // roster items related to the gateway service will be persistent. Roster
                    // items of legacy users are never persisted in the DB.
                    RosterItem gwitem =
908
                            roster.createRosterItem(contactjid, true, contactjid.getNode() == null);
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
                    gwitem.setSubStatus(RosterItem.SUB_BOTH);
                    gwitem.setAskStatus(RosterItem.ASK_NONE);
                    gwitem.setNickname(nickname);
                    try {
                        gwitem.setGroups(groups);
                    }
                    catch (Exception ee) {
                        // Oooookay, ignore then.
                    }
                    roster.updateRosterItem(gwitem);
                }
                catch (UserAlreadyExistsException ee) {
                    Log.error("getRosterItem claims user exists, but couldn't find via getRosterItem?");
                    // TODO: Should we throw exception or something?
                }
                catch (Exception ee) {
925
                    Log.error("createRosterItem caused exception: " + ee.toString());
926 927 928 929 930 931 932 933 934
                    // TODO: Should we throw exception or something?
                }
            }
        }
        catch (UserNotFoundException e) {
            throw new UserNotFoundException("Could not find roster for " + userjid.toString());
        }
    }

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
    /**
     * Either updates or adds a JID to a user's roster.
     *
     * Tries to only edit the roster if it has to.
     *
     * @param userjid JID of user to have item added to their roster.
     * @param contactjid JID to add to roster.
     * @param nickname Nickname of item. (can be null)
     * @param group Group item is to be placed in. (can be null)
     * @throws UserNotFoundException if userjid not found.
     */
    public void addOrUpdateRosterItem(JID userjid, JID contactjid, String nickname, String group) throws UserNotFoundException {
        ArrayList<String> groups = null;
        if (group != null) {
            groups = new ArrayList<String>();
            groups.add(group);
        }
        addOrUpdateRosterItem(userjid, contactjid, nickname, groups);
    }

955 956 957 958 959 960 961 962 963 964 965
    /**
     * Either updates or adds a contact to a user's roster.
     *
     * @param userjid JID of user to have item added to their roster.
     * @param contactid String contact name, will be translated to JID.
     * @param nickname Nickname of item. (can be null)
     * @param group Group item is to be placed in. (can be null)
     * @throws UserNotFoundException if userjid not found.
     */
    public void addOrUpdateRosterItem(JID userjid, String contactid, String nickname, String group) throws UserNotFoundException {
        try {
966
            addOrUpdateRosterItem(userjid, convertIDToJID(contactid), nickname, group);
967 968 969 970 971 972 973 974 975 976 977 978 979 980
        }
        catch (UserNotFoundException e) {
            // Pass it on down.
            throw e;
        }
    }

    /**
     * Removes a roster item from a user's roster.
     *
     * @param userjid JID of user whose roster we will interact with.
     * @param contactjid JID to be removed from roster.
     * @throws UserNotFoundException if userjid not found.
     */
981
    public void removeFromRoster(JID userjid, JID contactjid) throws UserNotFoundException {
982 983 984 985
        // Clean up the user's contact list.
        try {
            Roster roster = rosterManager.getRoster(userjid.getNode());
            for (RosterItem ri : roster.getRosterItems()) {
986
                if (ri.getJid().toBareJID().equals(contactjid.toBareJID())) {
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
                    try {
                        roster.deleteRosterItem(ri.getJid(), false);
                    }
                    catch (Exception e) {
                        Log.error("Error removing roster item: " + ri.toString());
                        // TODO: Should we say something?
                    }
                }
            }
        }
        catch (UserNotFoundException e) {
            throw new UserNotFoundException("Could not find roster for " + userjid.toString());
        }
    }

    /**
     * Removes a roster item from a user's roster based on a legacy contact.
     *
     * @param userjid JID of user whose roster we will interact with.
     * @param contactid Contact to be removed, will be translated to JID.
     * @throws UserNotFoundException if userjid not found.
     */
    void removeFromRoster(JID userjid, String contactid) throws UserNotFoundException {
        // Clean up the user's contact list.
        try {
1012
            removeFromRoster(userjid, convertIDToJID(contactid));
1013 1014 1015 1016 1017 1018 1019
        }
        catch (UserNotFoundException e) {
            // Pass it on through.
            throw e;
        }
    }

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    /**
     * Sync a user's roster with their legacy contact list.
     *
     * Given a collection of transport buddies, syncs up the user's
     * roster by fixing any nicknames, group assignments, adding and removing
     * roster items, and generally trying to make the jabber roster list
     * assigned to the transport's JID look at much like the legacy buddy
     * list as possible.  This is a very extensive operation.  You do not
     * want to do this very often.  Typically once right after the person
     * has logged into the legacy service.
     *
     * @param userjid JID of user who's roster we are syncing with.
     * @param legacyitems List of TransportBuddy's to be synced.
     * @throws UserNotFoundException if userjid not found.
     */
    public void syncLegacyRoster(JID userjid, List<TransportBuddy> legacyitems) throws UserNotFoundException {
        try {
            Roster roster = rosterManager.getRoster(userjid.getNode());

            // First thing first, we want to build ourselves an easy mapping.
            Map<JID,TransportBuddy> legacymap = new HashMap<JID,TransportBuddy>();
            for (TransportBuddy buddy : legacyitems) {
1042
                //Log.debug("ROSTERSYNC: Mapping "+buddy.getName());
1043
                legacymap.put(convertIDToJID(buddy.getName()), buddy);
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
            }

            // Now, lets go through the roster and see what matches up.
            for (RosterItem ri : roster.getRosterItems()) {
                if (!ri.getJid().getDomain().equals(this.jid.getDomain())) {
                    // Not our contact to care about.
                    continue;
                }
                if (ri.getJid().getNode() == null) {
                    // This is a transport instance, lets leave it alone.
                    continue;
                }
                JID jid = new JID(ri.getJid().toBareJID());
                if (legacymap.containsKey(jid)) {
1058
                    //Log.debug("ROSTERSYNC: We found, updating " + jid.toString());
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
                    // Ok, matched a legacy to jabber roster item
                    // Lets update if there are differences
                    TransportBuddy buddy = legacymap.get(jid);
                    try {
                        this.addOrUpdateRosterItem(userjid, buddy.getName(), buddy.getNickname(), buddy.getGroup());
                    }
                    catch (UserNotFoundException e) {
                        // TODO: Something is quite wrong if we see this.
                        Log.error("Failed updating roster item");
                    }
                    legacymap.remove(jid);
                }
                else {
1072
                    //Log.debug("ROSTERSYNC: We did not find, removing " + jid.toString());
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
                    // This person is apparantly no longer in the legacy roster.
                    try {
                        this.removeFromRoster(userjid, jid);
                    }
                    catch (UserNotFoundException e) {
                        // TODO: Something is quite wrong if we see this.
                        Log.error("Failed removing roster item");
                    }
                }
            }

            // Ok, we should now have only new items from the legacy roster
            for (TransportBuddy buddy : legacymap.values()) {
1086
                //Log.debug("ROSTERSYNC: We have new, adding " + buddy.getName());
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
                try {
                    this.addOrUpdateRosterItem(userjid, buddy.getName(), buddy.getNickname(), buddy.getGroup());
                }
                catch (UserNotFoundException e) {
                    // TODO: Something is quite wrong if we see this.
                    Log.error("Failed adding new roster item");
                }
            }
        }
        catch (UserNotFoundException e) {
            throw new UserNotFoundException("Could not find roster for " + userjid.toString());
        }
    }

1101 1102 1103 1104 1105 1106
    /**
     * Adds a registration with this transport.
     *
     * @param jid JID of user to add registration to.
     * @param username Legacy username of registration.
     * @param password Legacy password of registration.
1107
     * @param nickname Legacy nickname of registration.
1108 1109
     * @throws UserNotFoundException if registration or roster not found.
     */
1110
    public void addNewRegistration(JID jid, String username, String password, String nickname) throws UserNotFoundException {
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
        Collection<Registration> registrations = registrationManager.getRegistrations(jid, this.transportType);
        Boolean foundReg = false;
        for (Registration registration : registrations) {
            if (!registration.getUsername().equals(username)) {
                registrationManager.deleteRegistration(registration);
            }
            else {
                registration.setPassword(password);
                foundReg = true;
            }
        }

        if (!foundReg) {
1124
            registrationManager.createRegistration(jid, this.transportType, username, password, nickname);
1125 1126
        }

1127 1128 1129 1130 1131 1132 1133 1134

        // Clean up any leftover roster items from other transports.
        try {
            cleanUpRoster(jid, true);
        }
        catch (UserNotFoundException ee) {
            throw new UserNotFoundException("Unable to find roster.");
        }
1135

1136 1137 1138 1139 1140 1141 1142
        try {
            addOrUpdateRosterItem(jid, this.getJID(), this.getDescription(), "Transports");
        }
        catch (UserNotFoundException e) {
            throw new UserNotFoundException("User not registered with server.");
        }

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    }

    /**
     * Removes a registration from this transport.
     *
     * @param jid JID of user to add registration to.
     * @throws UserNotFoundException if registration or roster not found.
     */
    public void deleteRegistration(JID jid) throws UserNotFoundException {
        Collection<Registration> registrations = registrationManager.getRegistrations(jid, this.transportType);
        // For now, we're going to have to just nuke all of these.  Sorry.
        for (Registration reg : registrations) {
            registrationManager.deleteRegistration(reg);
        }

        // Clean up the user's contact list.
1159 1160 1161 1162 1163 1164 1165 1166 1167
        try {
            cleanUpRoster(jid, false);
        }
        catch (UserNotFoundException e) {
            throw new UserNotFoundException("Unable to find roster.");
        }
    }

    /**
1168
     * Cleans a roster of entries related to this transport that are not shared.
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
     *
     * This function will run through the roster of the specified user and clean up any
     * entries that share the domain of this transport.  This is primarily used during registration
     * to clean up leftovers from other transports.
     *
     * @param jid JID of user whose roster we want to clean up.
     * @param leaveDomain If set, we do not touch the roster item associated with the domain itself.
     * @throws UserNotFoundException if the user is not found.
     */
    public void cleanUpRoster(JID jid, Boolean leaveDomain) throws UserNotFoundException {
1179 1180 1181
        try {
            Roster roster = rosterManager.getRoster(jid.getNode());
            for (RosterItem ri : roster.getRosterItems()) {
1182
                if (ri.getJid().getDomain().equals(this.jid.getDomain())) {
1183 1184 1185 1186 1187 1188
                    if (ri.isShared()) {
                        continue;
                    }
                    if (leaveDomain && ri.getJid().getNode() == null) {
                        continue;
                    }
1189
                    try {
1190
                        Log.debug("Cleaning up roster entry " + ri.getJid().toString());
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
                        roster.deleteRosterItem(ri.getJid(), false);
                    }
                    catch (Exception e) {
                        Log.error("Error removing roster item: " + ri.toString());
                    }
                }
            }
        }
        catch (UserNotFoundException e) {
            throw new UserNotFoundException("Unable to find roster.");
        }
    }

1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    /**
     * Sends offline packets for an entire roster to the target user.
     *
     * This function will run through the roster of the specified user and send offline
     * presence packets for each roster item.   This is typically used when a user logs
     * off so that all of the associated roster items appear offline.  This also sends
     * the unavailable presence for the transport itself.
     *
     * @param jid JID of user whose roster we want to clean up.
     * @throws UserNotFoundException if the user is not found.
     */
    public void notifyRosterOffline(JID jid) throws UserNotFoundException {
        try {
            Roster roster = rosterManager.getRoster(jid.getNode());
            for (RosterItem ri : roster.getRosterItems()) {
                if (ri.getJid().getDomain().equals(this.jid.getDomain())) {
                    Presence p = new Presence(Presence.Type.unavailable);
                    p.setTo(jid);
                    p.setFrom(ri.getJid());
                    sendPacket(p);
                }
            }
        }
        catch (UserNotFoundException e) {
            throw new UserNotFoundException("Unable to find roster.");
        }
    }

1232 1233 1234 1235 1236 1237 1238 1239 1240
    /**
     * Sends a packet through the component manager as the component.
     *
     * @param packet Packet to be sent.
     */
    public void sendPacket(Packet packet) {
        try {
            this.componentManager.sendPacket(this, packet);
        }
1241
        catch (Exception e) {
1242 1243 1244 1245
            Log.error("Failed to deliver packet: " + packet.toString());
        }
    }

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    /**
     * Intercepts roster additions related to the gateway and flags them as non-persistent.
     *
     * @see org.jivesoftware.wildfire.roster.RosterEventListener#addingContact(org.jivesoftware.wildfire.roster.Roster, org.jivesoftware.wildfire.roster.RosterItem, boolean)
     */
    public boolean addingContact(Roster roster, RosterItem item, boolean persistent) {
        if (item.getJid().getDomain().equals(this.getJID()) && item.getJid().getNode() != null) {
            return false;
        }
        return persistent;
    }

    /**
     * Handles updates to a roster item that are not normally forwarded to the transport.
     *
     * @see org.jivesoftware.wildfire.roster.RosterEventListener#contactUpdated(org.jivesoftware.wildfire.roster.Roster, org.jivesoftware.wildfire.roster.RosterItem)
     */
    public void contactUpdated(Roster roster, RosterItem item) {
1264 1265 1266 1267
        if (!item.getJid().getDomain().equals(this.getJID().getDomain())) {
            // Not ours, not our problem.
            return;
        }
1268 1269 1270 1271
        if (item.getJid().getNode() == null) {
            // Gateway itself, don't care.
            return;
        }
1272 1273 1274 1275 1276 1277 1278
        try {
            TransportSession session = sessionManager.getSession(roster.getUsername());
            session.updateContact(item);
        }
        catch (NotFoundException e) {
            // Well we just don't care then.
        }
1279 1280 1281 1282 1283 1284 1285 1286
    }

    /**
     * Handles additions to a roster.  We don't really care because we hear about these via subscribes.
     *
     * @see org.jivesoftware.wildfire.roster.RosterEventListener#contactAdded(org.jivesoftware.wildfire.roster.Roster, org.jivesoftware.wildfire.roster.RosterItem)
     */
    public void contactAdded(Roster roster, RosterItem item) {
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
        if (!item.getJid().getDomain().equals(this.getJID().getDomain())) {
            // Not ours, not our problem.
            return;
        }
        try {
            TransportSession session = sessionManager.getSession(roster.getUsername());
            session.addContact(item);
        }
        catch (NotFoundException e) {
            // Well we just don't care then.
        }
1298 1299 1300 1301 1302 1303 1304 1305
    }

    /**
     * Handles deletions from a roster.  We don't really care because we hear about these via unsubscribes.
     *
     * @see org.jivesoftware.wildfire.roster.RosterEventListener#contactDeleted(org.jivesoftware.wildfire.roster.Roster, org.jivesoftware.wildfire.roster.RosterItem)
     */
    public void contactDeleted(Roster roster, RosterItem item) {
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
//        if (!item.getJid().getDomain().equals(this.getJID().getDomain())) {
//            // Not ours, not our problem.
//            return;
//        }
//        try {
//            TransportSession session = sessionManager.getSession(roster.getUsername());
//            session.removeContact(item);
//        }
//        catch (NotFoundException e) {
//            // TODO: Should maybe do something about this
//        }
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    }

    /**
     * Handles notifications of a roster being loaded.  Not sure we care.
     *
     * @see org.jivesoftware.wildfire.roster.RosterEventListener#rosterLoaded(org.jivesoftware.wildfire.roster.Roster)
     */
    public void rosterLoaded(Roster roster) {
        // Don't care
        // TODO: Evaluate if we could use this.
    }

1329 1330 1331 1332
    /**
     * Will handle logging in to the legacy service.
     *
     * @param registration Registration used for log in.
1333 1334 1335
     * @param jid JID that is logged into the transport.
     * @param presenceType Type of presence.
     * @param verboseStatus Longer status description.
1336 1337
     * @return A session instance for the new login.
     */
1338
    public abstract TransportSession registrationLoggedIn(Registration registration, JID jid, PresenceType presenceType, String verboseStatus, Integer priority);
1339 1340 1341 1342 1343 1344 1345 1346

    /**
     * Will handle logging out of the legacy service.
     *
     * @param session TransportSession to be logged out.
     */
    public abstract void registrationLoggedOut(TransportSession session);

1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    /**
     * Returns the terminology used for a username on the legacy service.
     *
     * @return String term for username.
     */
    public abstract String getTerminologyUsername();

    /**
     * Returns the terminology used for a password on the legacy service.
     *
     * @return String term for password.
     */
    public abstract String getTerminologyPassword();

1361 1362 1363 1364 1365 1366 1367 1368 1369
    /**
     * Returns the terminology used for a nickname on the legacy service.
     *
     * You can return null to indicate that this is not supported by the legacy service.
     *
     * @return String term for nickname.
     */
    public abstract String getTerminologyNickname();

1370 1371 1372 1373 1374 1375 1376 1377 1378
    /**
     * Returns instructions for registration in legacy complient terminology.
     *
     * You would write this out as if the entry textfields for the username and password
     * are after it/on the same page.  So something along these lines would be good:
     * Please enter your legacy username and password.
     */
    public abstract String getTerminologyRegistration();

1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
    /**
     * Returns true or false whether the password is required.
     */
    public abstract Boolean isPasswordRequired();

    /**
     * Returns true or false whether the nickname is required.
     */
    public abstract Boolean isNicknameRequired();

1389
}