summaryrefslogtreecommitdiff
path: root/cpp/src/IceGrid/Client.cpp
blob: 06326032ea24b821a8c53a7f5cd67270aa523eef (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
// **********************************************************************
//
// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <IceUtil/DisableWarnings.h>
#include <IceUtil/Options.h>
#include <IceUtil/CtrlCHandler.h>
#include <IceUtil/Thread.h>
#include <IceUtil/StringUtil.h>
#include <Ice/ConsoleUtil.h>
#include <Ice/UUID.h>
#include <IceUtil/Mutex.h>
#include <IceUtil/MutexPtrLock.h>
#include <Ice/Ice.h>
#include <Ice/SliceChecksums.h>
#include <IceGrid/Parser.h>
#include <IceGrid/FileParserI.h>
#include <IceGrid/Registry.h>
#include <IceGrid/IceLocatorDiscovery.h>
#include <Glacier2/Router.h>
#include <fstream>

//
// For getPassword()
//
#ifndef _WIN32
#   include <termios.h>
#else
#   include <conio.h>
#   include <fcntl.h>
#   include <io.h>
#endif

using namespace std;
using namespace Ice;
using namespace IceInternal;
using namespace IceLocatorDiscovery;
using namespace IceGrid;

class Client;

namespace
{

IceUtil::Mutex* _staticMutex = 0;
Client* _globalClient = 0;

class Init
{
public:

    Init()
    {
        _staticMutex = new IceUtil::Mutex;
    }

    ~Init()
    {
        delete _staticMutex;
        _staticMutex = 0;
    }
};

Init init;

class LookupReplyI : public LookupReply, private IceUtil::Monitor<IceUtil::Mutex>
{
public:

    virtual void
    foundLocator(const Ice::LocatorPrx& locator, const Ice::Current&)
    {
        Lock sync(*this);
        for(vector<Ice::LocatorPrx>::iterator p = _locators.begin(); p != _locators.end(); ++p)
        {
            if((*p)->ice_getIdentity() == locator->ice_getIdentity())
            {
                Ice::EndpointSeq newEndpoints = (*p)->ice_getEndpoints();
                Ice::EndpointSeq endpts = locator->ice_getEndpoints();
                for(Ice::EndpointSeq::const_iterator r = endpts.begin(); r != endpts.end(); ++r)
                {
                    //
                    // Only add unknown endpoints
                    //
                    bool found = false;
                    for(Ice::EndpointSeq::const_iterator q = newEndpoints.begin(); q != newEndpoints.end(); ++q)
                    {
                        if(*r == *q)
                        {
                            found = true;
                            break;
                        }
                    }
                    if(!found)
                    {
                        newEndpoints.push_back(*r);
                    }
                }
                *p = (*p)->ice_endpoints(newEndpoints);
                return;
            }
        }
        _locators.push_back(locator);
        notify();
    }

    vector<Ice::LocatorPrx>
    getLocators()
    {
        Lock sync(*this);
        return _locators;
    }

    bool
    waitForLocator()
    {
        Lock sync(*this);
        while(_locators.empty())
        {
            if(!timedWait(IceUtil::Time::milliSeconds(300)))
            {
                return false;
            }
        }
        return true;
    }

private:

    vector<Ice::LocatorPrx> _locators;
};
typedef IceUtil::Handle<LookupReplyI> LookupReplyIPtr;

}

class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor<IceUtil::Mutex>
{
public:

    SessionKeepAliveThread(const AdminSessionPrx& session, long timeout) :
        IceUtil::Thread("IceGrid admin session keepalive thread"),
        _session(session),
        _timeout(IceUtil::Time::seconds(timeout)),
        _destroy(false)
    {
    }

    virtual void
    run()
    {
        Lock sync(*this);
        while(!_destroy)
        {
            timedWait(_timeout);
            if(_destroy)
            {
                break;
            }
            try
            {
                _session->keepAlive();
            }
            catch(const Exception&)
            {
                break;
            }
        }
    }

    void
    destroy()
    {
        Lock sync(*this);
        _destroy = true;
        notify();
    }

private:

    AdminSessionPrx _session;
    const IceUtil::Time _timeout;
    bool _destroy;
};
typedef IceUtil::Handle<SessionKeepAliveThread> SessionKeepAliveThreadPtr;

class ReuseConnectionRouter : public Router
{
public:

    ReuseConnectionRouter(const ObjectPrx& proxy) : _clientProxy(proxy)
    {
    }

    virtual ObjectPrx
    getClientProxy(const Current&) const
    {
        return _clientProxy;
    }

    virtual ObjectPrx
    getServerProxy(const Current&) const
    {
        return 0;
    }

    virtual void
    addProxy(const ObjectPrx&, const Current&)
    {
    }

    virtual ObjectProxySeq
    addProxies(const ObjectProxySeq&, const Current&)
    {
        return ObjectProxySeq();
    }

private:

    const ObjectPrx _clientProxy;
};

class Client : public IceUtil::Monitor<IceUtil::Mutex>
{
public:

    void usage();
    int main(StringSeq& args);
    int run(StringSeq& args);
    void interrupted();

    CommunicatorPtr communicator() const { return _communicator; }
    const string& appName() const { return _appName; }

    string getPassword(const string&);

private:

    IceUtil::CtrlCHandler _ctrlCHandler;
    CommunicatorPtr _communicator;
    string _appName;
    ParserPtr _parser;
};

static void
interruptCallback(int /*signal*/)
{
    IceUtilInternal::MutexPtrLock<IceUtil::Mutex> lock(_staticMutex);
    if(_globalClient)
    {
        _globalClient->interrupted();
    }
}

#ifdef _WIN32

int
wmain(int argc, wchar_t* argv[])
{
    //
    // Enable binary input mode for stdin to avoid automatic conversions.
    //
    _setmode(_fileno(stdin), _O_BINARY);
#else

int
main(int argc, char* argv[])
{
#endif
    Client app;
    StringSeq args = argsToStringSeq(argc, argv);
    return app.main(args);
}

void
Client::usage()
{
    consoleErr << "Usage: " << appName() << " [options]\n";
    consoleErr <<
        "Options:\n"
        "-h, --help           Show this message.\n"
        "-v, --version        Display the Ice version.\n"
        "-e COMMANDS          Execute COMMANDS.\n"
        "-d, --debug          Print debug messages.\n"
        "-s, --server         Start icegridadmin as a server (to parse XML files).\n"
        "-i, --instanceName   Connect to the registry with the given instance name.\n"
        "-H, --host           Connect to the registry at the given host.\n"
        "-P, --port           Connect to the registry running on the given port.\n"
        "-u, --username       Login with the given username.\n"
        "-p, --password       Login with the given password.\n"
        "-S, --ssl            Authenticate through SSL.\n"
        "-r, --replica NAME   Connect to the replica NAME.\n"
        ;
}


int
Client::main(StringSeq& args)
{
    int status = EXIT_SUCCESS;

    try
    {
        _appName = args[0];
        InitializationData id;
        id.properties = createProperties(args);
        id.properties->setProperty("Ice.Warn.Endpoints", "0");
        _communicator = initialize(id);

        {
            IceUtilInternal::MutexPtrLock<IceUtil::Mutex> sync(_staticMutex);
            _globalClient = this;
        }
        _ctrlCHandler.setCallback(interruptCallback);

        try
        {
            status = run(args);
        }
        catch(const CommunicatorDestroyedException&)
        {
            // Expected if the client is interrupted during the initialization.
        }
    }
    catch(const IceUtil::Exception& ex)
    {
        consoleErr << _appName << ": " << ex << endl;
        status = EXIT_FAILURE;
    }
    catch(const std::exception& ex)
    {
        consoleErr << _appName << ": std::exception: " << ex.what() << endl;
        status = EXIT_FAILURE;
    }
    catch(const std::string& msg)
    {
        consoleErr << _appName << ": " << msg << endl;
        status = EXIT_FAILURE;
    }
    catch(const char* msg)
    {
        consoleErr << _appName << ": " << msg << endl;
        status = EXIT_FAILURE;
    }
    catch(...)
    {
        consoleErr << _appName << ": unknown exception" << endl;
        status = EXIT_FAILURE;
    }

    if(_communicator)
    {
        try
        {
            _communicator->destroy();
        }
        catch(const CommunicatorDestroyedException&)
        {
        }
        catch(const Exception& ex)
        {
            consoleErr << ex << endl;
            status = EXIT_FAILURE;
        }
    }

    _ctrlCHandler.setCallback(0);
    {
        IceUtilInternal::MutexPtrLock<IceUtil::Mutex> sync(_staticMutex);
        _globalClient = 0;
    }

    return status;

}

void
Client::interrupted()
{
    Lock sync(*this);
    if(_parser) // If there's an interactive parser, notify the parser.
    {
        _parser->interrupt();
    }
    else
    {
        //
        // Otherwise, destroy the communicator.
        //
        assert(_communicator);
        try
        {
            _communicator->destroy();
        }
        catch(const Exception&)
        {
        }
    }
}

int
Client::run(StringSeq& originalArgs)
{
    string commands;
    bool debug;

    IceUtilInternal::Options opts;
    opts.addOpt("h", "help");
    opts.addOpt("v", "version");
    opts.addOpt("e", "", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::Repeat);
    opts.addOpt("i", "instanceName", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("H", "host", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("P", "port", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("u", "username", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("p", "password", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("S", "ssl");
    opts.addOpt("d", "debug");
    opts.addOpt("s", "server");
    opts.addOpt("r", "replica", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);

    vector<string> args;
    try
    {
        args = opts.parse(originalArgs);
    }
    catch(const IceUtilInternal::BadOptException& e)
    {
        consoleErr << e.reason << endl;
        usage();
        return EXIT_FAILURE;
    }
    if(!args.empty())
    {
        consoleErr << _appName << ": too many arguments" << endl;
        usage();
        return EXIT_FAILURE;
    }

    if(opts.isSet("help"))
    {
        usage();
        return EXIT_SUCCESS;
    }
    if(opts.isSet("version"))
    {
        consoleOut << ICE_STRING_VERSION << endl;
        return EXIT_SUCCESS;
    }

    if(opts.isSet("server"))
    {
        ObjectAdapterPtr adapter =
            communicator()->createObjectAdapterWithEndpoints("FileParser", "tcp -h localhost");
        adapter->activate();
        ObjectPrx proxy = adapter->add(new FileParserI, stringToIdentity("FileParser"));
        consoleOut << proxy << endl;

        communicator()->waitForShutdown();
        return EXIT_SUCCESS;
    }

    if(opts.isSet("e"))
    {
        vector<string> optargs = opts.argVec("e");
        for(vector<string>::const_iterator i = optargs.begin(); i != optargs.end(); ++i)
        {
            commands += *i + ";";
        }
    }
    debug = opts.isSet("debug");

    bool ssl = communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.AuthenticateUsingSSL");
    if(opts.isSet("ssl"))
    {
        ssl = true;
    }

    string id = communicator()->getProperties()->getProperty("IceGridAdmin.Username");
    if(!opts.optArg("username").empty())
    {
        id = opts.optArg("username");
    }
    string password = communicator()->getProperties()->getProperty("IceGridAdmin.Password");
    if(!opts.optArg("password").empty())
    {
        password = opts.optArg("password");
    }

    string host = communicator()->getProperties()->getProperty("IceGridAdmin.Host");
    if(!opts.optArg("host").empty())
    {
        host = opts.optArg("host");
    }

    string instanceName = communicator()->getProperties()->getProperty("IceGridAdmin.InstanceName");
    if(!opts.optArg("instanceName").empty())
    {
        instanceName = opts.optArg("instanceName");
    }

    int port = communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.Port");
    if(!opts.optArg("port").empty())
    {
        istringstream is(opts.optArg("port"));
        if(!(is >> port))
        {
            consoleErr << _appName << ": given port number is not a numeric value" << endl;
            return EXIT_FAILURE;
        }
    }

    PropertiesPtr properties = communicator()->getProperties();
    string replica = properties->getProperty("IceGridAdmin.Replica");
    if(!opts.optArg("replica").empty())
    {
        replica = opts.optArg("replica");
    }

    Glacier2::RouterPrx router;
    AdminSessionPrx session;
    SessionKeepAliveThreadPtr keepAlive;
    int status = EXIT_SUCCESS;
    try
    {
        int sessionTimeout;
        int acmTimeout = 0;
        if(!communicator()->getDefaultLocator() && !communicator()->getDefaultRouter())
        {
            if(!host.empty())
            {
                const int timeout = 3000; // 3s connection timeout.
                ostringstream os;
                os << "Ice/LocatorFinder" << (ssl ? " -s" : "");
                os << ":tcp -h \"" << host << "\" -p " << (port == 0 ? 4061 : port) << " -t " << timeout;
                os << ":ssl -h \"" << host << "\" -p " << (port == 0 ? 4062 : port) << " -t " << timeout;
                LocatorFinderPrx finder = LocatorFinderPrx::uncheckedCast(communicator()->stringToProxy(os.str()));
                try
                {
                    communicator()->setDefaultLocator(finder->getLocator());
                }
                catch(const Ice::LocalException&)
                {
                    // Ignore.
                }
                if(!instanceName.empty() &&
                   communicator()->getDefaultLocator()->ice_getIdentity().category != instanceName)
                {
                    consoleErr << _appName << ": registry running on `" << host << "' uses a different instance name:\n";
                    consoleErr << communicator()->getDefaultLocator()->ice_getIdentity().category << endl;
                    return EXIT_FAILURE;
                }
            }
            else
            {
                bool ipv4 = properties->getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
                string address;
                bool preferIPv6 = properties->getPropertyAsInt("Ice.PreferIPv6Address") > 0;
                if(ipv4 && !preferIPv6)
                {
                    address = properties->getPropertyWithDefault("IceGridAdmin.Discovery.Address", "239.255.0.1");
                }
                else
                {
                    address = properties->getPropertyWithDefault("IceGridAdmin.Discovery.Address", "ff15::1");
                }

                string interface = properties->getProperty("IceGridAdmin.Discovery.Interface");

                string lookupEndpoints = properties->getProperty("IceGridAdmin.Discovery.Lookup");
                if(lookupEndpoints.empty())
                {
                    ostringstream os;
                    os << "udp -h \"" << address << "\" -p " << (port == 0 ? 4061 : port);
                    if(!interface.empty())
                    {
                        os << " --interface \"" << interface << "\"";
                    }
                    lookupEndpoints = os.str();
                }

                ObjectPrx prx = communicator()->stringToProxy("IceLocatorDiscovery/Lookup -d:" + lookupEndpoints);
                LookupPrx lookupPrx = LookupPrx::uncheckedCast(prx->ice_collocationOptimized(false));

                if(properties->getProperty("IceGridAdmin.Discovery.Reply.Endpoints").empty())
                {
                    ostringstream os;
                    os << "udp";
                    if(!interface.empty())
                    {
                        os << " -h \"" << interface << "\"";
                    }
                    properties->setProperty("IceGridAdmin.Discovery.Reply.Endpoints", os.str());
                }

                Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("IceGridAdmin.Discovery.Reply");
                adapter->activate();
                LookupReplyIPtr reply = new LookupReplyI();
                LookupReplyPrx replyPrx = LookupReplyPrx::uncheckedCast(adapter->addWithUUID(reply)->ice_datagram());
                int retryCount = 3; // Send several findLocator queries.
                try
                {
                    while(--retryCount >= 0)
                    {
                        lookupPrx->findLocator(instanceName, replyPrx);
                        if(instanceName.empty())
                        {
                            IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(300));
                        }
                        else if(reply->waitForLocator())
                        {
                            break;
                        }
                    }
                }
                catch(const Ice::LocalException& ex)
                {
                    consoleErr << _appName << ": registry discovery failed:\n" << ex << endl;
                    return EXIT_FAILURE;
                }
                adapter->destroy();

                vector<Ice::LocatorPrx> locators = reply->getLocators();
                if(locators.size() > 1)
                {
                    consoleOut << "found " << locators.size() << " Ice locators:" << endl;
                    unsigned int num = 0;
                    for(vector<Ice::LocatorPrx>::const_iterator p = locators.begin(); p != locators.end(); ++p)
                    {
                        consoleOut << ++num << ": proxy = `" << *p << "'" << endl;
                    }

                    num = 0;
                    while(num == 0 && cin.good())
                    {
                        consoleOut << "please enter the locator number to use: " << flush;
                        string line;
                        getline(cin, line);
                        if(!cin.good() || line.empty())
                        {
                            return EXIT_FAILURE;
                        }
                        line = IceUtilInternal::trim(line);

                        istringstream is(line);
                        is >> num;
                        if(num > locators.size())
                        {
                            num = 0;
                        }
                    }

                    assert(num <= locators.size());
                    communicator()->setDefaultLocator(locators[num - 1]);
                }
                else if(locators.size() == 1)
                {
                    consoleOut << "using discovered locator:\nproxy = `" << locators[0] << "'" << endl;
                    communicator()->setDefaultLocator(locators[0]);
                }
            }
        }

        if(communicator()->getDefaultRouter())
        {
            try
            {
                // Use SSL if available.
                router = Glacier2::RouterPrx::checkedCast(communicator()->getDefaultRouter()->ice_preferSecure(true));
                if(!router)
                {
                    consoleErr << _appName << ": configured router is not a Glacier2 router" << endl;
                    return EXIT_FAILURE;
                }
            }
            catch(const LocalException& ex)
            {
                consoleErr << _appName << ": could not contact the default router:" << endl << ex << endl;
                return EXIT_FAILURE;
            }

            if(ssl)
            {
                session = AdminSessionPrx::uncheckedCast(router->createSessionFromSecureConnection());
                if(!session)
                {
                    consoleErr << _appName
                         << ": Glacier2 returned a null session, please set the Glacier2.SSLSessionManager property"
                         << endl;
                    return EXIT_FAILURE;
                }
            }
            else
            {
                while(id.empty() && cin.good())
                {
                    consoleOut << "user id: " << flush;
                    getline(cin, id);
                    if(!cin.good())
                    {
                        return EXIT_FAILURE;
                    }
                    id = IceUtilInternal::trim(id);
                }

                if(password.empty())
                {
                    password = getPassword("password: ");
#ifndef _WIN32
                    if(!cin.good())
                    {
                        return EXIT_FAILURE;
                    }
#endif
                }

                session = AdminSessionPrx::uncheckedCast(router->createSession(id, password));
                fill(password.begin(), password.end(), '\0'); // Zero the password string.

                if(!session)
                {
                    consoleErr << _appName
                         << ": Glacier2 returned a null session, please set the Glacier2.SessionManager property"
                         << endl;
                    return EXIT_FAILURE;
                }
            }
            sessionTimeout = static_cast<int>(router->getSessionTimeout());
            try
            {
                acmTimeout = router->getACMTimeout();
            }
            catch(const Ice::OperationNotExistException&)
            {
            }
        }
        else if(communicator()->getDefaultLocator())
        {
            //
            // Create the identity of the registry to connect to.
            //
            Identity registryId;
            registryId.category = communicator()->getDefaultLocator()->ice_getIdentity().category;
            registryId.name = "Registry";
            if(!replica.empty() && replica != "Master")
            {
                registryId.name += "-" + replica;
            }

            //
            // First try to contact the locator. If we can't talk to the locator,
            // no need to go further. Otherwise, we get the proxy of local registry
            // proxy.
            //
            IceGrid::LocatorPrx locator;
            RegistryPrx localRegistry;
            try
            {
                locator = IceGrid::LocatorPrx::checkedCast(communicator()->getDefaultLocator());
                if(!locator)
                {
                    consoleErr << _appName << ": configured locator is not an IceGrid locator" << endl;
                    return EXIT_FAILURE;
                }
                localRegistry = locator->getLocalRegistry();
            }
            catch(const LocalException& ex)
            {
                consoleErr << _appName << ": could not contact the default locator:" << endl << ex << endl;
                return EXIT_FAILURE;
            }

            IceGrid::RegistryPrx registry;
            if(localRegistry->ice_getIdentity() == registryId)
            {
                registry = localRegistry;
            }
            else
            {
                //
                // The locator local registry isn't the registry we want to connect to.
                //

                try
                {
                    registry = RegistryPrx::checkedCast(locator->findObjectById(registryId));
                    if(!registry)
                    {
                        consoleErr << _appName << ": could not contact an IceGrid registry" << endl;
                    }
                }
                catch(const ObjectNotFoundException&)
                {
                    consoleErr << _appName << ": no active registry replica named `" << replica << "'" << endl;
                    return EXIT_FAILURE;
                }
                catch(const LocalException& ex)
                {
                    if(!replica.empty())
                    {
                        consoleErr << _appName << ": could not contact the registry replica named `" << replica << "':\n";
                        consoleErr << ex << endl;
                        return EXIT_FAILURE;
                    }
                    else
                    {
                        //
                        // If we can't contact the master, use the local registry.
                        //
                        registry = localRegistry;
                        string name = registry->ice_getIdentity().name;
                        const string prefix("Registry-");
                        string::size_type pos = name.find(prefix);
                        if(pos != string::npos)
                        {
                            name = name.substr(prefix.size());
                        }
                        consoleErr << _appName << ": warning: could not contact master, using slave `" << name << "'" << endl;
                    }
                }
            }

            //
            // If the registry to use is the locator local registry, we install a default router
            // to ensure we'll use a single connection regardless of the endpoints returned in the
            // proxies of the various session/admin methods (useful if used over an ssh tunnel).
            //
            if(registry->ice_getIdentity() == localRegistry->ice_getIdentity())
            {
                ObjectAdapterPtr colloc = communicator()->createObjectAdapter(""); // colloc-only adapter
                ObjectPrx router = colloc->addWithUUID(new ReuseConnectionRouter(locator));
                communicator()->setDefaultRouter(RouterPrx::uncheckedCast(router));
                registry = registry->ice_router(communicator()->getDefaultRouter());
            }

            // Prefer SSL.
            registry = registry->ice_preferSecure(true);

            if(ssl)
            {
                session = registry->createAdminSessionFromSecureConnection();
            }
            else
            {
                while(id.empty() && cin.good())
                {
                    consoleOut << "user id: " << flush;
                    getline(cin, id);
                    if(!cin.good())
                    {
                        return EXIT_FAILURE;
                    }
                    id = IceUtilInternal::trim(id);
                }

                if(password.empty())
                {
                    password = getPassword("password: ");
#ifndef _WIN32
                    if(!cin.good())
                    {
                        return EXIT_FAILURE;
                    }
#endif
                }

                session = registry->createAdminSession(id, password);
                fill(password.begin(), password.end(), '\0'); // Zero the password string.
            }

            sessionTimeout = registry->getSessionTimeout();
            try
            {
                acmTimeout = registry->getACMTimeout();
            }
            catch(const Ice::OperationNotExistException&)
            {
            }
        }
        else // No default locator or router set.
        {
            consoleErr << _appName << ": could not contact the registry:" << endl;
            consoleErr << "no default locator or router configured" << endl;
            return EXIT_FAILURE;
        }

        if(acmTimeout > 0)
        {
            session->ice_getConnection()->setACM(acmTimeout, IceUtil::None, Ice::HeartbeatAlways);
        }
        else if(sessionTimeout > 0)
        {
            keepAlive = new SessionKeepAliveThread(session, sessionTimeout / 2);
            keepAlive->start();
        }

        AdminPrx admin = session->getAdmin();

        SliceChecksumDict serverChecksums = admin->getSliceChecksums();
        SliceChecksumDict localChecksums = sliceChecksums();

        //
        // The following slice types are only used by the admin CLI.
        //
        localChecksums.erase("::IceGrid::FileParser");
        localChecksums.erase("::IceGrid::ParseException");

        for(SliceChecksumDict::const_iterator q = localChecksums.begin(); q != localChecksums.end(); ++q)
        {
            SliceChecksumDict::const_iterator r = serverChecksums.find(q->first);
            if(r == serverChecksums.end())
            {
                consoleErr << appName() << ": server is using unknown Slice type `" << q->first << "'" << endl;
            }
            else if(q->second != r->second)
            {
                consoleErr << appName() << ": server is using a different Slice definition of `" << q->first << "'" << endl;
            }
        }

        {
            Lock sync(*this);
            _parser = Parser::createParser(communicator(), session, admin, commands.empty());
        }

        if(!commands.empty()) // Commands were given
        {
            int parseStatus = _parser->parse(commands, debug);
            if(parseStatus == EXIT_FAILURE)
            {
                status = EXIT_FAILURE;
            }
        }
        else // No commands, let's use standard input
        {
            _parser->showBanner();

            int parseStatus = _parser->parse(stdin, debug);
            if(parseStatus == EXIT_FAILURE)
            {
                status = EXIT_FAILURE;
            }
        }
    }
    catch(const IceGrid::PermissionDeniedException& ex)
    {
        consoleOut << "permission denied:\n" << ex.reason << endl;
        return EXIT_FAILURE;
    }
    catch(const Glacier2::PermissionDeniedException& ex)
    {
        consoleOut << "permission denied:\n" << ex.reason << endl;
        return EXIT_FAILURE;
    }
    catch(const Glacier2::CannotCreateSessionException& ex)
    {
        consoleOut << "session creation failed:\n" << ex.reason << endl;
        return EXIT_FAILURE;
    }
    catch(...)
    {
        if(keepAlive)
        {
            keepAlive->destroy();
            keepAlive->getThreadControl().join();
        }

        try
        {
            if(router)
            {
                router->destroySession();
            }
            else if(session)
            {
                session->destroy();
            }
        }
        catch(const Exception&)
        {
        }
        throw;
    }

    if(keepAlive)
    {
        keepAlive->destroy();
        keepAlive->getThreadControl().join();
    }

    if(session)
    {
        try
        {
            if(router)
            {
                router->destroySession();
            }
            else
            {
                session->destroy();
            }
        }
        catch(const Exception&)
        {
            // Ignore. If the registry has been shutdown this will cause
            // an exception.
        }
    }

    return status;
}

string
Client::getPassword(const string& prompt)
{
    consoleOut << prompt << flush;
    string password;
#ifndef _WIN32
    struct termios oldConf;
    struct termios newConf;
    tcgetattr(0, &oldConf);
    newConf = oldConf;
    newConf.c_lflag &= (~ECHO);
    tcsetattr(0, TCSANOW, &newConf);
    getline(cin, password);
    tcsetattr(0, TCSANOW, &oldConf);
#else
    char c;
    while((c = _getch()) != '\r')
    {
        password += c;
    }
#endif
    consoleOut << endl;
    return IceUtilInternal::trim(password);
}