source: trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/Connect.java @ 1001

Revision 1001, 26.1 KB checked in by alexandrecorreia, 15 years ago (diff)

Ticket #552 - Inclusão do projeto Java referente ao applet do módulo.

Line 
1/*
2 *      Jeti, a Java Jabber client, Copyright (C) 2003 E.S. de Boer 
3 *
4 *  This program is free software; you can redistribute it and/or modify
5 *  it under the terms of the GNU General Public License as published by
6 *  the Free Software Foundation; either version 2 of the License, or
7 *  (at your option) any later version.
8 *
9 *  This program is distributed in the hope that it will be useful,
10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 *      GNU General Public License for more details.
13 *
14 *  You should have received a copy of the GNU General Public License
15 *  along with this program; if not, write to the Free Software
16 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 *
18 *      For questions, comments etc,
19 *      use the website at http://jeti.jabberstudio.org
20 *  or mail/im me at jeti@jabber.org
21 */
22
23package nu.fw.jeti.backend;
24
25import java.io.IOException;
26import java.io.InputStream;
27import java.io.OutputStream;
28import java.io.UnsupportedEncodingException;
29import java.net.InetAddress;
30import java.net.Socket;
31import java.net.UnknownHostException;
32import java.security.KeyManagementException;
33import java.security.MessageDigest;
34import java.security.NoSuchAlgorithmException;
35import java.security.cert.CertificateExpiredException;
36import java.security.cert.CertificateNotYetValidException;
37import java.security.cert.X509Certificate;
38import java.text.MessageFormat;
39import java.util.Iterator;
40
41import javax.net.ssl.HandshakeCompletedEvent;
42import javax.net.ssl.HandshakeCompletedListener;
43import javax.net.ssl.SSLContext;
44import javax.net.ssl.SSLSocket;
45import javax.net.ssl.SSLSocketFactory;
46import javax.net.ssl.TrustManager;
47import javax.net.ssl.X509TrustManager;
48import javax.swing.JOptionPane;
49
50import nu.fw.jeti.events.DiscoveryListener;
51import nu.fw.jeti.events.LoginListener;
52import nu.fw.jeti.jabber.Backend;
53import nu.fw.jeti.jabber.JID;
54import nu.fw.jeti.jabber.elements.DiscoveryInfo;
55import nu.fw.jeti.jabber.elements.DiscoveryItem;
56import nu.fw.jeti.jabber.elements.IQAuth;
57import nu.fw.jeti.jabber.elements.IQAuthBuilder;
58import nu.fw.jeti.jabber.elements.IQExtension;
59import nu.fw.jeti.jabber.elements.IQPrivate;
60import nu.fw.jeti.jabber.elements.IQXRoster;
61import nu.fw.jeti.jabber.elements.InfoQuery;
62import nu.fw.jeti.jabber.elements.JetiPrivateExtension;
63import nu.fw.jeti.jabber.elements.JetiPrivateRosterExtension;
64import nu.fw.jeti.jabber.elements.Packet;
65import nu.fw.jeti.jabber.elements.Presence;
66import nu.fw.jeti.jabber.elements.PresenceBuilder;
67import nu.fw.jeti.jabber.elements.StreamError;
68import nu.fw.jeti.plugins.OpenPGP;
69import nu.fw.jeti.plugins.PluginsInfo;
70import nu.fw.jeti.plugins.XMPP;
71import nu.fw.jeti.util.I18N;
72import nu.fw.jeti.util.Log;
73import nu.fw.jeti.util.Utils;
74
75/**
76 * @author E.S. de Boer
77 */
78
79//TODO stop packet start spul en de andere dingen in aparte class??
80//TODO improve error reporting, make it translatable
81 //class voor connectie
82 public class Connect implements ConnectionPacketReceiver
83{
84        private Output output;
85        private Input input;
86        private String authenticationId="yytr";
87        private JabberHandler jabberHandler;
88        private LoginInfo loginInfo;
89        private Backend backend;
90        private static JID myJID = new JID("test","test","test");
91        private boolean authenticated = false;
92        private boolean reconnecting = false;
93        private long latestConnected=0;
94        private int show;
95        private String status;
96        private String connectionID;
97        private Discovery discovery;
98        private OwnCapabilities capabilities;
99        private Socket socket;//socket needed to close if abort
100        private Thread connectThread;//login thread
101        private volatile boolean abort = false;//abort login
102        private OpenPGP openPGP;
103        private IQTimerQueue iqTimerQueue;
104        private Handlers handlers;
105        private XMPP xmpp;
106   
107        public Connect(Backend backend,IQTimerQueue timerQueue,Handlers handlers)
108        {
109                this.backend = backend;
110                iqTimerQueue = timerQueue;
111                this.handlers = handlers;
112                discovery = new Discovery(backend) ;
113                capabilities = new OwnCapabilities(backend);
114        }
115
116        public void addCapability(String capability,String feature)
117        {
118                capabilities.addCapability(capability, feature);
119        }
120       
121        public void removeCapability(String capability,String feature)
122        {
123                capabilities.removeCapability(capability, feature);
124        }
125       
126        public int getStatus()
127        {
128                return show;
129        }
130       
131        public void getItems(JID jid, DiscoveryListener listener, boolean useCache)
132        {
133                discovery.getItems(jid,listener,useCache);
134        }
135       
136        public void getItems(JID jid, DiscoveryListener listener)
137        {
138                discovery.getItems(jid,listener);
139        }
140       
141        public void getInfo(JID jid, DiscoveryListener listener)
142        {
143                discovery.getInfo(jid,listener);
144        }
145       
146        public void getItems(JID jid,String node, DiscoveryListener listener)
147        {
148                discovery.getItems(jid,node,listener);
149        }
150       
151        public void getInfo(JID jid,String node, DiscoveryListener listener)
152        {
153                discovery.getInfo(jid,node,listener);
154        }
155       
156        public boolean isLoggedIn()
157        {
158                return authenticated;
159        }
160       
161        public boolean isPasswordValid(String password)
162        {
163                return loginInfo.getPassword().equals(password);
164        }
165
166    public void login(LoginInfo info)
167    {
168        if(PluginsInfo.isPluginLoaded("openpgp"))
169        {
170                openPGP =  (OpenPGP)PluginsInfo.getPluginInstance("openpgp");
171        }
172        abort = false;
173                loginInfo = info;
174                connectThread = new Thread()
175                {
176                        public void run()
177                        {
178                                connect();
179                        }
180                };
181                connectThread.start();
182    }
183   
184        public void autoLogin(LoginInfo info,final int tries)
185        {
186                if(System.currentTimeMillis() < latestConnected + 60000)
187                {//prevent ping pong if things go wrong at login
188                        return;
189                }
190                abort = false;
191                loginInfo = info;
192                connectThread = new Thread()
193                {
194                        int tel = 0;
195                        public void run()
196                        {
197                                boolean connected=false;
198                                while(tel < tries)
199                                {
200                                        connected = connect();
201                                        if(connected) break;
202                                        try
203                                        {
204                                                Thread.sleep(60000);
205                                        }
206                                        catch (InterruptedException e){}
207                                        tel++;
208                                }
209                        }
210                };
211                connectThread.start();
212        }
213   
214    public void abort()
215    {
216                abort = true;
217                if(socket != null)
218                {
219                        try
220                        {
221                                socket.close();
222                        }
223                        catch (IOException e)
224                        {
225                                e.printStackTrace();
226                        }
227                }
228        connectThread.interrupt();
229                disconnect();
230    }
231   
232    public boolean isAborted()
233    {
234        return abort;
235    }
236
237        synchronized private boolean connect()
238        {       
239                latestConnected = System.currentTimeMillis();
240               
241                if( loginInfo == null )
242                        return true;
243
244                if( authenticated )
245                        disconnect();//clear old connection
246               
247                if (loginInfo.useProxy(LoginInfo.SOCKS_PROXY))
248                {
249                        System.getProperties().put( "proxySet", "true" );
250                        System.getProperties().setProperty("socksProxyHost", loginInfo.getProxyServer());
251                        System.getProperties().setProperty("socksProxyPort", loginInfo.getProxyPort());
252                        System.getProperties().setProperty("socksProxyUserName", loginInfo.getProxyUsername());
253                        if(loginInfo.getProxyPassword()!=null)System.getProperties().setProperty("socksProxyPassword", loginInfo.getProxyPassword());
254                }
255               
256                jabberHandler = new JabberHandler(this,handlers);
257               
258                if( xmpp == null && PluginsInfo.isPluginLoaded("xmpp") )
259                {
260                        xmpp = (XMPP)PluginsInfo.newPluginInstance("xmpp");
261                        handlers.loadExtraHandlers(xmpp.getXMPPHandlers());
262                }
263                               
264                try
265                {               
266            host = loginInfo.getHost();
267            if (host == null || host.length() == 0)
268            {
269                if(loginInfo.useProxy(LoginInfo.NO_PROXY) && PluginsInfo.isPluginLoaded("xmpp"))
270                {
271                        host = xmpp.resolveXMPPDomain(loginInfo.getServer());
272                }
273                else host = loginInfo.getServer();
274            }
275                       
276                        if(loginInfo.isSSl())
277                {
278                                if( loginInfo.isHTTPProxy() && loginInfo.getJavaProxy() )
279                        {
280                                        Socket tunnel = createHTTPTunel(host);
281                                socket = new DummySSLSocketFactory().createSocket(tunnel,host,loginInfo.getPort(),true);
282                        }
283                                else
284                                        socket = new DummySSLSocketFactory().createSocket(host,loginInfo.getPort());
285                }
286                else
287                {
288                        socket = new Socket(host,loginInfo.getPort());
289                }
290        }
291                catch (UnknownHostException ex)
292        {
293            sendLoginError(MessageFormat.format(I18N.gettext("main.loginstatus.Server_{0}_could_not_be_found"), new Object[] { loginInfo.getHost() } ));
294                        return false;
295        }
296                catch (IOException ex)
297                {
298                        sendLoginError(ex.getMessage());
299                        return false;
300        }
301                if( abort )
302                        return false;
303               
304                try
305                {
306                        input = new Input(socket.getInputStream(),this,jabberHandler);
307        }
308                catch (IOException ex)
309        {
310                        sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_input_because") + " " + ex.getMessage());
311                        return false;
312        }
313               
314                if( abort )
315                        return false;
316               
317            try
318            {
319                        output = new Output(socket,loginInfo.getServer(),this,socket.getOutputStream());
320        }
321            catch (IOException ex)
322        {
323                        sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_output_because") + " " +ex.getMessage());
324                        return false;
325        }
326
327        return true;
328        }
329       
330        String host;
331       
332        public boolean startTls(ConnectionPacketReceiver cpr)
333        {
334                if(abort)return false;
335                try{           
336           //TODO stop output
337                        output.disconnect(false);
338                        input.disconnect();
339            socket = new DummySSLSocketFactory().createSocket(socket,host,loginInfo.getPort(),true);
340            jabberHandler = new JabberHandler(cpr,handlers);
341         
342           
343            try{
344                    input = new Input(socket.getInputStream(),this,jabberHandler);
345                }catch (IOException ex)
346                {
347                                sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_input_because") + " " + ex.getMessage());
348                                return false;
349                }
350               
351            try{
352                        output = new Output(socket,loginInfo.getServer(),this,socket.getOutputStream());
353                }catch (IOException ex)
354                {
355                                sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_output_because") + " " +ex.getMessage());
356                                return false;
357                }
358                           
359                if(abort) return false;
360               
361                }catch (IOException e) {e.printStackTrace();}
362                return true;
363        }
364       
365        //used by compression plugin
366        public Socket getSocket(){
367                return socket;
368        }
369       
370        public boolean startCompressed(ConnectionPacketReceiver cpr,InputStream inputStream,OutputStream outputStream)
371        {
372                jabberHandler = new JabberHandler(cpr,handlers);
373                if ( abort )
374                        return false;
375                output.disconnect(false);
376                Input input2 = input;
377                input = new Input(inputStream,this,jabberHandler);
378        try
379        {
380                output = new Output(socket,loginInfo.getServer(),this,outputStream);
381        }
382        catch (IOException ex)
383        {
384                        sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_output_because") + " " +ex.getMessage());
385                        ex.printStackTrace();
386                        return false;
387        }
388                   
389        if ( abort )
390                return false;
391        input2.disconnect();
392        //FIXME Using thread.stop because throwing an exception to stop the sax parser in the input thread fails
393        input2.stop();
394        //throw new RuntimeException();
395
396                return true;
397        }
398       
399       
400        public void startSasl(ConnectionPacketReceiver cpr)
401        {
402                if( abort )
403                        return;
404               
405                //kill old input and send new stream
406                //input.disconnect();
407                jabberHandler = new JabberHandler(cpr,handlers);
408               
409                try
410                {
411                        input = new Input(socket.getInputStream(),this,jabberHandler);
412                }
413                catch (IOException e)
414                {
415                        e.printStackTrace();
416                }
417               
418                try
419                {
420                        output.writeHeader();
421                }
422                catch (IOException e)
423                {
424                        e.printStackTrace();
425                }
426               
427                throw new UnsupportedOperationException("end xmlparser");
428        }
429       
430        private Socket createHTTPTunel(String host) throws IOException
431        {
432                String tunnelHost = loginInfo.getProxyServer();
433            int tunnelPort = Integer.valueOf(loginInfo.getProxyPort()).intValue();
434            Socket tunnel = new Socket(tunnelHost, tunnelPort);
435            doTunnelHandshake(tunnel,host,loginInfo.getPort());
436            return tunnel;                   
437        }
438       
439        private void doTunnelHandshake(Socket tunnel, String host, int port)    throws IOException
440        {
441                OutputStream out = tunnel.getOutputStream();
442                String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n"
443                                + "User-Agent: "
444                                + sun.net.www.protocol.http.HttpURLConnection.userAgent;
445                               
446                if (loginInfo.getProxyUsername() != null && loginInfo.getProxyPassword() != null) {
447                          //add basic authentication header for the proxy
448                          sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
449                          String encodedPassword = enc.encode((loginInfo.getProxyUsername() + ":" + loginInfo.getProxyPassword()).getBytes());
450                           msg = msg + "\nProxy-Authorization: Basic " + encodedPassword;
451            }
452            msg = msg + "\nContent-Length: 0"
453                                +"\nPragma: no-cache"
454                                        +"\r\n\r\n";
455                byte b[];
456                try
457                {
458                        /*
459                         * We really do want ASCII7 -- the http protocol doesn't change
460                         * with locale.
461                         */
462                        b = msg.getBytes("ASCII7");
463                } catch (UnsupportedEncodingException ignored)
464                {
465                        /*
466                         * If ASCII7 isn't there, something serious is wrong, but
467                         * Paranoia Is Good (tm)
468                         */
469                        b = msg.getBytes();
470                }
471                out.write(b);
472                out.flush();
473
474                /*
475                 * We need to store the reply so we can create a detailed error
476                 * message to the user.
477                 */
478                byte reply[] = new byte[200];
479                int replyLen = 0;
480                int newlinesSeen = 0;
481                boolean headerDone = false; /* Done on first newline */
482                InputStream in = tunnel.getInputStream();
483
484                while ( newlinesSeen < 2 )
485                {
486                        int i = in.read();
487                        if (i < 0) { throw new IOException("Unexpected EOF from proxy"); }
488                        if (i == '\n')
489                        {
490                                headerDone = true;
491                                ++newlinesSeen;
492                        } else if (i != '\r')
493                        {
494                                newlinesSeen = 0;
495                                if (!headerDone && replyLen < reply.length)
496                                {
497                                        reply[replyLen++] = (byte) i;
498                                }
499                        }
500                }
501
502                /*
503                 * Converting the byte array to a string is slightly wasteful in the
504                 * case where the connection was successful, but it's insignificant
505                 * compared to the network overhead.
506                 */
507                String replyStr;
508                try
509                {
510                        replyStr = new String(reply, 0, replyLen, "ASCII7");
511                } catch (UnsupportedEncodingException ignored)
512                {
513                        replyStr = new String(reply, 0, replyLen);
514                }
515
516                /*
517                 * We check for Connection Established because our proxy returns
518                 * HTTP/1.1 instead of 1.0
519                 */
520                // if (!replyStr.startsWith("HTTP/1.0 200")) {
521                if (replyStr.toLowerCase().indexOf("200 connection established") == -1)
522                {
523                        String tunnelHost = System.getProperty("http.proxyHost");
524                        String tunnelPort = System.getProperty("http.proxyPort");
525                        throw new IOException("Unable to tunnel through " + tunnelHost
526                                        + ":" + tunnelPort + ".  Proxy returns \"" + replyStr
527                                        + "\"");
528                }
529                /* tunneling Handshake was successful! */
530        }
531
532        public void sendLoginError(String message)
533        {
534                for(Iterator j = backend.getListeners(LoginListener.class);j.hasNext();)
535                {
536                        ((LoginListener)j.next()).loginError(message);
537                }
538        }
539       
540        public void sendUnauthorized()
541        {
542                for(Iterator j = backend.getListeners(LoginListener.class);j.hasNext();)
543                {
544                        ((LoginListener)j.next()).unauthorized();
545                }
546        }
547
548        synchronized public void connected(String connectionID,String xmppVersion)
549        {
550                if(!abort)
551                {
552                        if(xmppVersion!=null && PluginsInfo.isPluginLoaded("xmpp"))
553                        {
554                                ConnectionPacketReceiver cpr = xmpp.getConnectionPacketReceiver(loginInfo,this);
555                                jabberHandler.changePacketReceiver(cpr);
556                                cpr.connected(connectionID, xmppVersion);
557                        }
558                        else
559                        {
560                                jabberHandler.changePacketReceiver(this);
561                                socket = null; //clear socket reference
562                                this.connectionID = connectionID;
563                                // TODO remove lowercase if filetransfer bug fixed
564                                output.send(new InfoQuery(null,"get",new IQAuth(loginInfo.getUsername().toLowerCase(),null,null)));
565                        }
566                }
567               
568        }
569
570        public void authenticate(IQAuth iqAuth)
571        {
572                if(!abort)
573                {
574                        authenticationId = "Jeti_Auth_" + new java.util.Date().getTime();
575                       
576                        if(iqAuth.hasDigest())
577                        {
578                                MessageDigest sha = null;
579                                try {
580                                  sha = MessageDigest.getInstance("SHA");
581                                } catch (Exception ex){
582                                  Log.error(I18N.gettext("main.loginstatus.Could_not_login_with_SHA"));
583                                  // TODO remove lowercase if filetransfer bug fixed
584                                  output.send(new InfoQuery(null,"set",authenticationId,new IQAuth(loginInfo.getUsername().toLowerCase(),loginInfo.getPassword() ,loginInfo.getResource())));
585                                  return;
586                                }
587
588                                sha.update(connectionID.getBytes());
589                                String digest = Utils.toString(sha.digest(loginInfo.getPassword().getBytes()));
590                                IQAuthBuilder iqab =  new IQAuthBuilder();
591                                iqab.digest = digest;
592                                // TODO remove lowercase if filetransfer bug fixed
593                                iqab.username = loginInfo.getUsername().toLowerCase();
594                                iqab.resource = loginInfo.getResource();
595                                output.send(new InfoQuery(null,"set",authenticationId,(IQExtension)iqab.build()));
596                        }
597                        else
598                        {
599                                if(!loginInfo.isSSl())
600                                {
601                                        int option = JOptionPane.showConfirmDialog(null,
602                                                        I18N.gettext("main.loginstatus.Sending_password_as_plain_text_over_an_unencrypted_connection,_continue?"),"Plain text",JOptionPane.YES_NO_OPTION);
603                                        if (option == JOptionPane.NO_OPTION)
604                                        {
605                                                sendLoginError("Sending password in plain not allowed");
606                                                return;
607                                        }
608                                }
609//                              TODO remove lowercase if filetransfer bug fixed
610                                output.send(new InfoQuery(null,"set",authenticationId,new IQAuth(loginInfo.getUsername().toLowerCase(),loginInfo.getPassword() ,loginInfo.getResource())));
611                        }
612                }
613        }
614
615        public void authenticated(InfoQuery infoQuery)
616        {
617                if(!abort)
618                {
619                        if(infoQuery.getType().equals("error"))
620                        {
621                                if(infoQuery.getErrorCode() == 401)
622                                {
623                                        sendUnauthorized();             
624                                }
625                                else
626                                {
627                                        sendLoginError(I18N.gettext("main.loginstatus.Not_logged_in_because") + " " + infoQuery.getErrorDescription());
628                                }       
629                                return;
630                        }
631//                      TODO remove lowercase if filetransfer bug fixed
632                        JID jid = new JID(loginInfo.getUsername().toLowerCase(),loginInfo.getServer() ,loginInfo.getResource());
633                        authenticated(jid);
634                }
635        }
636
637        public void authenticated(JID jid)
638        {
639                myJID = jid;
640                iqTimerQueue.clear();//remove iqs from previous connections
641                jabberHandler.changePacketReceiver(new Jabber(backend,capabilities,discovery,iqTimerQueue));
642                authenticated = true;
643        reconnecting = false;
644                output.setAuthenticated();
645                //output.send(new InfoQuery(new JID(server),"get",new IQBrowse()));
646                //browse(new JID(loginInfo.getServer()),null);
647                //TODO increase timeout
648                getItems(new JID(loginInfo.getServer()), new DiscoveryListener()
649                {
650                        public void discoveryItemResult(JID jid, DiscoveryItem item)
651                        {//cache disco items for this server
652                                if (item.hasItems())
653                                {
654                                        for(Iterator i = item.getItems();i.hasNext();)
655                                        {
656                                                DiscoveryItem di = (DiscoveryItem)i.next();
657                                                backend.getInfo(di.getJID(),null);
658                                        }
659                                }
660                        }
661                        public void discoveryInfoResult(JID jid, DiscoveryInfo info) {}
662                });
663                output.send(new InfoQuery("get",new IQPrivate(new JetiPrivateExtension())));
664                output.send(new InfoQuery("get",new IQXRoster()));
665                if(show == Presence.NONE)
666                {
667                        show = Presence.AVAILABLE;
668                        //status = Presence.toLongShow(show);
669                }
670                latestConnected =System.currentTimeMillis();
671                //moved to backend rosterloaded
672                //                      for(Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class);j.hasNext();)
673                //                      {//online
674                //                              ((nu.fw.jeti.events.StatusChangeListener)j.next()).connectionChanged(true);
675                //                      }
676                //changeStatus(show,status);
677        }
678       
679       
680        public void connected()
681        {
682                sendStatus();
683                send(new InfoQuery("get",new IQPrivate(new JetiPrivateRosterExtension())));
684                for( Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class) ; j.hasNext(); )
685                {
686                        //online
687                        ((nu.fw.jeti.events.StatusChangeListener)j.next()).connectionChanged(true);
688                }
689        }
690
691        public void receivePackets(Packet packet)
692        {
693                if (packet instanceof StreamError) streamError((StreamError)packet);
694                else if(authenticationId.equals(packet.getID())) authenticated((InfoQuery)packet);
695                else if(packet instanceof InfoQuery)
696                {
697                    IQExtension extension = packet.getIQExtension();
698                        if(extension instanceof IQAuth)
699                        {
700                                if(((InfoQuery)packet).getType().equals("error"))
701                                {
702                                        sendLoginError(packet.getErrorDescription());
703                                }
704                                else authenticate((IQAuth) extension);
705                        }
706                }
707        }
708
709        public void inputDeath()
710        {
711                //if(true)return; something todo with xmpp plugin, should not be here????? or server deads will not be detected
712                try
713                {
714                        if( socket != null ) socket.close();
715                }
716                catch (IOException e)
717                {
718                        e.printStackTrace();
719                }
720               
721                if((authenticated || reconnecting))
722                {
723                        authenticated = false;
724            if (reconnecting) {
725                try {
726                    Thread.sleep(10000);
727                } catch (InterruptedException e) {};
728            }
729            reconnecting = true;
730                        output.disconnect(true);
731                        for(Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class);j.hasNext();)
732                        {
733                                //offline
734                                ((nu.fw.jeti.events.StatusChangeListener)j.next()).connectionChanged(false);
735                        }
736                }
737                sendLoginError(I18N.gettext("main.loginstatus.Lost_Input"));
738                //else
739                //io error while logging in
740                //do something usefull
741        }
742
743        public void streamError(StreamError error)
744        {
745                //only when logging in
746                if(authenticated)
747                {
748                        authenticated = false;
749                        output.disconnect(true);
750                        for(Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class);j.hasNext();)
751                        {
752                                //offline
753                                ((nu.fw.jeti.events.StatusChangeListener)j.next()).connectionChanged(false);
754                        }
755                }
756                sendLoginError(error.getErrorDescription());
757        }
758
759        public void outputDeath()
760        {
761                authenticated = false;
762                for(Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class);j.hasNext();)
763                {
764                        //offline
765                        ((nu.fw.jeti.events.StatusChangeListener)j.next()).connectionChanged(false);
766                }
767        }
768
769        public static JID getMyJID()
770        {
771            return myJID;
772        }
773
774        public boolean getOnline()
775        {
776            return authenticated;
777        }
778
779        public void disconnect()
780        {
781                if( authenticated )
782                {
783                        send(new Presence(myJID, "unavailable"));
784                        authenticated = false;
785                        output.disconnect(true);
786                }
787                output = null;
788                for(Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class);j.hasNext();)
789                {
790                        //offline
791                        ((nu.fw.jeti.events.StatusChangeListener)j.next()).connectionChanged(false);
792                }
793        }
794
795        public void exit()
796        {
797                if(authenticated)
798                {
799                        send(new nu.fw.jeti.jabber.elements.Presence(myJID,"unavailable"));
800                        authenticated = false;
801                        output.disconnect(true);
802                }
803                output = null;
804                for(Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class);j.hasNext();)
805                {//exit
806                        ((nu.fw.jeti.events.StatusChangeListener)j.next()).exit();
807                }
808        }
809
810        public void send(Packet packet)
811        {
812                if(authenticated) output.send(packet);
813                else nu.fw.jeti.util.Log.notSend(packet.toString());
814        }
815       
816        public void sendWhileConnecting(Packet packet)
817        {
818                output.send(packet);
819        }
820
821        public String getAccountInfo()
822        {
823                return MessageFormat.format(I18N.gettext("main.popup.logged_in_as_{0}_on_server_{1}_with_resource_{2}"),new Object[]{loginInfo.getUsername(),loginInfo.getServer(),loginInfo.getResource()});
824        }
825
826        public void sendStatus()
827        {
828                if( authenticated )
829                {
830                        PresenceBuilder pb = new PresenceBuilder();
831                        pb.show = show;
832                        pb.status = status;
833                        pb.priority = loginInfo.getPriority();
834                        pb.addExtension(capabilities.getCaps());
835
836                        if(show!=Presence.UNAVAILABLE && openPGP!=null)
837                        {
838                                pb.addExtension(openPGP.signPresence(status));
839                        }
840                        try
841                        {
842                                send(pb.build());
843                        } catch (InstantiationException e)
844                        {
845                                e.printStackTrace();
846                        }
847                        for(Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class);j.hasNext();)
848                        {
849                                ((nu.fw.jeti.events.StatusChangeListener)j.next()).ownPresenceChanged(show,status);
850                        }
851                }
852        }
853       
854        public void changeStatus(int show,String status)
855        {
856                this.show = show;
857                this.status = status;
858                sendStatus();
859        }
860
861        public static class DummySSLSocketFactory extends SSLSocketFactory
862        {
863                private SSLSocketFactory factory;
864               
865                public DummySSLSocketFactory() {
866                        try {
867                                SSLContext sslcontent = SSLContext.getInstance("TLS");
868                                sslcontent.init(null, // KeyManager not required
869                                                                new TrustManager[] {new DummyTrustManager()},
870                                                                new java.security.SecureRandom());
871                                factory = sslcontent.getSocketFactory();
872                        }
873                        catch (NoSuchAlgorithmException e) {
874                                e.printStackTrace();
875                        }
876                        catch (KeyManagementException e) {
877                                e.printStackTrace();
878                        }
879                }
880       
881
882                public Socket createSocket(Socket socket, String s, int i,boolean flag) throws IOException
883                {
884                       
885                        return factory.createSocket(socket, s, i, flag);
886                }
887
888                public Socket createSocket(InetAddress inaddr, int i,InetAddress inaddr2, int j) throws IOException
889                {
890                        return factory.createSocket(inaddr, i, inaddr2, j);
891                }
892
893                public Socket createSocket(InetAddress inaddr, int i) throws IOException
894                {
895                        return factory.createSocket(inaddr, i);
896                }
897
898                public Socket createSocket(String s, int i, InetAddress inaddr, int j)  throws IOException
899                {
900                        return factory.createSocket(s, i, inaddr, j);
901                }
902
903                public Socket createSocket(String s, int i)     throws IOException
904                {
905                /*
906                * register a callback for handshaking completion event
907                */
908                       
909                        Socket so = factory.createSocket(s, i);
910                 ((SSLSocket)so).addHandshakeCompletedListener(
911                    new HandshakeCompletedListener() {
912                       public void handshakeCompleted(
913                          HandshakeCompletedEvent event) {
914                          System.out.println("Handshake finished!");
915                          System.out.println(
916                          "\t CipherSuite:" + event.getCipherSuite());
917                          System.out.println(
918                          "\t SessionId " + event.getSession());
919                          System.out.println(
920                          "\t PeerHost " + event.getSession().getPeerHost());
921                       }
922                    }
923                 );
924                return so;
925                }
926               
927                public String[] getDefaultCipherSuites() {
928                        return factory.getSupportedCipherSuites();
929                }
930
931                public String[] getSupportedCipherSuites() {
932                        return factory.getSupportedCipherSuites();
933                }
934        }
935
936        /**
937         * Trust manager which accepts certificates without any validation
938         * except date validation.
939         */
940        private static class DummyTrustManager implements X509TrustManager {
941
942                public void checkClientTrusted(X509Certificate[] chain, String authType) {      }
943
944                public void checkServerTrusted(X509Certificate[] chain, String authType)  {
945                        try {
946                                chain[0].checkValidity();
947                        }
948                        catch (CertificateExpiredException e) {
949                        }
950                        catch (CertificateNotYetValidException e) {
951                        }
952                }
953
954                public X509Certificate[] getAcceptedIssuers() {
955                        return new X509Certificate[0];
956                }
957        }
958 }
959
960
961/*
962 * Overrides for emacs
963 * Local variables:
964 * tab-width: 4
965 * End:
966 */
Note: See TracBrowser for help on using the repository browser.