aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/icq/ProtocolProviderServiceIcqImpl.java
blob: 140b9b81108d6b416dd675fae5de09541f7ab07a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
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
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
/*
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.protocol.icq;

import java.util.*;

import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import net.kano.joscar.flap.*;
import net.kano.joscar.flapcmd.*;
import net.kano.joscar.snaccmd.auth.*;
import net.kano.joustsim.*;
import net.kano.joustsim.oscar.*;
import net.kano.joustsim.oscar.oscar.loginstatus.*;
import net.kano.joustsim.oscar.oscar.service.*;
import net.kano.joustsim.oscar.oscar.service.icbm.*;
import net.kano.joustsim.oscar.proxy.*;

/**
 * An implementation of the protocol provider service over the AIM/ICQ protocol
 *
 * @author Emil Ivov
 * @author Damian Minkov
 */
public class ProtocolProviderServiceIcqImpl
    extends AbstractProtocolProviderService
{
    private static final Logger logger =
        Logger.getLogger(ProtocolProviderServiceIcqImpl.class);

    private DefaultAppSession session = null;

    private AimSession aimSession = null;

    private AimConnection aimConnection = null;

    private IcbmService icbmService = null;

    /**
     * Listener that catches all connection events originating from joscar
     * during connection to icq.
     */
    private AimConnStateListener aimConnStateListener = null;

    /**
     * Listener that catches all incoming and outgoing chat events generated
     * by joscar.
     */
    private AimIcbmListener aimIcbmListener = new AimIcbmListener();

    /**
     * indicates whether or not the provider is initialized and ready for use.
     */
    private boolean isInitialized = false;

    /**
     * We use this to lock access to initialization.
     */
    private Object initializationLock = new Object();

    /**
     * The identifier of the account that this provider represents.
     */
    private AccountID accountID = null;

    /**
     * Retrieves short or full user info, such as Name, Address, Nickname etc.
     */
    private InfoRetreiver infoRetreiver = null;

    /**
     * The icon corresponding to the icq protocol.
     */
    private ProtocolIconIcqImpl icqIcon
        = new ProtocolIconIcqImpl();

    /**
     * The icon corresponding to the aim protocol.
     */
    private ProtocolIconAimImpl aimIcon
        = new ProtocolIconAimImpl();

    /**
     *  Property whether we are using AIM or ICQ service
     */
    boolean USING_ICQ = true;

    /**
     * Used when we need to re-register
     */
    private SecurityAuthority authority = null;

    /**
     * Keeping track of the last fired registration state.
     */
    private RegistrationState lastRegistrationState = null;

    /**
     * Returns the state of the registration of this protocol provider
     * @return the <tt>RegistrationState</tt> that this provider is
     * currently in or null in case it is in a unknown state.
     */
    public RegistrationState getRegistrationState()
    {
        if(getAimConnection() == null)
            return RegistrationState.UNREGISTERED;

        State connState = getAimConnection().getState();

        return joustSimStateToRegistrationState(connState);
    }


    /**
     * Converts the specified joust sim connection state to a corresponding
     * RegistrationState.
     * @param jsState the joust sim connection state.
     * @return a RegistrationState corresponding best to the specified
     * joustSimState.
     */
    private RegistrationState joustSimStateToRegistrationState(State jsState)
    {
        return joustSimStateToRegistrationState(jsState, null);
    }

    /**
     * Converts the specified joust sim connection state to a corresponding
     * RegistrationState.
     * @param joustSimConnState the joust sim connection state.
     * @param joustSimConnStateInfo additional stateinfo if available (may be
     * null)
     * @return a RegistrationState corresponding best to the specified
     * joustSimState.
     */
    private RegistrationState joustSimStateToRegistrationState(
        State joustSimConnState,
        StateInfo joustSimConnStateInfo)
    {
        if(joustSimConnState == State.ONLINE)
            return RegistrationState.REGISTERED;
        else if (joustSimConnState == State.CONNECTING)
            return RegistrationState.REGISTERING;
        else if( joustSimConnState == State.AUTHORIZING)
            return RegistrationState.AUTHENTICATING;
        else if (joustSimConnState == State.CONNECTINGAUTH)
            return RegistrationState.AUTHENTICATING;
        else if (joustSimConnState == State.SIGNINGON)
            return RegistrationState.REGISTERING;
        else if (joustSimConnState == State.DISCONNECTED
                 || joustSimConnState == State.NOTCONNECTED)
        {
            if(joustSimConnStateInfo != null
                && joustSimConnStateInfo instanceof DisconnectedStateInfo
                && !((DisconnectedStateInfo)joustSimConnStateInfo).isOnPurpose())
            {
                return RegistrationState.CONNECTION_FAILED;
            }

            return RegistrationState.UNREGISTERED;
        }
        else if (joustSimConnState == State.FAILED)
        {
            if(joustSimConnStateInfo != null
                && joustSimConnStateInfo instanceof LoginFailureStateInfo)
            {
                LoginFailureInfo lfInfo = ((LoginFailureStateInfo)
                                joustSimConnStateInfo).getLoginFailureInfo();

                if (lfInfo instanceof AuthFailureInfo)
                    return RegistrationState.AUTHENTICATION_FAILED;
            }
            return RegistrationState.CONNECTION_FAILED;
        }
        else{
            logger.warn("Unknown state " + joustSimConnState
                        + ". Defaulting to " + RegistrationState.UNREGISTERED);
            return RegistrationState.UNREGISTERED;
        }
    }

    /**
     * Starts the registration process. Connection details such as
     * registration server, user name/number are provided through the
     * configuration service through implementation specific properties.
     *
     * @param authority the security authority that will be used for resolving
     *        any security challenges that may be returned during the
     *        registration or at any moment while wer're registered.
     *
     * @throws OperationFailedException with the corresponding code it the
     *        registration fails for some reason (e.g. a networking error or an
     *        implementation problem).
     */
    public void register(SecurityAuthority authority)
        throws OperationFailedException
    {
        if(authority == null)
            throw new IllegalArgumentException(
                "The register method needs a valid non-null authority impl "
                + " in order to be able and retrieve passwords.");

        // Keep the authority in case we need to re-register.
        this.authority = authority;

        connectAndLogin(authority, SecurityAuthority.AUTHENTICATION_REQUIRED);
    }

    /**
     * Reconnects if fails fire connection failed.
     * @param reasonCode the appropriate <tt>SecurityAuthority</tt> reasonCode,
     * which would specify the reason for which we're re-calling the login.
     */
    void reconnect(int reasonCode)
    {
        try
        {
            connectAndLogin(authority, reasonCode);
        }
        catch (OperationFailedException ex)
        {
            fireRegistrationStateChanged(
                getRegistrationState(),
                RegistrationState.CONNECTION_FAILED,
                RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);
        }
    }

    /**
     * Connects and logins to the server
     * @param authority SecurityAuthority
     * @throws  OperationFailedException if login parameters
     *          as server port are not correct
     */
    private void connectAndLogin(SecurityAuthority authority, int reasonCode)
        throws OperationFailedException
    {
        synchronized(initializationLock)
        {
            ProtocolProviderFactoryIcqImpl protocolProviderFactory = null;

            if(USING_ICQ)
                protocolProviderFactory
                    = IcqActivator.getIcqProtocolProviderFactory();
            else
                protocolProviderFactory
                    = IcqActivator.getAimProtocolProviderFactory();

            //verify whether a password has already been stored for this account
            String password
                = protocolProviderFactory.loadPassword(getAccountID());

            //decode
            if( password == null )
            {
                //create a default credentials object
                UserCredentials credentials = new UserCredentials();
                credentials.setUserName(this.getAccountID().getUserID());

                //request a password from the user
                credentials = authority.obtainCredentials(
                    getProtocolName(),
                    credentials,
                    reasonCode);

                // in case user has canceled the login window
                if(credentials == null)
                {
                    fireRegistrationStateChanged(
                        getRegistrationState(),
                        RegistrationState.UNREGISTERED,
                        RegistrationStateChangeEvent.REASON_USER_REQUEST, "");
                    return;
                }

                //extract the password the user passed us.
                char[] pass = credentials.getPassword();

                // the user didn't provide us a password (canceled the operation)
                if(pass == null)
                {
                    fireRegistrationStateChanged(
                        RegistrationState.UNREGISTERED,
                        RegistrationState.UNREGISTERED,
                        RegistrationStateChangeEvent.REASON_USER_REQUEST, "");
                    return;
                }

                password = new String(pass);

                if (credentials.isPasswordPersistent())
                {
                    protocolProviderFactory
                        .storePassword(getAccountID(), password);
                }
            }

            // it seems icq servers doesn't accept password with
            // length more then 8. But allow such registrations
            // we must trim such passwords to 8 characters
            if(USING_ICQ && password.length() > 8)
                password = password.substring(0, 8);

            //init the necessary objects
            session = new DefaultAppSession();
            aimSession = session.openAimSession(
                new Screenname(getAccountID().getUserID()));

            String proxyAddress =
                getAccountID().getAccountPropertyString(
                    ProtocolProviderFactory.PROXY_ADDRESS);
            if(proxyAddress != null && proxyAddress.length() > 0)
            {
                String proxyPortStr =
                    getAccountID().getAccountPropertyString(
                        ProtocolProviderFactory.PROXY_PORT);
                int proxyPort;
                try
                {
                    proxyPort = Integer.parseInt(proxyPortStr);
                }
                catch (NumberFormatException ex)
                {
                    throw new OperationFailedException("Wrong port",
                        OperationFailedException.INVALID_ACCOUNT_PROPERTIES, ex);
                }

                String proxyType =
                    getAccountID().getAccountPropertyString(
                        ProtocolProviderFactory.PROXY_TYPE);

                if(proxyType == null)
                    throw new OperationFailedException("Missing proxy type",
                        OperationFailedException.INVALID_ACCOUNT_PROPERTIES);

                String proxyUsername =
                    getAccountID().getAccountPropertyString(
                        ProtocolProviderFactory.PROXY_USERNAME);
                String proxyPassword =
                    getAccountID().getAccountPropertyString(
                        ProtocolProviderFactory.PROXY_PASSWORD);

                if(proxyType.equals("http"))
                {
                    // If we are using http proxy, sometimes
                    // default port 5190 is forbidden, so force
                    // http/https port
                    AimConnectionProperties connProps =
                        new AimConnectionProperties(
                            new Screenname(getAccountID().getUserID())
                            , password);
                    connProps.setLoginHost("login.icq.com");
                    connProps.setLoginPort(443);
                    aimConnection = aimSession.openConnection(connProps);
                    aimConnection.setProxy(
                        AimProxyInfo.forHttp(proxyAddress, proxyPort,
                                            proxyUsername, proxyPassword));
                }
                else
                {
                    aimConnection = aimSession.openConnection(
                        new AimConnectionProperties(
                            new Screenname(getAccountID().getUserID())
                            , password));

                    if(proxyType.equals("socks4"))
                    aimConnection.setProxy(
                        AimProxyInfo.forSocks4(proxyAddress, proxyPort,
                                               proxyUsername));
                    else if(proxyType.equals("socks5"))
                        aimConnection.setProxy(
                            AimProxyInfo.forSocks5(proxyAddress, proxyPort,
                                               proxyUsername, proxyPassword));
                }
            }
            else
            {
                aimConnection = aimSession.openConnection(
                        new AimConnectionProperties(
                            new Screenname(getAccountID().getUserID())
                            , password));
            }

            aimConnStateListener = new AimConnStateListener();
            aimConnection.addStateListener(aimConnStateListener);

            aimConnection.connect();
        }
    }

    /**
     * Ends the registration of this protocol provider with the service.
     */
    public void unregister()
    {
        if(aimConnection != null)
            aimConnection.disconnect(true);
    }

    /**
     * Returns the short name of the protocol that the implementation of this
     * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for
     * example).
     *
     * @return a String containing the short name of the protocol this
     *   service is taking care of.
     */
    public String getProtocolName()
    {
        if(USING_ICQ)
            return ProtocolNames.ICQ;
        else
            return ProtocolNames.AIM;
    }

    /**
     * Returns the protocol display name. This is the name that would be used
     * by the GUI to display the protocol name.
     *
     * @return a String containing the display name of the protocol this service
     * is implementing
     */
    public String getProtocolDisplayName()
    {
        if(USING_ICQ)
            return ProtocolNames.ICQ;
        else
            return ProtocolNames.AIM;
    }

    /**
     * Initialized the service implementation, and puts it in a sate where it
     * could interoperate with other services. It is strongly recomended that
     * properties in this Map be mapped to property names as specified by
     * <tt>AccountProperties</tt>.
     *
     * @param screenname the account id/uin/screenname of the account that
     * we're about to create
     * @param accountID the identifier of the account that this protocol
     * provider represents.
     *
     * @see net.java.sip.communicator.service.protocol.AccountID
     */
    protected void initialize(String screenname,
                              AccountID accountID)
    {
        synchronized(initializationLock)
        {
            this.accountID = accountID;

            if(IcqAccountID.isAIM(accountID.getAccountProperties()))
                    USING_ICQ = false;

            supportedOperationSets.put(OperationSetInstantMessageTransform.class.getName(), 
                new OperationSetInstantMessageTransformImpl());
            
            //initialize the presence operationset
            OperationSetPersistentPresence persistentPresence =
                new OperationSetPersistentPresenceIcqImpl(this, screenname);

            supportedOperationSets.put(
                OperationSetPersistentPresence.class.getName(),
                persistentPresence);

            //register it once again for those that simply need presence
            supportedOperationSets.put( OperationSetPresence.class.getName(),
                                        persistentPresence);

            //initialize the IM operation set
            OperationSetBasicInstantMessaging basicInstantMessaging =
                new OperationSetBasicInstantMessagingIcqImpl(this);

            supportedOperationSets.put(
                OperationSetBasicInstantMessaging.class.getName(),
                basicInstantMessaging);
            
          //initialize the multi chat operation set
           OperationSetMultiUserChatIcqImpl multiUserOpSet = new OperationSetMultiUserChatIcqImpl(
                   this);

           supportedOperationSets.put(OperationSetMultiUserChat.class
                   .getName(), multiUserOpSet);

            //initialize the typing notifications operation set
            OperationSetTypingNotifications typingNotifications =
                new OperationSetTypingNotificationsIcqImpl(this);

            supportedOperationSets.put(
                OperationSetTypingNotifications.class.getName(),
                typingNotifications);

            if(USING_ICQ)
            {
                this.infoRetreiver = new InfoRetreiver(this, screenname);

                OperationSetServerStoredContactInfo serverStoredContactInfo =
                    new OperationSetServerStoredContactInfoIcqImpl
                        (infoRetreiver, this);

                supportedOperationSets.put(
                    OperationSetServerStoredContactInfo.class.getName(),
                    serverStoredContactInfo);


                OperationSetServerStoredAccountInfo serverStoredAccountInfo =
                    new OperationSetServerStoredAccountInfoIcqImpl
                        (infoRetreiver, screenname, this);

                supportedOperationSets.put(
                    OperationSetServerStoredAccountInfo.class.getName(),
                    serverStoredAccountInfo);

                OperationSetWebAccountRegistration webAccountRegistration =
                    new OperationSetWebAccountRegistrationIcqImpl();
                supportedOperationSets.put(
                    OperationSetWebAccountRegistration.class.getName(),
                    webAccountRegistration);

                OperationSetWebContactInfo webContactInfo =
                    new OperationSetWebContactInfoIcqImpl();
                supportedOperationSets.put(
                    OperationSetWebContactInfo.class.getName(),
                    webContactInfo);

                OperationSetExtendedAuthorizationsIcqImpl extendedAuth =
                    new OperationSetExtendedAuthorizationsIcqImpl(this);
                supportedOperationSets.put(
                    OperationSetExtendedAuthorizations.class.getName(),
                    extendedAuth);

            }

            OperationSetFileTransferIcqImpl fileTransferOpSet =
                    new OperationSetFileTransferIcqImpl(this);
                supportedOperationSets.put(
                    OperationSetFileTransfer.class.getName(),
                    fileTransferOpSet);

            isInitialized = true;
        }
    }

    /**
     * Makes the service implementation close all open sockets and release
     * any resources that it might have taken and prepare for
     * shutdown/garbage collection.
     */
    public void shutdown()
    {
        /** @todo is there anything else to add here? */
        synchronized(initializationLock){
            icbmService = null;
            session = null;
            aimSession = null;
            aimConnection = null;
            aimConnStateListener = null;
            aimIcbmListener = null;
            isInitialized = false;
        }
    }

    /**
     * Returns true if the provider service implementation is initialized and
     * ready for use by other services, and false otherwise.
     *
     * @return true if the provider is initialized and ready for use and false
     * otherwise
     */
    public boolean isInitialized()
    {
        return isInitialized;
    }

    /**
     * Returns the AccountID that uniquely identifies the account represented
     * by this instance of the ProtocolProviderService.
     * @return the id of the account represented by this provider.
     */
    public AccountID getAccountID()
    {
        return accountID;
    }

    /**
     * Creates a RegistrationStateChange event corresponding to the specified
     * old and new joust sim states and notifies all currently registered
     * listeners.
     *
     * @param oldJoustSimState the state that the joust sim connection had
     * before the change occurred
     * @param oldJoustSimStateInfo the state info associated with the state of
     * the underlying connection state as it is after the change.
     * @param newJoustSimState the state that the underlying joust sim
     * connection is currently in.
     * @param newJoustSimStateInfo the state info associated with the state of
     * the underlying connection state as it was before the change.
     * @param reasonCode a value corresponding to one of the REASON_XXX fields
     * of the RegistrationStateChangeEvent class, indicating the reason for this
     * state transition.
     * @param reason a String further explaining the reason code or null if
     * no such explanation is necessary.
     */
    private void fireRegistrationStateChanged(  State      oldJoustSimState,
                                                StateInfo oldJoustSimStateInfo,
                                                State     newJoustSimState,
                                                StateInfo newJoustSimStateInfo,
                                                int       reasonCode,
                                                String    reason)
    {
        RegistrationState oldRegistrationState
            = joustSimStateToRegistrationState(oldJoustSimState
                                               , oldJoustSimStateInfo);
        RegistrationState newRegistrationState
            = joustSimStateToRegistrationState(newJoustSimState
                                               , newJoustSimStateInfo);

        fireRegistrationStateChanged(oldRegistrationState, newRegistrationState
                                     , reasonCode, reason);
    }

    /**
     * Creates a RegistrationStateChange event corresponding to the specified
     * old and new states and notifies all currently registered listeners.
     *
     * @param oldState the state that the provider had before the change
     * occurred
     * @param newState the state that the provider is currently in.
     * @param reasonCode a value corresponding to one of the REASON_XXX fields
     * of the RegistrationStateChangeEvent class, indicating the reason for
     * this state transition.
     * @param reason a String further explaining the reason code or null if
     * no such explanation is necessary.
     */
    public void fireRegistrationStateChanged( RegistrationState oldState,
                                               RegistrationState newState,
                                               int               reasonCode,
                                               String            reason)
    {
        if(newState.equals(RegistrationState.CONNECTION_FAILED) &&
            isRegistered())
        {
            // if for some reason (keep alive failed) and connection is
            // still connected disconneted
            unregister();
        }

        lastRegistrationState = newState;

        super.fireRegistrationStateChanged(oldState, newState, reasonCode, reason);
    }

    /**
     * Returns the info retriever that we've initialized for the current
     * session.
     *
     * @return the info retriever that we've initialized for the current
     * session.
     */
    protected InfoRetreiver getInfoRetreiver()
    {
        return infoRetreiver;
    }

    /**
     * This class handles connection state events that have originated in this
     * provider's aim connection. Events are acted upon accordingly and,
     * if necessary, forwarded to registered listeners (asynchronously).
     */
    private class AimConnStateListener implements StateListener
    {
        public void handleStateChange(StateEvent event)
        {
            State newState = event.getNewState();
            State oldState = event.getOldState();

            AimConnection conn = event.getAimConnection();
            logger.debug("ICQ protocol provider " + getProtocolName()
                         + " changed registration status from "
                         + oldState + " to " + newState);

            int reasonCode = RegistrationStateChangeEvent.REASON_NOT_SPECIFIED;
            String reasonStr = null;

            if (newState == State.ONLINE)
            {
                icbmService = conn.getIcbmService();
                icbmService.addIcbmListener(aimIcbmListener);

                conn.getInfoService().
                    getOscarConnection().getSnacProcessor().
                        getFlapProcessor().addPacketListener(
                            new ConnectionClosedListener(conn));
            }
            else if (newState == State.DISCONNECTED)
            {
                // we need a Service here. no metter which
                // I've choose BosService
                // we just need the oscar conenction from the service
                Service service = aimConnection.getBosService();
                if(service != null)
                {
                    int discconectCode = service.getOscarConnection()
                        .getLastCloseCode();
                    reasonCode = ConnectionClosedListener
                        .convertCodeToRegistrationStateChangeEvent(
                            discconectCode);
                    reasonStr = ConnectionClosedListener
                        .convertCodeToStringReason(discconectCode);
                    logger.debug(
                        "The aim Connection was disconnected! with reason : "
                        + reasonStr);
                }
                else
                    logger.debug("The aim Connection was disconnected!");
            }
            else
                if(newState == State.FAILED)
                {
                    logger.debug("The aim Connection failed! "
                                 + event.getNewStateInfo());
                }

            if(event.getNewStateInfo() instanceof LoginFailureStateInfo)
            {
                LoginFailureInfo loginFailure =
                    ((LoginFailureStateInfo)event.getNewStateInfo())
                        .getLoginFailureInfo();

                if(loginFailure instanceof AuthFailureInfo)
                {
                    AuthFailureInfo afi = (AuthFailureInfo)loginFailure;
                    logger.debug("AuthFailureInfo code : " +
                                 afi.getErrorCode());
                    int code =  ConnectionClosedListener
                        .convertAuthCodeToReasonCode(afi);
                    reasonCode = ConnectionClosedListener
                        .convertCodeToRegistrationStateChangeEvent(code);
                    reasonStr = ConnectionClosedListener
                        .convertCodeToStringReason(code);
                }
            }

            //as a side note - if this was an AuthenticationFailed error
            //set the stored password to null so that we don't use it any more.
            if(reasonCode == RegistrationStateChangeEvent
                .REASON_AUTHENTICATION_FAILED)
            {
                if(USING_ICQ)
                    IcqActivator.getIcqProtocolProviderFactory().storePassword(
                        getAccountID(), null);
                else
                    IcqActivator.getAimProtocolProviderFactory().storePassword(
                        getAccountID(), null);

                reconnect(SecurityAuthority.WRONG_PASSWORD);
            }

            if (newState == State.ONLINE)
            {
                // we will fire FINALIZING_REGISTRATION and will wait
                // for the registration to finnish.
                fireRegistrationStateChanged(lastRegistrationState,
                    RegistrationState.FINALIZING_REGISTRATION, -1, null);

                // we must wait a little bit before firing registered
                // event , waiting for ClientReadyCommand to be sent successfully
                new RegisteredEventThread().start();
            }
            else
            {
                //now tell all interested parties about what happened.
                fireRegistrationStateChanged(
                    oldState,
                    event.getOldStateInfo(),
                    newState,
                    event.getNewStateInfo(),
                    reasonCode,
                    reasonStr);
            }
        }
    }

    private class RegisteredEventThread extends Thread
    {
        public void run()
        {
            Object w = new Object();
            synchronized(w)
            {
                try
                {
                    w.wait(2000);
                }
                catch (Exception e)
                {}
            }

            fireRegistrationStateChanged(lastRegistrationState,
                RegistrationState.REGISTERED, -1, null);
        }
    }

    /**
     * Returns the <tt>AimSession</tt> opened by this provider.
     * @return a reference to the <tt>AimSession</tt> that this provider
     * last opened.
     */
    protected AimSession getAimSession()
    {
        return aimSession;
    }

    /**
     * Returns the <tt>AimConnection</tt>opened by this provider
     * @return a reference to the <tt>AimConnection</tt> last opened by this
     * provider.
     */
    protected AimConnection getAimConnection()
    {
        return aimConnection;
    }

    public static class AimIcbmListener implements IcbmListener
    {

        public void newConversation(IcbmService service, Conversation conv)
        {
            logger.debug("Received a new conversation event");
            conv.addConversationListener(new AimConversationListener());
        }

        public void buddyInfoUpdated(IcbmService service, Screenname buddy,
                                     IcbmBuddyInfo info)
        {
            logger.debug("Got a BuddINFO event");
        }

        public void sendAutomaticallyFailed(
            IcbmService service,
            net.kano.joustsim.oscar.oscar.service.icbm.Message message,
            Set triedConversations)
        {
        }
    }

    public static class AimConversationListener
        implements ConversationListener
    {
        public void sentOtherEvent(Conversation conversation,
                                   ConversationEventInfo event)
        {
            logger.debug("reveived ConversationEventInfo:" + event);
        }

        // This may be called without ever calling conversationOpened
        public void conversationClosed(Conversation co)
        {
            logger.debug("conversation closed");
        }

        public void gotOtherEvent(Conversation conversation,
                                  ConversationEventInfo event)
        {
            logger.debug("goet other event");
            if(event instanceof TypingInfo)
            {
                TypingInfo ti = (TypingInfo)event;
                logger.debug("got typing info and state is: "
                             + ti.getTypingState());
            }
            else if (event instanceof MessageInfo)
            {
                MessageInfo ti = (MessageInfo)event;
                logger.debug("got message info for msg: " + ti.getMessage());
            }
        }

        public void canSendMessageChanged(Conversation con, boolean canSend)
        {
            logger.debug("can send message event");
        }

        // This may never be called
        public void conversationOpened(Conversation con)
        {
            logger.debug("conversation opened event");
        }

        // This may be called after conversationClosed is called
        public void sentMessage(Conversation con, MessageInfo minfo)
        {
            logger.debug("sent message event");
        }

        // This may be called after conversationClosed is called.
        public void gotMessage(Conversation con, MessageInfo minfo)
        {
            logger.debug("got message event"
                         + minfo.getMessage().getMessageBody());
        }

    }

    /**
     * Fix for late close conenction due to
     * multiple logins.
     * Listening for incoming packets for the close command
     * when this is received we discconect the session to force it
     * because otherwise is wait for timeout of reading from the socket stream
     * which leads to from 10 to 20 seconds delay of closing the session
     * and connection
     * */
    public static class ConnectionClosedListener
        implements FlapPacketListener
    {
        private AimConnection aimConnection = null;

        private final static int REASON_MULTIPLE_LOGINS = 0x0001;
        private final static int REASON_BAD_PASSWORD_A = 0x0004;
        private final static int REASON_BAD_PASSWORD_B = 0x0005;
        private final static int REASON_NON_EXISTING_ICQ_UIN_A = 0x0007;
        private final static int REASON_NON_EXISTING_ICQ_UIN_B = 0x0008;
        private final static int REASON_MANY_CLIENTS_FROM_SAME_IP_A = 0x0015;
        private final static int REASON_MANY_CLIENTS_FROM_SAME_IP_B = 0x0016;
        private final static int REASON_CONNECTION_RATE_EXCEEDED = 0x0018;
        private final static int REASON_CONNECTION_TOO_FAST = 0x001D;
        private final static int REASON_TRY_AGAIN = 0x001E;

        private final static String REASON_STRING_MULTIPLE_LOGINS
            = "multiple logins (on same UIN)";
        private final static String REASON_STRING_BAD_PASSWORD
            = "bad password";
        private final static String REASON_STRING_NON_EXISTING_ICQ_UIN
            = "non-existant UIN";
        private final static String REASON_STRING_MANY_CLIENTS_FROM_SAME_IP
            = "too many clients from same IP";
        private final static String REASON_STRING_CONNECTION_RATE_EXCEEDED
            = "Rate exceeded. The server temporarily bans you.";
        private final static String REASON_STRING_CONNECTION_TOO_FAST
            = "You are reconnecting too fast";
        private final static String REASON_STRING_TRY_AGAIN
            = "Can't register on ICQ network, try again soon.";
        private final static String REASON_STRING_NOT_SPECIFIED
            = "Not Specified";

        ConnectionClosedListener(AimConnection aimConnection)
        {
            this.aimConnection = aimConnection;
        }


        public void handleFlapPacket(FlapPacketEvent evt)
        {
            FlapCommand flapCommand = evt.getFlapCommand();
            if (flapCommand instanceof CloseFlapCmd)
            {
                CloseFlapCmd closeCmd = (CloseFlapCmd)flapCommand;
                logger.trace("received close command with code : "
                             + closeCmd.getCode());

                aimConnection.disconnect();
            }
        }

        /**
         * Converts the codes in the close command
         * or the lastCloseCode of OscarConnection to the states
         * which are registered in the service protocol events
         *
         * @param reasonCode int the reason of close connection
         * @return int corresponding RegistrationStateChangeEvent
         */
        static int convertCodeToRegistrationStateChangeEvent(int reasonCode)
        {
            switch(reasonCode)
            {
                case REASON_MULTIPLE_LOGINS :
                    return RegistrationStateChangeEvent
                        .REASON_MULTIPLE_LOGINS;
                case REASON_BAD_PASSWORD_A :
                    return RegistrationStateChangeEvent
                        .REASON_AUTHENTICATION_FAILED;
                case REASON_BAD_PASSWORD_B :
                    return RegistrationStateChangeEvent
                        .REASON_AUTHENTICATION_FAILED;
                case REASON_NON_EXISTING_ICQ_UIN_A :
                    return RegistrationStateChangeEvent
                        .REASON_NON_EXISTING_USER_ID;
                case REASON_NON_EXISTING_ICQ_UIN_B :
                    return RegistrationStateChangeEvent
                        .REASON_NON_EXISTING_USER_ID;
                case REASON_MANY_CLIENTS_FROM_SAME_IP_A :
                    return RegistrationStateChangeEvent
                        .REASON_CLIENT_LIMIT_REACHED_FOR_IP;
                case REASON_MANY_CLIENTS_FROM_SAME_IP_B :
                    return RegistrationStateChangeEvent
                        .REASON_CLIENT_LIMIT_REACHED_FOR_IP;
                case REASON_CONNECTION_RATE_EXCEEDED :
                    return RegistrationStateChangeEvent
                        .REASON_RECONNECTION_RATE_LIMIT_EXCEEDED;
                case REASON_CONNECTION_TOO_FAST :
                    return RegistrationStateChangeEvent
                        .REASON_RECONNECTION_RATE_LIMIT_EXCEEDED;
                case REASON_TRY_AGAIN :
                    return RegistrationStateChangeEvent
                        .REASON_RECONNECTION_RATE_LIMIT_EXCEEDED;
                default :
                    return RegistrationStateChangeEvent
                        .REASON_NOT_SPECIFIED;
            }
        }

        /**
         * returns the reason string corresponding to the code
         * in the close command
         *
         * @param reasonCode int the reason of close connection
         * @return String describing the reason
         */
        static String convertCodeToStringReason(int reasonCode)
        {
            switch(reasonCode)
            {
                case REASON_MULTIPLE_LOGINS :
                    return REASON_STRING_MULTIPLE_LOGINS;
                case REASON_BAD_PASSWORD_A :
                    return REASON_STRING_BAD_PASSWORD;
                case REASON_BAD_PASSWORD_B :
                    return REASON_STRING_BAD_PASSWORD;
                case REASON_NON_EXISTING_ICQ_UIN_A :
                    return REASON_STRING_NON_EXISTING_ICQ_UIN;
                case REASON_NON_EXISTING_ICQ_UIN_B :
                    return REASON_STRING_NON_EXISTING_ICQ_UIN;
                case REASON_MANY_CLIENTS_FROM_SAME_IP_A :
                    return REASON_STRING_MANY_CLIENTS_FROM_SAME_IP;
                case REASON_MANY_CLIENTS_FROM_SAME_IP_B :
                    return REASON_STRING_MANY_CLIENTS_FROM_SAME_IP;
                case REASON_CONNECTION_RATE_EXCEEDED :
                    return REASON_STRING_CONNECTION_RATE_EXCEEDED;
                case REASON_CONNECTION_TOO_FAST :
                    return REASON_STRING_CONNECTION_TOO_FAST;
                case REASON_TRY_AGAIN :
                    return REASON_STRING_TRY_AGAIN;
                default :
                    return REASON_STRING_NOT_SPECIFIED;
            }
        }

        /**
         * When receiving login failure
         * the reasons for the failure are in the authorization
         * part of the protocol ( 0x13 )
         * In the AuthResponse are the possible reason codes
         * here they are converted to those in the ConnectionClosedListener
         * so the they can be converted to the one in service protocol events
         *
         * @param afi AuthFailureInfo the failure info
         * @return int the corresponding code to this failure
         */
        static int convertAuthCodeToReasonCode(AuthFailureInfo afi)
        {
            switch(afi.getErrorCode())
            {
                case AuthResponse.ERROR_BAD_PASSWORD :
                    return REASON_BAD_PASSWORD_A;
                case AuthResponse.ERROR_CONNECTING_TOO_MUCH_A :
                    return REASON_CONNECTION_RATE_EXCEEDED;
                case AuthResponse.ERROR_CONNECTING_TOO_MUCH_B :
                    return REASON_CONNECTION_RATE_EXCEEDED;
                case AuthResponse.ERROR_INVALID_SN_OR_PASS_A :
                    return REASON_NON_EXISTING_ICQ_UIN_A;
                case AuthResponse.ERROR_INVALID_SN_OR_PASS_B :
                    return REASON_NON_EXISTING_ICQ_UIN_B;
                // 16 is also used for blocked from same IP
                case 16 :
                    return REASON_MANY_CLIENTS_FROM_SAME_IP_A;
                case AuthResponse.ERROR_SIGNON_BLOCKED :
                    return REASON_MANY_CLIENTS_FROM_SAME_IP_B;
                default :
                    return RegistrationStateChangeEvent.REASON_NOT_SPECIFIED;
            }
        }
    }

    /**
     * Returns the icq/aim protocol icon.
     * @return the icq/aim protocol icon
     */
    public ProtocolIcon getProtocolIcon()
    {
        if(USING_ICQ)
            return icqIcon;
        else
            return aimIcon;
    }
}