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
/*
 * Copyright (C) 2015-2018 Neo Visionaries Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package NeoVisionaries.WebSockets;


import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;


/**
 * Proxy settings.
 * 
 * <EMBED CLASS='external-html' DATA-FILE-ID=LICENSE><BR />
 *
 * <p>
 * If a proxy server's host name is set (= if {@link #getHost()}
 * returns a non-null value), a socket factory that creates a
 * socket to communicate with the proxy server is selected based
 * on the settings of this {@code ProxySettings} instance. The
 * following is the concrete flow to select a socket factory.
 * </p>
 *
 * <blockquote>
 * <ol>
 * <li>
 *   If {@link #isSecure()} returns {@code true},
 *   <ol type="i">
 *     <li>
 *       If an {@link SSLContext} instance has been set by {@link
 *       #setSSLContext(SSLContext)}, the value returned from {@link
 *       SSLContext#getSocketFactory()} method of the instance is used.
 *     </li>
 *     <li>
 *       Otherwise, if an {@link SSLSocketFactory} instance has been
 *       set by {@link #setSSLSocketFactory(SSLSocketFactory)}, the
 *       instance is used.
 *     </li>
 *     <li>
 *       Otherwise, the value returned from {@link SSLSocketFactory#getDefault()}
 *       is used.
 *     </li>
 *   </ol>
 * </li>
 * <li>
 *   Otherwise (= {@link #isSecure()} returns {@code false}),
 *   <ol type="i">
 *     <li>
 *       If a {@link SocketFactory} instance has been set by {@link
 *       #setSocketFactory(SocketFactory)}, the instance is used.
 *     </li>
 *     <li>
 *       Otherwise, the value returned from {@link SocketFactory#getDefault()}
 *       is used.
 *     </li>
 *   </ol>
 * </li>
 * </ol>
 * </blockquote>
 *
 * <p>
 * Note that the current implementation supports only Basic Authentication
 * for authentication at the proxy server.
 * </p>
 *
 * @see WebSocketFactory#getProxySettings()
 *
 * @since 1.3
 */
public class ProxySettings
{
    private final WebSocketFactory mWebSocketFactory;
    private final Map<String, List<String>> mHeaders;
    private final SocketFactorySettings mSocketFactorySettings;
    private boolean mSecure;
    private String mHost;
    private int mPort;
    private String mId;
    private String mPassword;
    private String[] mServerNames;


    /**
     * Constructor.
     *         A {@code WebSocketFactory} instance to be associated with.
     *
     * @param factory factory
     */
    ProxySettings(WebSocketFactory factory)
    {
        mWebSocketFactory = factory;
        mHeaders = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
        mSocketFactorySettings = new SocketFactorySettings();

        reset();
    }


    /**
     * Constructor with settings.
     *
     * @param factory
     *         A {@code WebSocketFactory} instance to be associated with.
     *
     * @param settings
     *         Settings to copy.
     *
     * @since 2.10
     */
    ProxySettings(WebSocketFactory factory, ProxySettings settings)
    {
        this(factory);

        mHeaders.putAll(settings.mHeaders);
        mSecure   = settings.mSecure;
        mHost     = settings.mHost;
        mPort     = settings.mPort;
        mId       = settings.mId;
        mPassword = settings.mPassword;

        if (settings.mServerNames != null)
        {
            mServerNames = new String[settings.mServerNames.length];
            System.arraycopy(settings.mServerNames, 0, mServerNames, 0, mServerNames.length);
        }
    }


    /**
     * Get the associated {@link WebSocketFactory} instance.
     */
    public WebSocketFactory getWebSocketFactory()
    {
        return mWebSocketFactory;
    }


    /**
     * Reset the proxy settings. To be concrete, parameter values are
     * set as shown below.
     *
     * <blockquote>
     * <table border="1" cellpadding="5" style="border-collapse: collapse;">
     *   <thead>
     *     <tr>
     *       <th>Name</th>
     *       <th>Value</th>
     *       <th>Description</th>
     *     </tr>
     *   </thead>
     *   <tbody>
     *     <tr>
     *       <td>Secure</td>
     *       <td>{@code false}</td>
     *       <td>Use TLS to connect to the proxy server or not.</td>
     *     </tr>
     *     <tr>
     *       <td>Host</td>
     *       <td>{@code null}</td>
     *       <td>The host name of the proxy server.</td>
     *     </tr>
     *     <tr>
     *       <td>Port</td>
     *       <td>{@code -1}</td>
     *       <td>The port number of the proxy server.</td>
     *     </tr>
     *     <tr>
     *       <td>ID</td>
     *       <td>{@code null}</td>
     *       <td>The ID for authentication at the proxy server.</td>
     *     </tr>
     *     <tr>
     *       <td>Password</td>
     *       <td>{@code null}</td>
     *       <td>The password for authentication at the proxy server.</td>
     *     </tr>
     *     <tr>
     *       <td>Headers</td>
     *       <td>Cleared</td>
     *       <td>Additional HTTP headers passed to the proxy server.</td>
     *     </tr>
     *     <tr>
     *       <td>Server Names</td>
     *       <td>{@code null}</td>
     *       <td>Server names for SNI (Server Name Indication).</td>
     *     </tr>
     *   </tbody>
     * </table>
     * </blockquote>
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings reset()
    {
        mSecure   = false;
        mHost     = null;
        mPort     = -1;
        mId       = null;
        mPassword = null;
        mHeaders.clear();
        mServerNames = null;

        return this;
    }


    /**
     * Check whether use of TLS is enabled or disabled.
     *
     * @return
     *         {@code true} if TLS is used in the communication with
     *         the proxy server.
     */
    public boolean isSecure()
    {
        return mSecure;
    }


    /**
     * Enable or disable use of TLS.
     *
     * @param secure
     *         {@code true} to use TLS in the communication with
     *         the proxy server.
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings setSecure(boolean secure)
    {
        mSecure = secure;

        return this;
    }


    /**
     * Get the host name of the proxy server.
     *
     * <p>
     * The default value is {@code null}. If this method returns
     * a non-null value, it is used as the proxy server.
     * </p>
     *
     * @return
     *         The host name of the proxy server.
     */
    public String getHost()
    {
        return mHost;
    }


    /**
     * Set the host name of the proxy server.
     *
     * <p>
     * If a non-null value is set, it is used as the proxy server.
     * </p>
     *
     * @param host
     *         The host name of the proxy server.
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings setHost(String host)
    {
        mHost = host;

        return this;
    }


    /**
     * Get the port number of the proxy server.
     *
     * <p>
     * The default value is {@code -1}. {@code -1} means that
     * the default port number ({@code 80} for non-secure
     * connections and {@code 443} for secure connections)
     * should be used.
     * </p>
     *
     * @return
     *         The port number of the proxy server.
     */
    public int getPort()
    {
        return mPort;
    }


    /**
     * Set the port number of the proxy server.
     *
     * <p>
     * If {@code -1} is set, the default port number ({@code 80}
     * for non-secure connections and {@code 443} for secure
     * connections) is used.
     * </p>
     *
     * @param port
     *         The port number of the proxy server.
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings setPort(int port)
    {
        mPort = port;

        return this;
    }


    /**
     * Get the ID for authentication at the proxy server.
     *
     * <p>
     * The default value is {@code null}. If this method returns
     * a non-null value, it is used as the ID for authentication
     * at the proxy server. To be concrete, the value is used to
     * generate the value of <code><a href=
     * "http://tools.ietf.org/html/rfc2616#section-14.34"
     * >Proxy-Authorization</a></code> header.
     * </p>
     *
     * @return
     *         The ID for authentication at the proxy server.
     */
    public String getId()
    {
        return mId;
    }


    /**
     * Set the ID for authentication at the proxy server.
     *
     * <p>
     * If a non-null value is set, it is used as the ID for
     * authentication at the proxy server. To be concrete, the
     * value is used to generate the value of <code><a href=
     * "http://tools.ietf.org/html/rfc2616#section-14.34"
     * >Proxy-Authorization</a></code> header.
     * </p>
     *
     * @param id
     *         The ID for authentication at the proxy server.
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings setId(String id)
    {
        mId = id;

        return this;
    }


    /**
     * Get the password for authentication at the proxy server.
     *
     * @return
     *         The password for authentication at the proxy server.
     */
    public String getPassword()
    {
        return mPassword;
    }


    /**
     * Set the password for authentication at the proxy server.
     *
     * @param password
     *         The password for authentication at the proxy server.
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings setPassword(String password)
    {
        mPassword = password;

        return this;
    }


    /**
     * Set credentials for authentication at the proxy server.
     * This method is an alias of {@link #setId(String) setId}{@code
     * (id).}{@link #setPassword(String) setPassword}{@code
     * (password)}.
     *
     * @param id
     *         The ID.
     *
     * @param password
     *         The password.
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings setCredentials(String id, String password)
    {
        return setId(id).setPassword(password);
    }


    /**
     * Set the proxy server by a URI. See the description of
     * {@link #setServer(URI)} about how the parameters are updated.
     *
     * @param uri
     *         The URI of the proxy server. If {@code null} is given,
     *         none of the parameters are updated.
     *
     * @return
     *         {@code this} object.
     *
     * @throws IllegalArgumentException
     *         Failed to convert the given string to a {@link URI} instance.
     */
    public ProxySettings setServer(String uri)
    {
        if (uri == null)
        {
            return this;
        }

        return setServer(URI.create(uri));
    }


    /**
     * Set the proxy server by a URL. See the description of
     * {@link #setServer(URI)} about how the parameters are updated.
     *
     * @param url
     *         The URL of the proxy server. If {@code null} is given,
     *         none of the parameters are updated.
     *
     * @return
     *         {@code this} object.
     *
     * @throws IllegalArgumentException
     *         Failed to convert the given URL to a {@link URI} instance.
     */
    public ProxySettings setServer(URL url)
    {
        if (url == null)
        {
            return this;
        }

        try
        {
            return setServer(url.toURI());
        }
        catch (URISyntaxException e)
        {
            throw new IllegalArgumentException(e);
        }
    }


    /**
     * Set the proxy server by a URI. The parameters are updated as
     * described below.
     *
     * <blockquote>
     * <dl>
     *   <dt>Secure</dt>
     *   <dd><p>
     *     If the URI contains the scheme part and its value is
     *     either {@code "http"} or {@code "https"} (case-insensitive),
     *     the {@code secure} parameter is updated to {@code false}
     *     or to {@code true} accordingly. In other cases, the parameter
     *     is not updated.
     *   </p></dd>
     *   <dt>ID &amp; Password</dt>
     *   <dd><p>
     *     If the URI contains the userinfo part and the ID embedded
     *     in the userinfo part is not an empty string, the {@code
     *     id} parameter and the {@code password} parameter are updated
     *     accordingly. In other cases, the parameters are not updated.
     *   </p></dd>
     *   <dt>Host</dt>
     *   <dd><p>
     *     The {@code host} parameter is always updated by the given URI.
     *   </p></dd>
     *   <dt>Port</dt>
     *   <dd><p>
     *     The {@code port} parameter is always updated by the given URI.
     *   </p></dd>
     * </dl>
     * </blockquote>
     *
     * @param uri
     *         The URI of the proxy server. If {@code null} is given,
     *         none of the parameters is updated.
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings setServer(URI uri)
    {
        if (uri == null)
        {
            return this;
        }

        String scheme   = uri.getScheme();
        String userInfo = uri.getUserInfo();
        String host     = uri.getHost();
        int port        = uri.getPort();

        return setServer(scheme, userInfo, host, port);
    }


    private ProxySettings setServer(String scheme, String userInfo, String host, int port)
    {
        setByScheme(scheme);
        setByUserInfo(userInfo);
        mHost = host;
        mPort = port;

        return this;
    }


    private void setByScheme(String scheme)
    {
        if ("http".equalsIgnoreCase(scheme))
        {
            mSecure = false;
        }
        else if ("https".equalsIgnoreCase(scheme))
        {
            mSecure = true;
        }
    }


    private void setByUserInfo(String userInfo)
    {
        if (userInfo == null)
        {
            return;
        }

        String[] pair = userInfo.split(":", 2);
        String id;
        String pw;

        switch (pair.length)
        {
            case 2:
                id = pair[0];
                pw = pair[1];
                break;

            case 1:
                id = pair[0];
                pw = null;
                break;

            default:
                return;
        }

        if (id.length() == 0)
        {
            return;
        }

        mId       = id;
        mPassword = pw;
    }


    /**
     * Get additional HTTP headers passed to the proxy server.
     *
     * @return
     *         Additional HTTP headers passed to the proxy server.
     *         The comparator of the returned map is {@link
     *         String#CASE_INSENSITIVE_ORDER}.
     */
    public Map<String, List<String>> getHeaders()
    {
        return mHeaders;
    }


    /**
     * Add an additional HTTP header passed to the proxy server.
     *
     * @param name
     *         The name of an HTTP header (case-insensitive).
     *         If {@code null} or an empty string is given,
     *         nothing is added.
     *
     * @param value
     *         The value of the HTTP header.
     *
     * @return
     *         {@code this} object.
     */
    public ProxySettings addHeader(String name, String value)
    {
        if (name == null || name.length() == 0)
        {
            return this;
        }

        List<String> list = mHeaders.get(name);

        if (list == null)
        {
            list = new ArrayList<String>();
            mHeaders.put(name, list);
        }

        list.add(value);

        return this;
    }


    /**
     * Get the socket factory that has been set by {@link
     * #setSocketFactory(SocketFactory)}.
     *
     * @return
     *         The socket factory.
     */
    public SocketFactory getSocketFactory()
    {
        return mSocketFactorySettings.getSocketFactory();
    }


    /**
     * Set a socket factory.
     *
     * @param factory
     *         A socket factory.
     *
     * @return
     *         {@code this} instance.
     */
    public ProxySettings setSocketFactory(SocketFactory factory)
    {
        mSocketFactorySettings.setSocketFactory(factory);

        return this;
    }


    /**
     * Get the SSL socket factory that has been set by {@link
     * #setSSLSocketFactory(SSLSocketFactory)}.
     *
     * @return
     *         The SSL socket factory.
     */
    public SSLSocketFactory getSSLSocketFactory()
    {
        return mSocketFactorySettings.getSSLSocketFactory();
    }


    /**
     * Set an SSL socket factory.
     *
     * @param factory
     *         An SSL socket factory.
     *
     * @return
     *         {@code this} instance.
     */
    public ProxySettings setSSLSocketFactory(SSLSocketFactory factory)
    {
        mSocketFactorySettings.setSSLSocketFactory(factory);

        return this;
    }


    /**
     * Get the SSL context that has been set by {@link #setSSLContext(SSLContext)}.
     *
     * @return
     *         The SSL context.
     */
    public SSLContext getSSLContext()
    {
        return mSocketFactorySettings.getSSLContext();
    }


    /**
     * Set an SSL context to get a socket factory.
     *
     * @param context
     *         An SSL context.
     *
     * @return
     *         {@code this} instance.
     */
    public ProxySettings setSSLContext(SSLContext context)
    {
        mSocketFactorySettings.setSSLContext(context);

        return this;
    }


    SocketFactory selectSocketFactory()
    {
        return mSocketFactorySettings.selectSocketFactory(mSecure);
    }


    /**
     * Get server names for SNI (Server Name Indication).
     *
     * @return
     *         List of host names.
     *
     * @since 2.4
     */
    public String[] getServerNames()
    {
        return mServerNames;
    }


    /**
     * Set server names for SNI (Server Name Indication).
     *
     * If {@code setServerNames(List<SNIServerName>)} method of
     * {@link javax.net.ssl.SSLParameters SSLParameters} class is available
     * in the underlying system, the method is called to set up server names
     * for SNI (Server Name Indication).
     *
     * @param serverNames
     *         List of host names.
     *
     * @return
     *         {@code this} object.
     *
     * @since 2.4
     */
    public ProxySettings setServerNames(String[] serverNames)
    {
        mServerNames = serverNames;

        return this;
    }


    /**
     * Set a server name for SNI (Server Name Indication).
     *
     * This method internally creates a String array of size 1 which
     * contains the given {@code serverName} and calls {@link
     * #setServerNames(String[])}.
     *
     * @param serverName
     *         A host name.
     *
     * @return
     *         {@code this} object.
     *
     * @since 2.4
     */
    public ProxySettings setServerName(String serverName)
    {
        return setServerNames(new String[] { serverName });
    }
}