summaryrefslogtreecommitdiffstats
path: root/pki/base/console/src/com/netscape/admin/certsrv/connection/AdminConnection.java
blob: 7539c393c82ffe9d0f012761ff691f6c5094fc29 (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
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.admin.certsrv.connection;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.*;
import com.netscape.certsrv.common.*;
import com.netscape.admin.certsrv.*;
import com.netscape.management.client.util.*;
import com.netscape.management.client.*;
import com.netscape.management.client.preferences.*;

/**
 * This class represents an administration connection shell
 * to the certificate server. The user need to specify the
 * connection factory
 *
 * @author thomask
 * @author Jack Pan-Chen
 * @version $Revision$, $Date$
 * @see com.netscape.certsrv.client.connection
 * @see com.netscape.certsrv.client
 */
public class AdminConnection {

    /*==========================================================
     * variables
     *==========================================================*/
    public static int NO_TIMEOUT = 0;
    public static int DEFAULT_TIMEOUT = 600000;      //600 sec
    
    private IConnectionFactory mFactory= null;
	private IConnection mConn = null;
	private IAuthenticator mAuth = null;
	private int mDefaultTimeout = DEFAULT_TIMEOUT;
	private int mCurrentTimeout = DEFAULT_TIMEOUT;
	private boolean mIsKeepAlive = false;
	private String mHost;
	private int mPort;
    private IConnectionListener mConnectionListener;
    private String mAuthType="";
    private String mPath=null;
    private static FilePreferenceManager mPM = null;

	/*==========================================================
     * constructors
     *==========================================================*/

    /**
     * Default Constructor<p>
     * Construct an administartion connection with keep alive disabled
     *
     * @param auth authentication mechanism object
     * @param factory factory used to create server connection
     * @param host server host name
     * @param port server port number
     *
     * @see com.netscape.certsrv.client.connection.IConnection
     * @see com.netscape.certsrv.client.connection.IConnectionFactory
     * @see com.netscape.certsrv.client.connection.IAuthenticator
     */
	public AdminConnection( IAuthenticator auth,
	                        IConnectionFactory factory,
	                        String host, int port, String path) {
               if (mPM == null) {
                 mPM = new FilePreferenceManager(Framework.IDENTIFIER, 
                       Framework.VERSION);
               }
               Preferences p = mPM.getPreferences(
                  Framework.PREFERENCES_GENERAL);
               int timeout = p.getInt("CMSConnTimeout", 600000);
               setDefaultTimeout(timeout);
               setCurrentTimeout(timeout);
               Debug.println("AdminConnection: " + timeout + " " + 
                   mPM.getClass().getName());

		mAuth = auth;
		mFactory = factory;
		mHost = host;
		mPort = port;
		mPath = path;
	}

    /**
     * Default Constructor<p>
     * Construct an administartion connection
     *
     * @param auth authentication mechanism object
     * @param factory factory used to create server connection
     * @param enableKeepAlive enable HTTP keep alive or not
     * @param host server host name
     * @param port server port number
     *
     * @see com.netscape.certsrv.client.connection.IConnection
     * @see com.netscape.certsrv.client.connection.IConnectionFactory
     * @see com.netscape.certsrv.client.connection.IAuthenticator
     */
	public AdminConnection( IAuthenticator auth,
	                        IConnectionFactory factory,
	                        boolean enableKeepAlive,
	                        String host, int port, String path) {
               if (mPM == null) {
                 mPM = new FilePreferenceManager(Framework.IDENTIFIER, 
                       Framework.VERSION);
               }
               Preferences p = mPM.getPreferences(
                  Framework.PREFERENCES_GENERAL);
               int timeout = p.getInt("CMSConnTimeout", 600000);
               setDefaultTimeout(timeout);
               setCurrentTimeout(timeout);
               Debug.println("AdminConnection: " + timeout + " " + 
                   mPM.getClass().getName());

		mAuth = auth;
		mFactory = factory;
		mIsKeepAlive = enableKeepAlive;
		mHost = host;
		mPort = port;
		mPath = path;
	}

    /*==========================================================
     * private methods
     *==========================================================*/

    private String b64encode (byte[] data) {
        int i, k, n;
        int len = data.length;
        byte b;
        StringBuffer b64 = new StringBuffer();
        String base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

        for (i = 0; i < len; i += 3) {
            byte d0 = data[i];
            byte d1 = (i+1<len)? data[i+1]: (byte)0;
            byte d2 = (i+2<len)? data[i+2]: (byte)0;
            b = (byte)((d0 & (byte)0xFC) >>> 2);
            b64.append(base64.charAt((int)b));
            b = (byte)(((d0 & 0x03) << 4) | ((d1 & 0xF0) >>> 4));
            b64.append(base64.charAt((int)b));
            b = (byte)(((d1 & 0x0F) << 2) | ((d2 & 0xC0) >>> 6));
            if (i+1 < len) {
                b64.append(base64.charAt((int)b));
            } else {
                b64.append('=');
            }
            b = (byte)(d2 & 0x3F);
            if (i+2 < len) {
                b64.append(base64.charAt((int)b));
            } else {
                b64.append('=');
            }
        }

        b64.append('\n');

        return b64.toString();
    } 

    /*==========================================================
	 * public methods
     *==========================================================*/

    /**
     * Set the listener. 
     */
    public void setConnectionListener(IConnectionListener l) {
        mConnectionListener = l;
    }

    /**
     * Returns the authentication object for this connection.<p>
     * The choice of authentication object is dependding on the
     * authentication method used on the server side.
     *
     * @return authentication object
     * @see com.netscape.certsrv.client.connection.IAuthenticator
     * @see com.netscape.certsrv.client.connection.BasicAuthenticator
     */
	public IAuthenticator getAuthenticator() {
		return mAuth;
	}

    /**
     * Returns the connection object used to establish the connection
     * This can be SSLavaConnection or SSLConnection. THIS OBJECT REFERENCE
     * IS NOT STABLE, SINCE IT IS RECREATED EACH TIME IF KEEPALIVE IS NOT
     * ENABLE.
     *
     * @return connection object
     */
    public IConnection getIConnection() {
        return mConn;
    }

    /**
     * Sets the one time current timeout value for specific operation
     * if less then default timeout the default timeout is used.
     *
     * @param timeout time in ms
     */
    public void setCurrentTimeout(int timeout) {
        mCurrentTimeout = timeout;    
    }


    /**
     * Sets the default timeout value
     * @param timeout time in ms
     */
    public void setDefaultTimeout(int timeout) {
        mDefaultTimeout = timeout;
    }

    /**
     * OPERATION: ADD<p>
     *
     * <pre>
     * FORMAT:
     *
     *      GET/[OP_DEST]?
     *          OP_TYPE=[OP_TYPE]&
     *          OP_SCOPE=[OP_SCOPE]&
     *          RS_ID=[RS_ID]&
     *          [NAME=VALUE][&[NAME=VALUE]]
     *
     * </pre>
     *
     * Add new entries into the scope using the NVP information provided.
     * This operation will ONLY be used by DYNAMIC content and
     * configuartion, such as Users and Groups, and Policies.
     *
     * @param dest OP_DEST
     * @param scope OP_SCOPE
     * @param id RS_ID
     * @param pairs NVP info
     *
     * @see http://warp/server/certificate/columbo/design/ui/admin-protocol-definition.html
     *
     */
    public void add(String dest, String scope, String id, NameValuePairs pairs)
        throws EAdminException {

		checkParams(dest,scope,id,pairs);
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_ADD);
        request.set(Constants.OP_SCOPE, scope);
        request.set(Constants.RS_ID, id);
        for (int i = 0; i < pairs.size(); i++) {
            NameValuePair p = (NameValuePair)pairs.elementAt(i);
            request.set(p.getName(), p.getValue());
        }
        Response response = sendRequest(request);
        if (response.getReturnCode() == Response.SUCCESS) {
            return;
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    /**
     * OPERATION: DELETE<p>
     *
     * <pre>
     * FORMAT:
     *
     *      GET/[OP_DEST]?
     *          OP_TYPE=[OP_TYPE]&
     *          OP_SCOPE=[OP_SCOPE]&
     *          RS_ID=[RS_ID]&
     *
     * </pre>
     *
     * Removing an entry with specified id from the scope specified.
     *
     * @param dest OP_DEST
     * @param scope OP_SCOPE
     * @param id RS_ID
     *
     * @see http://warp/server/certificate/columbo/design/ui/admin-protocol-definition.html
     *
     */
    public void delete(String dest, String scope, String id)
        throws EAdminException {

		checkParams(dest,scope,id);
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_DELETE);
        request.set(Constants.OP_SCOPE, scope);
        request.set(Constants.RS_ID, id);
        Response response = sendRequest(request);
        if (response.getReturnCode() == Response.SUCCESS) {
            return;
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    public void delete(String dest, String scope, String id, NameValuePairs pairs)
        throws EAdminException {

        checkParams(dest,scope,id,pairs);
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_DELETE);
        request.set(Constants.OP_SCOPE, scope);
        request.set(Constants.RS_ID, id);
        for (int i = 0; i < pairs.size(); i++) {
            NameValuePair p = (NameValuePair)pairs.elementAt(i);
            request.set(p.getName(), p.getValue());
        }
        Response response = sendRequest(request);
        if (response.getReturnCode() == Response.SUCCESS) {
            return;
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    /**
     * OPERATION: AUTH<p>
     *
     * <pre>
     * FORMAT:
     *
     *      GET/[OP_DEST]?
     *          OP_TYPE=[OP_TYPE]&
     *          OP_SCOPE=[OP_SCOPE]&
     *          [NAME=VALUE][&[NAME=VALUE]]
     *
     * </pre>
     *
     * getting  properties (name-value pairs) using some criteria
     * specified in NVP.
     *
     * @param dest OP_DEST
     * @param scope OP_SCOPE
     * @param pairs NVP search filter
     *
     * @see http://warp/server/certificate/columbo/design/ui/admin-protocol-definition.html
     *
     */
    public void auth(String dest, String scope) throws EAdminException {
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_AUTH);
        request.set(Constants.OP_SCOPE, scope);
        Response response = sendRequest(request);
        if (response.getReturnCode() == Response.SUCCESS) {
            return;
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    public String authType(String dest, String scope) throws EAdminException {
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_AUTH);
        request.set(Constants.OP_SCOPE, scope);

        Response response = sendRequest(request);
        if (response.getReturnCode() == Response.SUCCESS) {
            Enumeration e = response.getNames();
            while (e.hasMoreElements()) {
                String n = (String)e.nextElement();
                if (n.equals("authType"))
                    mAuthType = response.get(n);
                    return mAuthType;
            }
            return "";
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    /**
     * OPERATION: SEARCH<p>
     *
     * <pre>
     * FORMAT:
     *
     *      GET/[OP_DEST]?
     *          OP_TYPE=[OP_TYPE]&
     *          OP_SCOPE=[OP_SCOPE]&
     *          [NAME=VALUE][&[NAME=VALUE]]
     *
     * </pre>
     *
     * getting  properties (name-value pairs) using some criteria
     * specified in NVP.
     *
     * @param dest OP_DEST
     * @param scope OP_SCOPE
     * @param pairs NVP search filter
     *
     * @see http://warp/server/certificate/columbo/design/ui/admin-protocol-definition.html
     *
     */
    public NameValuePairs search(String dest, String scope, NameValuePairs filters)
        throws EAdminException {

		checkParams(dest,scope,"",filters);
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_SEARCH);
        request.set(Constants.OP_SCOPE, scope);
        for (int i = 0; i < filters.size(); i++) {
            NameValuePair p = (NameValuePair)filters.elementAt(i);
            request.set(p.getName(), p.getValue());
        }

        Response response = sendRequest(request);

        if (response.getReturnCode() == Response.SUCCESS) {
            NameValuePairs newpairs = new NameValuePairs();
            Enumeration e = response.getNames();
            while (e.hasMoreElements()) {
                String n = (String)e.nextElement();
		        newpairs.add(n, response.get(n));
            }
            return newpairs;
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    /**
     * OPERATION: READ<p>
     *
     * <pre>
     * FORMAT:
     *
     *      GET/[OP_DEST]?
     *          OP_TYPE=[OP_TYPE]&
     *          OP_SCOPE=[OP_SCOPE]&
     *          RS_ID=[RS_ID]&
     *          [NAME=VALUE][&[NAME=VALUE]]
     *
     * </pre>
     *
     * getting specific properties (name-value pairs) using
     * attributes specified in NVP.
     *
     * @param dest OP_DEST
     * @param scope OP_SCOPE
     * @param id RS_ID
     * @param pairs NVP info
     *
     * @see http://warp/server/certificate/columbo/design/ui/admin-protocol-definition.html
     *
     */
    public NameValuePairs read(String dest, String scope, String id, NameValuePairs pairs)
        throws EAdminException {

		checkParams(dest,scope,id);
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_READ);
        request.set(Constants.OP_SCOPE, scope);
        request.set(Constants.RS_ID, id);
        for (int i = 0; i < pairs.size(); i++) {
            NameValuePair p = (NameValuePair)pairs.elementAt(i);
            request.set(p.getName(), p.getValue());
        }

        Response response = sendRequest(request);

        if (response.getReturnCode() == Response.SUCCESS) {
            NameValuePairs newpairs = new NameValuePairs();
            Enumeration e = response.getNames();
            while (e.hasMoreElements()) {
                String n = (String)e.nextElement();
		        newpairs.add(n, response.get(n));
            }
            return newpairs;
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    public NameValuePairs process(String dest, String scope, String id,
      NameValuePairs pairs) throws EAdminException {
         return process(dest, scope, id, pairs, false);
    }

    public NameValuePairs process(String dest, String scope, String id,
      NameValuePairs pairs, boolean useGET) throws EAdminException {
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_PROCESS);
        request.set(Constants.OP_SCOPE, scope);
        request.set(Constants.RS_ID, id);

        for (int i = 0; i < pairs.size(); i++) {
            NameValuePair p = (NameValuePair)pairs.elementAt(i);
            request.set(p.getName(), p.getValue());
        }

        Response response = sendRequest(request, useGET);
        if (response.getReturnCode() == Response.SUCCESS) {
            NameValuePairs newpairs = new NameValuePairs();
            Enumeration e = response.getNames();
            while (e.hasMoreElements()) {
                String n = (String)e.nextElement();
                newpairs.add(n, response.get(n));
            }
            return newpairs;
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    public void validate(String dest, String scope, NameValuePairs pairs) 
        throws EAdminException {
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_VALIDATE);
        request.set(Constants.OP_SCOPE, scope);
        for (int i = 0; i < pairs.size(); i++) {
            NameValuePair p = (NameValuePair)pairs.elementAt(i);
            request.set(p.getName(), p.getValue());
        }

        Response response = sendRequest(request);
        if (response.getReturnCode() == Response.SUCCESS) {
            return;
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    /**
     * OPERATION: MODIFY<p>
     *
     * <pre>
     * FORMAT:
     *
     *      GET/[OP_DEST]?
     *          OP_TYPE=[OP_TYPE]&
     *          OP_SCOPE=[OP_SCOPE]&
     *          RS_ID=[RS_ID]&
     *          [NAME=VALUE][&[NAME=VALUE]]
     *
     * </pre>
     *
     * Modify an existing entry's attributes.
     *
     * @param dest OP_DEST
     * @param scope OP_SCOPE
     * @param id RS_ID
     * @param pairs NVP info
     *
     * @see http://warp/server/certificate/columbo/design/ui/admin-protocol-definition.html
     *
     */
    public void modify(String dest, String scope, String id, NameValuePairs pairs)
        throws EAdminException {
          modify(dest, scope, id, pairs, false);
    }

    public void modify(String dest, String scope, String id, NameValuePairs pairs, boolean useGET)
        throws EAdminException {

		checkParams(dest,scope,id,pairs);
        Request request = new Request(mPath + "/" + dest);
        request.set(Constants.OP_TYPE, OpDef.OP_MODIFY);
        request.set(Constants.OP_SCOPE, scope);
        request.set(Constants.RS_ID, id);
        for (int i = 0; i < pairs.size(); i++) {
            NameValuePair p = (NameValuePair)pairs.elementAt(i);
            request.set(p.getName(), p.getValue());
        }
        Response response = sendRequest(request, useGET);
        if (response.getReturnCode() == Response.SUCCESS) {
            return;
        } else if (response.getReturnCode() == Response.RESTART) {
            mConnectionListener.restartCallback();
            return;    
        }
        throw new EAdminException(response.getErrorMessage(), true);
    }

    private synchronized void retryConnection() throws EAdminException {
        if (mConn instanceof JSSConnection) {
            JSSConnection conn = (JSSConnection)mConn;
            if (!conn.isTokenPasswordInit()) {
                mConn = null;
                if (!conn.isSamePwd()) {
                    throw new EAdminException(CMSAdminResources.SERVERCONNECTION_DIFFERENT_PWD, false);
                }
                throw new EAdminException(CMSAdminResources.SERVERCONNECTION_TOKEN_INIT_FAILED, false);
            }

            if (!conn.isServerCertImported()) {
                mConn = null;
                throw new EAdminException(CMSAdminResources.SERVERCONNECTION_SERVER_CERT_IMPORTED_FAILED, false);
            }
            if (!conn.isCertAccepted()) {
                mConn = null;
                throw new EAdminException(CMSAdminResources.SERVERCONNECTION_SERVER_CERT_DENIED, false);
            }
            if (conn != null && conn.isAbortAction() && conn.isClientAuth()) {
                mConn = null;
                throw new EAdminException(CMSAdminResources.SERVERCONNECTION_NO_CLIENT_CERT, false);
            }
            if (conn != null && !conn.hasClientCert()) {
                mConn = null;
                throw new EAdminException(CMSAdminResources.SERVERCONNECTION_NO_CLIENT_CERT, false);
            }
        }
        try {
            mConn = mFactory.create(mHost, mPort);
        } catch (UnknownHostException e) {
            mConn = null;
            throw new EAdminException(CMSAdminResources.UNKNOWNHOST, false);
        } catch (IOException e) {
            mConn = null;
    	    throw new EAdminException(CMSAdminResources.SERVER_UNREACHABLE, false);
        } catch (Exception e) {
            mConn = null;
			if (Debug.isEnabled()) {
				e.printStackTrace();
			}
            throw new EAdminException(CMSAdminResources.UNKNOWNEXCEPTION, false);
        }
    }

    /**
     * Deliver the request through the connection object
     *
     * @param request request object
     * @return response object
     * @see com.netscape.certsrv.client.connection.Response
     */
    private synchronized Response sendRequest(Request request)
        throws EAdminException {
        return sendRequest(request, false);
    }

    private synchronized Response sendRequest(Request request, boolean useGET)
        throws EAdminException {

    	try {
    	    if (mConn == null) {
    	        mConn = mFactory.create(mHost, mPort);
    	    }
    	} catch (UnknownHostException e) {
    	    mConn = null;
    	    throw new EAdminException(CMSAdminResources.UNKNOWNHOST, false);
    	} catch (IOException e) {
            retryConnection();
    	    throw new EAdminException(CMSAdminResources.SERVER_UNREACHABLE, false);
    	} catch (Exception e) {
            retryConnection();
    	    if (Debug.isEnabled()) {
				e.printStackTrace();
			}
    	    throw new EAdminException(CMSAdminResources.UNKNOWNEXCEPTION, false);
    	}

        try {
    	    return processRequest(request, useGET);    
    	//all errors will set the connection to null
    	//to force re-connection and avoid null ptr exception

    	} catch (Exception e) {
            retryConnection();
         
            try {
                return processRequest(request, useGET);
            } catch (InterruptedIOException ex) {
       
    	        //timeout occurred
    	        mConn = null;

    	        //set time out back to original
                mCurrentTimeout = mDefaultTimeout;
    	        throw new EAdminException(CMSAdminResources.SERVER_NORESPONSE, false);
    	    } catch (SocketException ex) {
    	        mConn = null;
    	        throw new EAdminException(CMSAdminResources.SERVER_UNREACHABLE, false);
    	    } catch (IOException ex) { 
 			    if (Debug.isEnabled()) {
				    ex.printStackTrace();
			}
    	        mConn = null;
    	        throw new EAdminException(CMSAdminResources.SERVER_UNREACHABLE, false);
            } catch (EAdminException ex) {
                throw ex;
    	    } catch (Exception ex) {
    	        mConn = null;
 			    if (Debug.isEnabled()) {
				    ex.printStackTrace();
			    }
    	        throw new EAdminException(CMSAdminResources.UNKNOWNEXCEPTION, false);
            }
    	}
    }

    private Response processRequest(Request request, boolean useGET) throws Exception {
        //packaging the request
        StringBuffer sb = new StringBuffer();
        if (useGET) {
          sb.append("GET /" + request.getPrefix() + "?");
          Enumeration names = request.getElements();
          while (names.hasMoreElements()) {
            String name = (String)names.nextElement();
            sb.append(name);
            sb.append("=");
            if (request.get(name) != null) {
                sb.append(java.net.URLEncoder.encode(request.get(name)));
            }
            if (names.hasMoreElements())
              sb.append("&");
          }
        } else {
          sb.append("POST /" + request.getPrefix());
        }
            sb.append(" HTTP/1.0\n");

        StringBuffer sb1 = new StringBuffer();
        if (!useGET) {
            sb.append("Content-type: application/x-www-form-urlencoded\n");
          Enumeration names = request.getElements();
          while (names.hasMoreElements()) {
            String name = (String)names.nextElement();
            sb1.append(name);
            sb1.append("=");
            if (request.get(name) != null) {
                sb1.append(java.net.URLEncoder.encode(request.get(name)));
            }
            if (names.hasMoreElements())
              sb1.append("&");
          }
            sb.append("Content-length: " + sb1.toString().length() + "\n");
        }
 
        sb.append("Pragma: no-cache\n");
        if (mIsKeepAlive) {
                sb.append("Connection: Keep-Alive\n");
        }
 
        if (mAuthType.equals("") || mAuthType.equals("pwd")) {
            BasicAuthenticator auth = (BasicAuthenticator)mAuth;
            // sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            // sb.append("Authorization: Basic " +
            //          encoder.encodeBuffer((auth.getUserid() +
            //                               ":" + auth.getPassword()).getBytes()) + "\n");
            sb.append("Authorization: Basic " +
                      b64encode((auth.getUserid() +
                                          ":" + auth.getPassword()).getBytes()) + "\n");
        } else if (mAuthType.equals("sslclientauth")) {
            sb.append("\n");
        } else {
            throw new EAdminException(CMSAdminResources.AUTHENNOTSUPPORTED, false);
        }

        if (!useGET) {
            sb.append(sb1.toString());
        }
        //Debug.println(sb.toString());
 
        //System.out.println("AdminConnection: sendRequest() - sending");
        int timeout = mDefaultTimeout;
        if (mCurrentTimeout > mDefaultTimeout)
            timeout = mCurrentTimeout;
            mConn.setSoTimeout(timeout);
            mConn.sendRequest(sb.toString());

            Response resp = new Response(mConn.getResponse());
 
            if (!mIsKeepAlive) {
                mConn.disconnect();
                mConn = null;
            }
 
            //set time out back to original
            mConn.setSoTimeout(mDefaultTimeout);
            mCurrentTimeout = mDefaultTimeout;
            return resp;
    }
	
	private void checkParams(String dest,String scope,String id)
	{
		NameValuePairs pairs = new NameValuePairs();

		checkParams(dest,scope,id,pairs);
	}

	private void checkParams(String dest,String scope,String id, NameValuePairs pairs)
	{
		boolean bad=false;
		if (dest == null) {
			Debug.println("** WARNING **: 'dest' = null");
			bad = true;
		}
		if (scope == null) {
			Debug.println("** WARNING ** : 'scope' = null");
			bad = true;
		}
		if (id == null) {
			Debug.println("** WARNING ** : 'id' = null");
			bad = true;
		}
		if (pairs == null) {
			Debug.println("** WARNING ** : 'pairs' = null");
			bad = true;
		}
		if (bad) {
			Debug.println("dest = "+dest);
			Debug.println("scope = "+scope);
			Debug.println("id = "+id);
			Debug.println("---------");
		}
	}
}