summaryrefslogtreecommitdiffstats
path: root/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
blob: c98fe219335a2c05ddc9e7fadea4aa71073195ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
package com.netscape.pkisilent.http;

// --- 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 ---

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.mozilla.jss.crypto.X509Certificate;
import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;
import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback;
import org.mozilla.jss.ssl.SSLSocket;
import org.mozilla.jss.ssl.TestCertApprovalCallback;
import org.mozilla.jss.ssl.TestClientCertificateSelectionCallback;

import com.netscape.cmsutil.util.Utils;
import com.netscape.pkisilent.argparser.ArgParser;
import com.netscape.pkisilent.argparser.StringHolder;
import com.netscape.pkisilent.common.ComCrypto;

public class HTTPClient implements SSLCertificateApprovalCallback {

    public static final int BUFFER_SIZE = 4096;
    public boolean debugMode = true;

    public static String basic_auth_header_value = null;

    public static String cs_hostname = null;
    public static String cs_port = null;
    public static String ssl = null;
    public static String client_certdb_dir = null;
    public static String client_certdb_pwd = null;
    public static String client_cert_nickname = null;
    public static String uri = null;
    public static String query = null;
    public static String request_type = null;
    public static String user_id = null;
    public static String user_password = null;
    public static String auth_type = null;
    public static String debug = null;

    public static boolean parse_xml = false;

    public static X509Certificate server_cert = null;

    // cookie variable for CS install UI
    public static String j_session_id = null;
    public static boolean ecc_support = false;

    public HTTPClient() {
        // constructor
        // turn off ecc by default
        ecc_support = true;
    }

    public HTTPClient(boolean ecc) {
        ecc_support = ecc;
    }

    public boolean setCipherPref(SSLSocket socket) {

        if (ecc_support) {
            int ecc_Ciphers[] = {
                    SSLSocket.TLS_ECDH_ECDSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
                    SSLSocket.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
                    SSLSocket.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_NULL_SHA,
                    SSLSocket.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
                    SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
                    SSLSocket.TLS_ECDH_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_RSA_WITH_RC4_128_SHA,
                    SSLSocket.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
                    SSLSocket.TLS_ECDHE_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
                    SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
                    SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
                    0 };

            try {
                for (int i = 0; i < ecc_Ciphers.length; i++) {
                    if (ecc_Ciphers[i] > 0)
                        socket.setCipherPreference(
                                ecc_Ciphers[i], true);
                }
            } catch (Exception e) {
                System.out.println("ERROR: unable to set ECC Cipher List");
                System.out.println("ERROR: Exception  = " + e.getMessage());
            }

        }
        return true;
    }

    public boolean disableSSL2(SSLSocket socket) {
        try {
            SSLSocket.enableSSL3Default(true);
            socket.enableSSL3(true);
            socket.enableSSL2(false);
            SSLSocket.enableSSL2Default(false);
            socket.enableV2CompatibleHello(false);
        } catch (Exception e) {
            System.out.println("ERROR: Exception  = " + e.getMessage());
        }
        return true;
    }

    public X509Certificate getServerCert() {
        return server_cert;
    }

    public void set_parse_xml(boolean b) {
        parse_xml = b;
    }

    public boolean approve(X509Certificate cert,
            SSLCertificateApprovalCallback.ValidityStatus status) {

        // when this method is called by SSLSocket we get the server cert
        // we can capture this for future use.
        server_cert = cert;
        return true;
    }

    public boolean testsslConnect(String hostname, String portnumber) {
        boolean st = true;

        try {

            System.out.println("#############################################");
            System.out.println("Attempting to connect to: " + hostname + ":" +
                            portnumber);

            Integer x = new Integer(portnumber);
            int port = x.intValue();

            SSLClientCertificateSelectionCallback certSelectionCallback =
                                new TestClientCertificateSelectionCallback();

            Socket js = new Socket(InetAddress.getByName(hostname), port);
            SSLSocket socket = new SSLSocket(js, hostname, this,
                        certSelectionCallback);
            setCipherPref(socket);
            disableSSL2(socket);
            socket.forceHandshake();
            System.out.println("Connected.");
            socket.setUseClientMode(true);

            // test connection to obtain server cert. close it.
            socket.close();

        }

        catch (Exception e) {
            System.err.println("Exception: Unable to Send Request:" + e);
            e.printStackTrace();
            st = false;
        }

        if (!st)
            return false;
        else
            return true;
    }

    // performs ssl connect to given host/port requiring client auth
    // posts the given query data
    // returns HTTPResponse
    public HTTPResponse sslConnectClientAuth(String hostname, String portnumber,
                                String client_cert, String url, String query) {

        boolean st = true;
        HTTPResponse hr = null;
        PrintStream ps = null;
        SSLSocket socket = null;
        Socket js = null;
        OutputStream rawos = null;
        BufferedOutputStream os = null;
        try {

            System.out.println("#############################################");
            System.out.println("Attempting to connect to: " + hostname + ":" +
                            portnumber);

            Integer x = new Integer(portnumber);
            int port = x.intValue();

            SSLCertificateApprovalCallback approvalCallback =
                                new TestCertApprovalCallback();
            CertSelection certSelectionCallback =
                                new CertSelection();

            // Client Cert for Auth is set here
            certSelectionCallback.setClientCert(client_cert);

            js = new Socket(InetAddress.getByName(hostname), port);
            socket = new SSLSocket(js, hostname, approvalCallback,
                        certSelectionCallback);
            disableSSL2(socket);
            setCipherPref(socket);
            socket.forceHandshake();
            System.out.println("Connected.");
            socket.setUseClientMode(true);

            System.out.println("Posting Query = " +
                                "https://" + hostname +
                                ":" + portnumber +
                                "/" + url +
                                "?" + query);

            rawos = socket.getOutputStream();
            os = new BufferedOutputStream(rawos);
            ps = new PrintStream(os);

            ps.println("POST " + url + " HTTP/1.0");
            ps.println("Connection: Keep-Alive");
            ps.println("Content-type: application/x-www-form-urlencoded");
            ps.println("Content-length: " + query.length());
            ps.println("");
            ps.print(query);
            ps.flush();
            os.flush();
            hr = readResponse(socket.getInputStream());
            hr.parseContent();
        }

        catch (Exception e) {
            System.err.println("Exception: Unable to Send Request:" + e);
            e.printStackTrace();
            st = false;
        } finally {
            if (ps != null) {
                ps.close();
                ps = null;
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null)
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            if (rawos != null)
                try {
                    rawos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            if (js != null)
                try {
                    js.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }

        if (!st)
            return null;
        else
            return hr;
    }

    // performs ssl connect to given host/port
    // posts the given query data
    // returns HTTPResponse
    public HTTPResponse sslConnect(String hostname, String portnumber,
                                String url, String query) throws Exception {

        Socket js = null;
        SSLSocket socket = null;
        OutputStream rawos = null;
        BufferedOutputStream os = null;
        PrintStream ps = null;

        try {

            System.out.println("#############################################");
            System.out.println("Attempting to connect to: " + hostname + ":" +
                            portnumber);

            Integer x = new Integer(portnumber);
            int port = x.intValue();

            SSLCertificateApprovalCallback approvalCallback =
                                new TestCertApprovalCallback();
            SSLClientCertificateSelectionCallback certSelectionCallback =
                                new TestClientCertificateSelectionCallback();

            js = new Socket(InetAddress.getByName(hostname), port);
            socket = new SSLSocket(js, hostname, approvalCallback,
                        certSelectionCallback);
            setCipherPref(socket);
            disableSSL2(socket);
            socket.forceHandshake();
            System.out.println("Connected.");
            socket.setUseClientMode(true);

            System.out.println("Posting Query = " +
                                "https://" + hostname +
                                ":" + portnumber +
                                "/" + url +
                                "?" + query);

            rawos = socket.getOutputStream();
            os = new BufferedOutputStream(rawos);
            ps = new PrintStream(os);

            ps.println("POST " + url + " HTTP/1.0");

            // check to see if we have a cookie to send
            if (j_session_id != null)
                ps.println("Cookie: " + j_session_id);

            ps.println("Content-type: application/x-www-form-urlencoded");
            ps.println("Content-length: " + query.length());
            ps.println("Connection: Keep-Alive");

            // special header posting if available
            if (basic_auth_header_value != null) {
                System.out.println("basic_auth = " + basic_auth_header_value);
                ps.println("Authorization: Basic " + basic_auth_header_value);
            }

            ps.println("");
            ps.println(query);
            ps.println("\r");
            ps.flush();
            os.flush();

            HTTPResponse hr = readResponse(socket.getInputStream());
            hr.parseContent();

            return hr;

        } catch (Exception e) {
            System.err.println("Exception: Unable to Send Request:" + e);
            throw e;

        } finally {
            if (ps != null)
                ps.close();
            if (os != null)
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            if (rawos != null)
                try {
                    rawos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            if (socket != null)
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            if (js != null)
                try {
                    js.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
    }

    // performs non ssl connect to given host/port
    // posts the given query data
    // returns HTTPResponse
    public HTTPResponse nonsslConnect(String hostname, String portnumber,
                                String url, String query) throws Exception {

        Socket socket = null;
        OutputStream rawos = null;
        BufferedOutputStream os = null;
        PrintStream ps = null;
        try {

            System.out.println("#############################################");
            System.out.println("Attempting to connect to: " + hostname + ":" +
                            portnumber);

            Integer x = new Integer(portnumber);
            int port = x.intValue();

            socket = new Socket(hostname, port);

            System.out.println("Posting Query = " +
                                "http://" + hostname +
                                ":" + portnumber +
                                "/" + url +
                                "?" + query);

            rawos = socket.getOutputStream();
            os = new BufferedOutputStream(rawos);
            ps = new PrintStream(os);

            System.out.println("Connected.");

            ps.println("POST " + url + " HTTP/1.0");

            // check to see if we have a cookie to send
            if (j_session_id != null)
                ps.println("Cookie: " + j_session_id);

            ps.println("Content-type: application/x-www-form-urlencoded");
            ps.println("Content-length: " + query.length());
            ps.println("Connection: Keep-Alive");

            // special header posting if available
            if (basic_auth_header_value != null) {
                System.out.println("basic_auth = " + basic_auth_header_value);
                ps.println("Authorization: Basic " + basic_auth_header_value);
            }

            ps.println("");
            ps.println(query);
            ps.println("\r");
            ps.flush();
            os.flush();

            HTTPResponse hr = readResponse(socket.getInputStream());
            hr.parseContent();

            return hr;

        } catch (Exception e) {
            System.err.println("Exception: Unable to Send Request:" + e);
            throw e;

        } finally {
            if (ps != null)
                ps.close();
            if (os != null)
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            if (rawos != null)
                try {
                    rawos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            if (socket != null)
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
    }

    public HTTPResponse readResponse(InputStream inputStream)
            throws Exception {
        // read response from http input stream and return HTTPResponse
        byte[] buffer = new byte[BUFFER_SIZE];
        HTTPResponse response = null;
        int statusCode = 0;

        // Read an initial chunk of the response from the server.
        int bytesRead = inputStream.read(buffer);
        if (bytesRead < 0) {
            throw new IOException("Unexpected end of input stream from server");
        }

        // Hopefully, this initial chunk will contain the entire header, so look for
        // it.  Technically, HTTP is supposed to use CRLF as the end-of-line
        // character, so look for that first, but also check for LF by itself just
        // in case.
        int headerEndPos = -1;
        int dataStartPos = -1;
        for (int i = 0; i < (bytesRead - 3); i++) {
            if ((buffer[i] == '\r') && (buffer[i + 1] == '\n') &&
                    (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
                headerEndPos = i;
                dataStartPos = i + 4;
                break;
            }
        }

        if (headerEndPos < 0) {
            for (int i = 0; i < (bytesRead - 1); i++) {
                if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
                    headerEndPos = i;
                    dataStartPos = i + 2;
                    break;
                }
            }
        }

        // In the event that we didn't get the entire header in the first pass, keep
        // reading until we do have enough.
        if (headerEndPos < 0) {
            byte[] buffer2 = new byte[BUFFER_SIZE];
            while (headerEndPos < 0) {
                int startPos = bytesRead;
                int moreBytesRead = inputStream.read(buffer2);
                if (moreBytesRead < 0) {
                    throw new IOException("Unexpected end of input stream from server " +
                                "when reading more data from response");
                }

                byte[] newBuffer = new byte[bytesRead + moreBytesRead];
                System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
                System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead);
                buffer = newBuffer;
                bytesRead += moreBytesRead;

                for (int i = startPos; i < (bytesRead - 3); i++) {
                    if ((buffer[i] == '\r') && (buffer[i + 1] == '\n') &&
                            (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
                        headerEndPos = i;
                        dataStartPos = i + 4;
                        break;
                    }
                }

                if (headerEndPos < 0) {
                    for (int i = startPos; i < (bytesRead - 1); i++) {
                        if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
                            headerEndPos = i;
                            dataStartPos = i + 2;
                            break;
                        }
                    }
                }
            }
        }

        // At this point, we should have the entire header, so read and analyze it.
        String headerStr = new String(buffer, 0, headerEndPos);
        StringTokenizer tokenizer = new StringTokenizer(headerStr, "\r\n");
        if (tokenizer.hasMoreTokens()) {
            String statusLine = tokenizer.nextToken();
            if (debugMode) {
                System.out.println("RESPONSE STATUS:  " + statusLine);
            }

            int spacePos = statusLine.indexOf(' ');
            if (spacePos < 0) {
                System.out.println("ERROR: Unable to parse response header -- could " +
                                "not find protocol/version delimiter");
                return null;

            }

            String protocolVersion = statusLine.substring(0, spacePos);
            int spacePos2 = statusLine.indexOf(' ', spacePos + 1);
            if (spacePos2 < 0) {
                System.out.println("ERROR: Unable to parse response header -- could " +
                                "not find response code delimiter");
                return null;
            }

            try {
                statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
                                                           spacePos2));
            } catch (NumberFormatException nfe) {
                System.out.println("Unable to parse response header -- could " +
                                "not interpret status code as an integer");
                return null;
            }

            String responseMessage = statusLine.substring(spacePos2 + 1);
            response = new HTTPResponse(statusCode, protocolVersion,
                                  responseMessage);

            while (tokenizer.hasMoreTokens()) {
                String headerLine = tokenizer.nextToken();
                if (debugMode) {
                    System.out.println("RESPONSE HEADER:  " + headerLine);
                }

                int colonPos = headerLine.indexOf(':');
                if (colonPos < 0) {
                    if (headerLine.toLowerCase().startsWith("http/")) {
                        // This is a direct violation of RFC 2616, but certain HTTP servers
                        // seem to immediately follow a 100 continue with a 200 ok without
                        // the required CRLF in between.
                        System.out.println("ERROR: Found illegal status line '" + headerLine +
                                "'in the middle of a response -- attempting " +
                                "to deal with it as the start of a new " +
                                "response.");
                        statusLine = headerLine;
                        spacePos = statusLine.indexOf(' ');
                        if (spacePos < 0) {
                            System.out.println("ERROR: Unable to parse response header -- " +
                                      "could not find protocol/version " +
                                      "delimiter");
                            return null;
                        }

                        protocolVersion = statusLine.substring(0, spacePos);
                        spacePos2 = statusLine.indexOf(' ', spacePos + 1);
                        if (spacePos2 < 0) {
                            System.out.println("ERROR: Unable to parse response header -- " +
                                      "could not find response code delimiter");
                            return null;
                        }

                        try {
                            statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
                                                                 spacePos2));
                        } catch (NumberFormatException nfe) {
                            System.out.println("ERROR: Unable to parse response header -- " +
                                      "could not interpret status code as an " +
                                      "integer");
                            return null;
                        }

                        responseMessage = statusLine.substring(spacePos2 + 1);
                        response = new HTTPResponse(statusCode, protocolVersion,
                                        responseMessage);
                        continue;
                    } else {
                        System.out.println("ERROR: Unable to parse response header -- no " +
                                    "colon found on header line \"" +
                                    headerLine + "\"");
                    }
                }

                String headerName = headerLine.substring(0, colonPos);
                String headerValue = headerLine.substring(colonPos + 1).trim();
                response.addHeader(headerName, headerValue);
            }
        } else {
            // This should never happen -- an empty response
            System.out.println("Unable to parse response header -- empty " +
                              "header");
            throw new Exception("Unable to create response. Empty header.");
        }

        // If the status code was 100 (continue), then it was an intermediate header
        // and we need to keep reading until we get the real response header.
        while (response.getStatusCode() == 100) {
            if (dataStartPos < bytesRead) {
                byte[] newBuffer = new byte[bytesRead - dataStartPos];
                System.arraycopy(buffer, dataStartPos, newBuffer, 0, newBuffer.length);
                buffer = newBuffer;
                bytesRead = buffer.length;

                headerEndPos = -1;
                for (int i = 0; i < (bytesRead - 3); i++) {
                    if ((buffer[i] == '\r') && (buffer[i + 1] == '\n') &&
                            (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
                        headerEndPos = i;
                        dataStartPos = i + 4;
                        break;
                    }
                }

                if (headerEndPos < 0) {
                    for (int i = 0; i < (bytesRead - 1); i++) {
                        if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
                            headerEndPos = i;
                            dataStartPos = i + 2;
                            break;
                        }
                    }
                }
            } else {
                buffer = new byte[0];
                bytesRead = 0;
                headerEndPos = -1;
            }

            byte[] buffer2 = new byte[BUFFER_SIZE];
            while (headerEndPos < 0) {
                int startPos = bytesRead;
                int moreBytesRead = inputStream.read(buffer2);

                if (moreBytesRead < 0) {
                    throw new IOException("Unexpected end of input stream from server " +
                                "when reading more data from response");
                }

                byte[] newBuffer = new byte[bytesRead + moreBytesRead];
                System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
                System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead);
                buffer = newBuffer;
                bytesRead += moreBytesRead;

                for (int i = startPos; i < (bytesRead - 3); i++) {
                    if ((buffer[i] == '\r') && (buffer[i + 1] == '\n') &&
                            (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
                        headerEndPos = i;
                        dataStartPos = i + 4;
                        break;
                    }
                }

                if (headerEndPos < 0) {
                    for (int i = startPos; i < (bytesRead - 1); i++) {
                        if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
                            headerEndPos = i;
                            dataStartPos = i + 2;
                            break;
                        }
                    }
                }
            }

            // We should now have the next header, so examine it.
            headerStr = new String(buffer, 0, headerEndPos);
            tokenizer = new StringTokenizer(headerStr, "\r\n");
            if (tokenizer.hasMoreTokens()) {
                String statusLine = tokenizer.nextToken();
                if (debugMode) {
                    System.out.println("RESPONSE STATUS:  " + statusLine);
                }

                int spacePos = statusLine.indexOf(' ');
                if (spacePos < 0) {
                    System.out.println("Unable to parse response header -- could " +
                                  "not find protocol/version delimiter");
                }

                String protocolVersion = statusLine.substring(0, spacePos);
                int spacePos2 = statusLine.indexOf(' ', spacePos + 1);
                if (spacePos2 < 0) {
                    System.out.println("Unable to parse response header -- could " +
                                  "not find response code delimiter");
                }

                try {
                    statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
                                                             spacePos2));
                } catch (NumberFormatException nfe) {
                    System.out.println("Unable to parse response header -- could " +
                                  "not interpret status code as an integer");
                }

                String responseMessage = statusLine.substring(spacePos2 + 1);
                response = new HTTPResponse(statusCode, protocolVersion,
                                    responseMessage);

                while (tokenizer.hasMoreTokens()) {
                    String headerLine = tokenizer.nextToken();
                    if (debugMode) {
                        System.out.println("RESPONSE HEADER:  " + headerLine);
                    }

                    int colonPos = headerLine.indexOf(':');
                    if (colonPos < 0) {
                        System.out.println("Unable to parse response header -- no " +
                                    "colon found on header line \"" +
                                    headerLine + "\"");
                    }

                    String headerName = headerLine.substring(0, colonPos);
                    String headerValue = headerLine.substring(colonPos + 1).trim();
                    response.addHeader(headerName, headerValue);
                }
            } else {
                // This should never happen -- an empty response
                System.out.println("Unable to parse response header -- empty " +
                                "header");
            }
        }

        // Now that we have parsed the header, use it to determine how much data
        // there is.  If we're lucky, the server will have told us using the
        // "Content-Length" header.
        int contentLength = response.getContentLength();

        if (contentLength >= 0) {
            readContentDataUsingLength(response, inputStream, contentLength, buffer,
                                 dataStartPos, bytesRead);
        } else {
            // It's not chunked encoding, so our last hope is that the connection
            // will be closed when all the data has been sent.
            String connectionStr = response.getHeader("connection");
            if ((connectionStr != null) &&
                    (!connectionStr.equalsIgnoreCase("close"))) {
                System.out.println("ERROR:Unable to determine how to find when the " +
                                  "end of the data has been reached (no " +
                                  "content length, not chunked encoding, " +
                                  "connection string is \"" + connectionStr +
                                  "\" rather than \"close\")");
            } else {
                readContentDataUsingConnectionClose(response, inputStream, buffer,
                                              dataStartPos, bytesRead);
            }
        }
        // Finally, return the response to the caller.
        return response;
    }

    /**
     * Reads the actual data of the response based on the content length provided
     * by the server in the response header.
     *
     * @param response The response with which the data is associated.
     * @param inputStream The input stream from which to read the response.
     * @param contentLength The number of bytes that the server said are in the
     *            response.
     * @param dataRead The data that we have already read. This includes
     *            the header data, but may also include some or all of
     *            the content data as well.
     * @param dataStartPos The position in the provided array at which the
     *            content data starts.
     * @param dataBytesRead The total number of valid bytes in the provided
     *            array that should be considered part of the
     *            response (the number of header bytes is included in
     *            this count).
     *
     * @throws IOException If a problem occurs while reading data from the
     *             server.
     */
    private void readContentDataUsingLength(HTTPResponse response,
                                          InputStream inputStream,
                                          int contentLength, byte[] dataRead,
                                          int dataStartPos, int dataBytesRead)
            throws IOException {
        if (contentLength <= 0) {
            response.setResponseData(new byte[0]);
            return;
        }

        byte[] contentBytes = new byte[contentLength];
        int startPos = 0;
        if (dataBytesRead > dataStartPos) {
            // We've already got some data to include in the header, so copy that into
            // the content array.  Make sure the server didn't do something stupid
            // like return more data than it told us was in the response.
            int bytesToCopy = Math.min(contentBytes.length,
                                 (dataBytesRead - dataStartPos));
            System.arraycopy(dataRead, dataStartPos, contentBytes, 0, bytesToCopy);
            startPos = bytesToCopy;
        }

        byte[] buffer = new byte[BUFFER_SIZE];
        while (startPos < contentBytes.length) {
            int bytesRead = inputStream.read(buffer);
            if (bytesRead < 0) {
                throw new IOException("Unexpected end of input stream reached when " +
                              "reading data from the server");
            }

            System.arraycopy(buffer, 0, contentBytes, startPos, bytesRead);
            startPos += bytesRead;
        }

        response.setResponseData(contentBytes);
    }

    /**
     * Reads the actual data of the response using chunked encoding, which is a
     * way for the server to provide the data in several chunks rather than all at
     * once.
     *
     * @param response The response with which the data is associated.
     * @param inputStream The input stream from which to read the response.
     * @param dataRead The data that we have already read. This includes
     *            the header data, but may also include some or all of
     *            the content data as well.
     * @param dataStartPos The position in the provided array at which the
     *            content data starts.
     * @param dataBytesRead The total number of valid bytes in the provided
     *            array that should be considered part of the
     *            response (the number of header bytes is included in
     *            this count).
     *
     * @throws IOException If a problem occurs while reading data from the
     *             server.
     */
    private void readContentDataUsingConnectionClose(HTTPResponse response,
                                                   InputStream inputStream,
                                                   byte[] dataRead,
                                                   int dataStartPos,
                                                   int dataBytesRead)
            throws IOException {
        // Create an array list that we will use to hold the chunks of information
        // read from the server.
        ArrayList<ByteBuffer> bufferList = new ArrayList<ByteBuffer>();

        // Create a variable to hold the total number of bytes in the data.
        int totalBytes = 0;

        // See if we have unread data in the array already provided.
        int existingBytes = dataBytesRead - dataStartPos;
        if (existingBytes > 0) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(existingBytes);
            byteBuffer.put(dataRead, dataStartPos, existingBytes);
            bufferList.add(byteBuffer);
            totalBytes += existingBytes;
        }

        // Keep reading until we hit the end of the input stream.
        byte[] buffer = new byte[BUFFER_SIZE];
        while (true) {
            try {
                int bytesRead = inputStream.read(buffer);
                if (bytesRead < 0) {
                    // We've hit the end of the stream and therefore the end of the
                    // document.
                    break;
                } else if (bytesRead > 0) {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(bytesRead);
                    byteBuffer.put(buffer, 0, bytesRead);
                    bufferList.add(byteBuffer);
                    totalBytes += bytesRead;
                }
            } catch (IOException ioe) {
                // In this case we'll assume that the end of the stream has been
                // reached.  It's possible that there was some other error, but we can't
                // do anything about it so try to process what we've got so far.
                System.out.println("ERROR: unable to read until end of stream");
                System.out.println("ERROR: " + ioe.getMessage());
                break;
            }
        }

        // Assemble the contents of all the buffers into a big array and store that
        // array in the response.
        int startPos = 0;
        byte[] contentData = new byte[totalBytes];
        for (int i = 0; i < bufferList.size(); i++) {
            ByteBuffer byteBuffer = bufferList.get(i);
            byteBuffer.flip();
            byteBuffer.get(contentData, startPos, byteBuffer.limit());
            startPos += byteBuffer.limit();
        }
        response.setResponseData(contentData);
    }

    // performs ssl connect to given host/port
    // posts the given query data - format - a byte array
    // returns HTTPResponse

    public HTTPResponse sslConnect(String hostname, String portnumber,
                                String url, byte[] data) {

        boolean st = true;
        HTTPResponse hr = null;
        DataOutputStream dos = null;
        SSLSocket socket = null;
        Socket js = null;
        try {

            System.out.println("#############################################");
            System.out.println("Attempting to connect to: " + hostname + ":" +
                            portnumber);

            Integer x = new Integer(portnumber);
            int port = x.intValue();

            SSLCertificateApprovalCallback approvalCallback =
                                new TestCertApprovalCallback();
            SSLClientCertificateSelectionCallback certSelectionCallback =
                                new TestClientCertificateSelectionCallback();

            js = new Socket(InetAddress.getByName(hostname), port);
            socket = new SSLSocket(js, hostname, approvalCallback,
                        certSelectionCallback);
            setCipherPref(socket);
            disableSSL2(socket);
            socket.forceHandshake();
            System.out.println("Connected.");
            socket.setUseClientMode(true);

            dos = new DataOutputStream(socket.getOutputStream());
            dos.writeBytes("POST /ocsp HTTP/1.0\r\n");
            dos.writeBytes("Content-length: " + data.length + "\r\n");
            dos.writeBytes("\r\n");
            dos.write(data);
            dos.writeBytes("\r\n");
            dos.flush();
            hr = readResponse(socket.getInputStream());
            hr.parseContent();

        }

        catch (Exception e) {
            System.err.println("Exception: Unable to Send Request:" + e);
            e.printStackTrace();
            st = false;
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (js != null) {
                try {
                    js.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (!st)
            return null;
        else
            return hr;
    }

    // performs non ssl connect to given host/port
    // posts the given query data
    // returns HTTPResponse
    public HTTPResponse nonsslConnect(String hostname, String portnumber,
                                String url, byte[] data) {

        boolean st = true;
        HTTPResponse hr = null;
        DataOutputStream dos = null;
        Socket socket = null;
        try {

            System.out.println("#############################################");
            System.out.println("Attempting to connect to: " + hostname + ":" +
                            portnumber);

            Integer x = new Integer(portnumber);
            int port = x.intValue();

            socket = new Socket(hostname, port);

            System.out.println("Posting Query = " +
                                "http://" + hostname +
                                ":" + portnumber +
                                "/" + url);

            System.out.println("Connected.");

            dos = new DataOutputStream(socket.getOutputStream());
            dos.writeBytes("POST " + url + " HTTP/1.0\r\n");
            dos.writeBytes("Content-length: " + data.length + "\r\n");
            dos.writeBytes("\r\n");
            dos.write(data);
            dos.writeBytes("\r\n");
            dos.flush();

            hr = readResponse(socket.getInputStream());
            hr.parseContent();

        }

        catch (Exception e) {
            System.err.println("Exception: Unable to Send Request:" + e);
            e.printStackTrace();
            st = false;
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (!st)
            return null;
        else
            return hr;
    }

    public static boolean init_nss() {
        try {

            ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
                                        client_certdb_pwd,
                                        null,
                                        null,
                                        null);
            cCrypt.setDebug(true);
            cCrypt.setGenerateRequest(false);
            cCrypt.loginDB();
        } catch (Exception e) {
            System.out.println("ERROR: unable to login to : " +
                            client_certdb_dir);
            return false;
        }

        return true;
    }

    public static void main(String args[]) throws Exception  {
        HTTPClient hc = new HTTPClient();
        HTTPResponse hr = null;

        // parse args
        StringHolder x_hostname = new StringHolder();
        StringHolder x_port = new StringHolder();
        StringHolder x_ssl = new StringHolder();
        StringHolder x_client_certdb_dir = new StringHolder();
        StringHolder x_client_certdb_pwd = new StringHolder();
        StringHolder x_client_cert_nickname = new StringHolder();
        StringHolder x_uri = new StringHolder();
        StringHolder x_query = new StringHolder();
        StringHolder x_request_type = new StringHolder();
        StringHolder x_auth_type = new StringHolder();
        StringHolder x_user_id = new StringHolder();
        StringHolder x_user_password = new StringHolder();
        StringHolder x_debug = new StringHolder();
        StringHolder x_decode = new StringHolder();

        // parse the args
        ArgParser parser = new ArgParser("HTTPClient");

        parser.addOption("-hostname %s #Hostname",
                            x_hostname);
        parser.addOption("-port %s #port number",
                            x_port);
        parser.addOption("-ssl %s #HTTP or HTTPS[true or false]",
                            x_ssl);
        parser.addOption("-client_certdb_dir %s #CertDB dir",
                            x_client_certdb_dir);
        parser.addOption("-client_certdb_pwd %s #CertDB password",
                            x_client_certdb_pwd);
        parser.addOption("-client_cert_nickname %s #client cert nickname",
                            x_client_cert_nickname);
        parser.addOption("-uri %s #URI",
                            x_uri);
        parser.addOption("-query %s #URL encoded query string[note: url encode value part only for CS operations]",
                            x_query);
        parser.addOption("-request_type %s #Request Type [ post ]",
                            x_request_type);
        parser.addOption("-user_id %s #user id for authorization",
                            x_user_id);
        parser.addOption("-user_password %s #password for authorization",
                            x_user_password);
        parser.addOption("-auth_type %s #type of authorization [ BASIC ]",
                            x_auth_type);
        parser.addOption("-debug %s #enables display of debugging info",
                            x_debug);
        parser.addOption("-decode %s #URL Decode the resulting output",
                            x_decode);

        // and then match the arguments
        String[] unmatched = null;
        unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);

        if (unmatched != null) {
            System.out.println("ERROR: Argument Mismatch");
            System.exit(-1);
        }

        // set variables
        cs_hostname = x_hostname.value;
        cs_port = x_port.value;
        ssl = x_ssl.value;
        client_certdb_dir = x_client_certdb_dir.value;
        client_certdb_pwd = x_client_certdb_pwd.value;
        client_cert_nickname = x_client_cert_nickname.value;
        uri = x_uri.value;
        query = x_query.value;
        request_type = x_request_type.value;
        user_id = x_user_id.value;
        user_password = x_user_password.value;
        auth_type = x_auth_type.value;
        debug = x_debug.value;

        String decode = x_decode.value;

        // init_nss if needed
        boolean st = init_nss();
        if (!st)
            System.exit(-1);

        // set basic auth if needed
        if (auth_type != null && auth_type.equalsIgnoreCase("BASIC")) {
            // BASE64Encoder encoder = new BASE64Encoder();

            // String temp = encoder.encodeBuffer((user_id +
            // 			":" + user_password).getBytes());
            String temp = Utils.base64encode((user_id +
                    ":" + user_password).getBytes());

            // note: temp already contains \r and \n.
            // remove \r and \n from the base64 encoded string.
            // causes problems when sending http post requests
            // using PrintStream.println()

            temp = temp.replaceAll("\\r", "");
            temp = temp.replaceAll("\\n", "");

            basic_auth_header_value = temp;
        }

        // route to proper function

        if (ssl != null && ssl.equalsIgnoreCase("true")) {
            if (client_cert_nickname != null &&
                    !client_cert_nickname.equalsIgnoreCase("null")) {
                // ssl client auth call

                hr = hc.sslConnectClientAuth(cs_hostname, cs_port,
                        client_cert_nickname,
                        uri, query);
            }

            else {
                // ssl client call
                hr = hc.sslConnect(cs_hostname, cs_port, uri, query);
            }
        } else if (ssl != null && ssl.equalsIgnoreCase("false")) {
            // non ssl connect
            hr = hc.nonsslConnect(cs_hostname, cs_port, uri, query);
        } else {
            System.out.println("ERROR: ssl parameter is null");
            System.exit(-1);
        }

        // collect and print response

        if (hr.getStatusCode() == 200)
            System.out.println("Response from Host:" + cs_hostname + " OK");
        else {
            System.out.println("ERROR: unable to get response from host:" +
                                cs_hostname);
            System.exit(-1);
        }

        String responseValue = null;
        if (decode.equalsIgnoreCase("true"))
            responseValue = URLDecoder.decode(hr.getHTML(), "UTF-8");
        else
            responseValue = hr.getHTML();

        System.out.println("###############################");
        System.out.println("RESULT=" + responseValue);
        System.out.println("###############################");

    }

};