Skip to main content
summaryrefslogtreecommitdiffstats
blob: 44ab1479103e6dd47fd9efb43322710cf792680f (plain) (blame)
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
// ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================

package org.eclipse.jetty.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.ServletRequest;

import org.eclipse.jetty.http.HttpBuffers;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.http.HttpSchemes;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.statistic.SampleStatistic;
import org.eclipse.jetty.util.statistic.CounterStatistic;
import org.eclipse.jetty.util.thread.ThreadPool;

/**
 * Abstract Connector implementation. This abstract implementation of the
 * Connector interface provides:
 * <ul>
 * <li>AbstractLifeCycle implementation</li>
 * <li>Implementations for connector getters and setters</li>
 * <li>Buffer management</li>
 * <li>Socket configuration</li>
 * <li>Base acceptor thread</li>
 * <li>Optional reverse proxy headers checking</li>
 * </ul>
 * 
 * 
 */
public abstract class AbstractConnector extends HttpBuffers implements Connector
{
    private String _name;

    private Server _server;
    private ThreadPool _threadPool;
    private String _host;
    private int _port = 0;
    private String _integralScheme = HttpSchemes.HTTPS;
    private int _integralPort = 0;
    private String _confidentialScheme = HttpSchemes.HTTPS;
    private int _confidentialPort = 0;
    private int _acceptQueueSize = 0;
    private int _acceptors = 1;
    private int _acceptorPriorityOffset = 0;
    private boolean _useDNS;
    private boolean _forwarded;
    private String _hostHeader;
    private String _forwardedHostHeader = "X-Forwarded-Host"; // default to
                                                              // mod_proxy_http
                                                              // header
    private String _forwardedServerHeader = "X-Forwarded-Server"; // default to
                                                                  // mod_proxy_http
                                                                  // header
    private String _forwardedForHeader = "X-Forwarded-For"; // default to
                                                            // mod_proxy_http
                                                            // header
    private boolean _reuseAddress = true;

    protected int _maxIdleTime = 200000;
    protected int _lowResourceMaxIdleTime = -1;
    protected int _soLingerTime = -1;

    private transient Thread[] _acceptorThread;

    private final AtomicLong _statsStartedAt = new AtomicLong(-1L);

    private final CounterStatistic _connectionStats = new CounterStatistic(); // connections
                                                                              // to
                                                                              // server
    private final SampleStatistic _requestStats = new SampleStatistic(); // requests
                                                                                 // per
                                                                                 // connection
    private final SampleStatistic _connectionDurationStats = new SampleStatistic(); // duration
                                                                                            // of
                                                                                            // a
                                                                                            // connection

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    /**
     */
    public AbstractConnector()
    {
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    public final Buffer newBuffer(int size)
    {
        // TODO remove once no overrides established
        return null;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    @Override
    public Buffer newRequestBuffer(int size)
    {
        return new ByteArrayBuffer(size);
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    @Override
    public Buffer newRequestHeader(int size)
    {
        return new ByteArrayBuffer(size);
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    @Override
    public Buffer newResponseBuffer(int size)
    {
        return new ByteArrayBuffer(size);
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    @Override
    public Buffer newResponseHeader(int size)
    {
        return new ByteArrayBuffer(size);
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    @Override
    protected boolean isRequestHeader(Buffer buffer)
    {
        return true;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    @Override
    protected boolean isResponseHeader(Buffer buffer)
    {
        return true;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    /*
     */
    public Server getServer()
    {
        return _server;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    public void setServer(Server server)
    {
        _server = server;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    /*
     * @see org.eclipse.jetty.http.HttpListener#getHttpServer()
     */
    public ThreadPool getThreadPool()
    {
        return _threadPool;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    public void setThreadPool(ThreadPool pool)
    {
        _threadPool = pool;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    /**
     */
    public void setHost(String host)
    {
        _host = host;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    /*
     */
    public String getHost()
    {
        return _host;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    /*
     * @see org.eclipse.jetty.server.server.HttpListener#setPort(int)
     */
    public void setPort(int port)
    {
        _port = port;
    }

    /*
     * --------------------------------------------------------------------------
     * -----
     */
    /*
     * @see org.eclipse.jetty.server.server.HttpListener#getPort()
     */
    public int getPort()
    {
        return _port;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the maxIdleTime.
     */
    public int getMaxIdleTime()
    {
        return _maxIdleTime;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the maximum Idle time for a connection, which roughly translates to
     * the {@link Socket#setSoTimeout(int)} call, although with NIO
     * implementations other mechanisms may be used to implement the timeout.
     * The max idle time is applied:
     * <ul>
     * <li>When waiting for a new request to be received on a connection</li>
     * <li>When reading the headers and content of a request</li>
     * <li>When writing the headers and content of a response</li>
     * </ul>
     * Jetty interprets this value as the maximum time between some progress
     * being made on the connection. So if a single byte is read or written,
     * then the timeout (if implemented by jetty) is reset. However, in many
     * instances, the reading/writing is delegated to the JVM, and the semantic
     * is more strictly enforced as the maximum time a single read/write
     * operation can take. Note, that as Jetty supports writes of memory mapped
     * file buffers, then a write may take many 10s of seconds for large content
     * written to a slow device.
     * <p>
     * Previously, Jetty supported separate idle timeouts and IO operation
     * timeouts, however the expense of changing the value of soTimeout was
     * significant, so these timeouts were merged. With the advent of NIO, it
     * may be possible to again differentiate these values (if there is demand).
     * 
     * @param maxIdleTime
     *            The maxIdleTime to set.
     */
    public void setMaxIdleTime(int maxIdleTime)
    {
        _maxIdleTime = maxIdleTime;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the maxIdleTime when resources are low.
     */
    public int getLowResourcesMaxIdleTime()
    {
        return _lowResourceMaxIdleTime;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param maxIdleTime
     *            The maxIdleTime to set when resources are low.
     */
    public void setLowResourcesMaxIdleTime(int maxIdleTime)
    {
        _lowResourceMaxIdleTime = maxIdleTime;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the maxIdleTime when resources are low.
     * @deprecated
     */
    public final int getLowResourceMaxIdleTime()
    {
        return getLowResourcesMaxIdleTime();
    }

    /* ------------------------------------------------------------ */
    /**
     * @param maxIdleTime
     *            The maxIdleTime to set when resources are low.
     * @deprecated
     */
    public final void setLowResourceMaxIdleTime(int maxIdleTime)
    {
        setLowResourcesMaxIdleTime(maxIdleTime);
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the soLingerTime.
     */
    public int getSoLingerTime()
    {
        return _soLingerTime;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the acceptQueueSize.
     */
    public int getAcceptQueueSize()
    {
        return _acceptQueueSize;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param acceptQueueSize
     *            The acceptQueueSize to set.
     */
    public void setAcceptQueueSize(int acceptQueueSize)
    {
        _acceptQueueSize = acceptQueueSize;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the number of acceptor threads.
     */
    public int getAcceptors()
    {
        return _acceptors;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param acceptors
     *            The number of acceptor threads to set.
     */
    public void setAcceptors(int acceptors)
    {
        _acceptors = acceptors;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param soLingerTime
     *            The soLingerTime to set or -1 to disable.
     */
    public void setSoLingerTime(int soLingerTime)
    {
        _soLingerTime = soLingerTime;
    }

    /* ------------------------------------------------------------ */
    @Override
    protected void doStart() throws Exception
    {
        if (_server == null)
            throw new IllegalStateException("No server");

        // open listener port
        open();

        super.doStart();

        if (_threadPool == null)
            _threadPool = _server.getThreadPool();
        if (_threadPool != _server.getThreadPool() && (_threadPool instanceof LifeCycle))
            ((LifeCycle)_threadPool).start();

        // Start selector thread
        synchronized (this)
        {
            _acceptorThread = new Thread[getAcceptors()];

            for (int i = 0; i < _acceptorThread.length; i++)
            {
                if (!_threadPool.dispatch(new Acceptor(i)))
                {
                    Log.warn("insufficient maxThreads configured for {}",this);
                    break;
                }
            }
        }

        Log.info("Started {}",this);
    }

    /* ------------------------------------------------------------ */
    @Override
    protected void doStop() throws Exception
    {
        try
        {
            close();
        }
        catch (IOException e)
        {
            Log.warn(e);
        }

        if (_threadPool != _server.getThreadPool() && _threadPool instanceof LifeCycle)
            ((LifeCycle)_threadPool).stop();

        super.doStop();

        Thread[] acceptors = null;
        synchronized (this)
        {
            acceptors = _acceptorThread;
            _acceptorThread = null;
        }
        if (acceptors != null)
        {
            for (int i = 0; i < acceptors.length; i++)
            {
                Thread thread = acceptors[i];
                if (thread != null)
                    thread.interrupt();
            }
        }
    }

    /* ------------------------------------------------------------ */
    public void join() throws InterruptedException
    {
        Thread[] threads = _acceptorThread;
        if (threads != null)
            for (int i = 0; i < threads.length; i++)
                if (threads[i] != null)
                    threads[i].join();
    }

    /* ------------------------------------------------------------ */
    protected void configure(Socket socket) throws IOException
    {
        try
        {
            socket.setTcpNoDelay(true);
            if (_maxIdleTime >= 0)
                socket.setSoTimeout(_maxIdleTime);
            if (_soLingerTime >= 0)
                socket.setSoLinger(true,_soLingerTime / 1000);
            else
                socket.setSoLinger(false,0);
        }
        catch (Exception e)
        {
            Log.ignore(e);
        }
    }

    /* ------------------------------------------------------------ */
    public void customize(EndPoint endpoint, Request request) throws IOException
    {
        if (isForwarded())
            checkForwardedHeaders(endpoint,request);
    }

    /* ------------------------------------------------------------ */
    protected void checkForwardedHeaders(EndPoint endpoint, Request request) throws IOException
    {
        HttpFields httpFields = request.getConnection().getRequestFields();

        // Retrieving headers from the request
        String forwardedHost = getLeftMostValue(httpFields.getStringField(getForwardedHostHeader()));
        String forwardedServer = getLeftMostValue(httpFields.getStringField(getForwardedServerHeader()));
        String forwardedFor = getLeftMostValue(httpFields.getStringField(getForwardedForHeader()));

        if (_hostHeader != null)
        {
            // Update host header
            httpFields.put(HttpHeaders.HOST_BUFFER,_hostHeader);
            request.setServerName(null);
            request.setServerPort(-1);
            request.getServerName();
        }
        else if (forwardedHost != null)
        {
            // Update host header
            httpFields.put(HttpHeaders.HOST_BUFFER,forwardedHost);
            request.setServerName(null);
            request.setServerPort(-1);
            request.getServerName();
        }
        else if (forwardedServer != null)
        {
            // Use provided server name
            request.setServerName(forwardedServer);
        }

        if (forwardedFor != null)
        {
            request.setRemoteAddr(forwardedFor);
            InetAddress inetAddress = null;

            if (_useDNS)
            {
                try
                {
                    inetAddress = InetAddress.getByName(forwardedFor);
                }
                catch (UnknownHostException e)
                {
                    Log.ignore(e);
                }
            }

            request.setRemoteHost(inetAddress == null?forwardedFor:inetAddress.getHostName());
        }
    }

    /* ------------------------------------------------------------ */
    protected String getLeftMostValue(String headerValue)
    {
        if (headerValue == null)
            return null;

        int commaIndex = headerValue.indexOf(',');

        if (commaIndex == -1)
        {
            // Single value
            return headerValue;
        }

        // The left-most value is the farthest downstream client
        return headerValue.substring(0,commaIndex);
    }

    /* ------------------------------------------------------------ */
    public void persist(EndPoint endpoint) throws IOException
    {
    }

    /* ------------------------------------------------------------ */
    /*
     * @see org.eclipse.jetty.server.Connector#getConfidentialPort()
     */
    public int getConfidentialPort()
    {
        return _confidentialPort;
    }

    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    /*
     * @see org.eclipse.jetty.server.Connector#getConfidentialScheme()
     */
    public String getConfidentialScheme()
    {
        return _confidentialScheme;
    }

    /* ------------------------------------------------------------ */
    /*
     * @see
     * org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server
     * .Request)
     */
    public boolean isIntegral(Request request)
    {
        return false;
    }

    /* ------------------------------------------------------------ */
    /*
     * @see org.eclipse.jetty.server.Connector#getConfidentialPort()
     */
    public int getIntegralPort()
    {
        return _integralPort;
    }

    /* ------------------------------------------------------------ */
    /*
     * @see org.eclipse.jetty.server.Connector#getIntegralScheme()
     */
    public String getIntegralScheme()
    {
        return _integralScheme;
    }

    /* ------------------------------------------------------------ */
    /*
     * @see
     * org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server
     * .Request)
     */
    public boolean isConfidential(Request request)
    {
        return false;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param confidentialPort
     *            The confidentialPort to set.
     */
    public void setConfidentialPort(int confidentialPort)
    {
        _confidentialPort = confidentialPort;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param confidentialScheme
     *            The confidentialScheme to set.
     */
    public void setConfidentialScheme(String confidentialScheme)
    {
        _confidentialScheme = confidentialScheme;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param integralPort
     *            The integralPort to set.
     */
    public void setIntegralPort(int integralPort)
    {
        _integralPort = integralPort;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param integralScheme
     *            The integralScheme to set.
     */
    public void setIntegralScheme(String integralScheme)
    {
        _integralScheme = integralScheme;
    }

    /* ------------------------------------------------------------ */
    protected abstract void accept(int acceptorID) throws IOException, InterruptedException;

    /* ------------------------------------------------------------ */
    public void stopAccept(int acceptorID) throws Exception
    {
    }

    /* ------------------------------------------------------------ */
    public boolean getResolveNames()
    {
        return _useDNS;
    }

    /* ------------------------------------------------------------ */
    public void setResolveNames(boolean resolve)
    {
        _useDNS = resolve;
    }

    /* ------------------------------------------------------------ */
    /**
     * Is reverse proxy handling on?
     * 
     * @return true if this connector is checking the
     *         x-forwarded-for/host/server headers
     */
    public boolean isForwarded()
    {
        return _forwarded;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set reverse proxy handling
     * 
     * @param check
     *            true if this connector is checking the
     *            x-forwarded-for/host/server headers
     */
    public void setForwarded(boolean check)
    {
        if (check)
            Log.debug(this + " is forwarded");
        _forwarded = check;
    }

    /* ------------------------------------------------------------ */
    public String getHostHeader()
    {
        return _hostHeader;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set a forced valued for the host header to control what is returned by
     * {@link ServletRequest#getServerName()} and
     * {@link ServletRequest#getServerPort()}. This value is only used if
     * {@link #isForwarded()} is true.
     * 
     * @param hostHeader
     *            The value of the host header to force.
     */
    public void setHostHeader(String hostHeader)
    {
        _hostHeader = hostHeader;
    }

    /* ------------------------------------------------------------ */
    public String getForwardedHostHeader()
    {
        return _forwardedHostHeader;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param forwardedHostHeader
     *            The header name for forwarded hosts (default x-forwarded-host)
     */
    public void setForwardedHostHeader(String forwardedHostHeader)
    {
        _forwardedHostHeader = forwardedHostHeader;
    }

    /* ------------------------------------------------------------ */
    public String getForwardedServerHeader()
    {
        return _forwardedServerHeader;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param forwardedServerHeader
     *            The header name for forwarded server (default
     *            x-forwarded-server)
     */
    public void setForwardedServerHeader(String forwardedServerHeader)
    {
        _forwardedServerHeader = forwardedServerHeader;
    }

    /* ------------------------------------------------------------ */
    public String getForwardedForHeader()
    {
        return _forwardedForHeader;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param forwardedRemoteAddressHeader
     *            The header name for forwarded for (default x-forwarded-for)
     */
    public void setForwardedForHeader(String forwardedRemoteAddressHeader)
    {
        _forwardedForHeader = forwardedRemoteAddressHeader;
    }

    /* ------------------------------------------------------------ */
    @Override
    public String toString()
    {
        String name = this.getClass().getName();
        int dot = name.lastIndexOf('.');
        if (dot > 0)
            name = name.substring(dot + 1);

        return name + "@" + (getHost() == null?"0.0.0.0":getHost()) + ":" + (getLocalPort() <= 0?getPort():getLocalPort());
    }

    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    private class Acceptor implements Runnable
    {
        int _acceptor = 0;

        Acceptor(int id)
        {
            _acceptor = id;
        }

        /* ------------------------------------------------------------ */
        public void run()
        {
            Thread current = Thread.currentThread();
            String name;
            synchronized (AbstractConnector.this)
            {
                if (_acceptorThread == null)
                    return;

                _acceptorThread[_acceptor] = current;
                name = _acceptorThread[_acceptor].getName();
                current.setName(name + " - Acceptor" + _acceptor + " " + AbstractConnector.this);
            }
            int old_priority = current.getPriority();

            try
            {
                current.setPriority(old_priority - _acceptorPriorityOffset);
                while (isRunning() && getConnection() != null)
                {
                    try
                    {
                        accept(_acceptor);
                    }
                    catch (EofException e)
                    {
                        Log.ignore(e);
                    }
                    catch (IOException e)
                    {
                        Log.ignore(e);
                    }
                    catch (InterruptedException x)
                    {
                        // Connector has been stopped
                        Log.ignore(x);
                    }
                    catch (ThreadDeath e)
                    {
                        throw e;
                    }
                    catch (Throwable e)
                    {
                        Log.warn(e);
                    }
                }
            }
            finally
            {
                current.setPriority(old_priority);
                current.setName(name);
                try
                {
                    if (_acceptor == 0)
                        close();
                }
                catch (IOException e)
                {
                    Log.warn(e);
                }

                synchronized (AbstractConnector.this)
                {
                    if (_acceptorThread != null)
                        _acceptorThread[_acceptor] = null;
                }
            }
        }
    }

    /* ------------------------------------------------------------ */
    public String getName()
    {
        if (_name == null)
            _name = (getHost() == null?"0.0.0.0":getHost()) + ":" + (getLocalPort() <= 0?getPort():getLocalPort());
        return _name;
    }

    /* ------------------------------------------------------------ */
    public void setName(String name)
    {
        _name = name;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Get the number of requests handled by this connector since last
     *         call of statsReset(). If setStatsOn(false) then this is
     *         undefined.
     */
    public int getRequests()
    {
        return (int)_requestStats.getTotal();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the connectionsDurationTotal.
     */
    public long getConnectionsDurationTotal()
    {
        return _connectionDurationStats.getTotal();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Number of connections accepted by the server since statsReset()
     *         called. Undefined if setStatsOn(false).
     */
    public int getConnections()
    {
        return (int)_connectionStats.getTotal();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Number of connections currently open that were opened since
     *         statsReset() called. Undefined if setStatsOn(false).
     */
    public int getConnectionsOpen()
    {
        return (int)_connectionStats.getCurrent();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Maximum number of connections opened simultaneously since
     *         statsReset() called. Undefined if setStatsOn(false).
     */
    public int getConnectionsOpenMax()
    {
        return (int)_connectionStats.getMax();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Mean duration in milliseconds of open connections since
     *         statsReset() called. Undefined if setStatsOn(false).
     */
    public double getConnectionsDurationMean()
    {
        return _connectionDurationStats.getMean();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Maximum duration in milliseconds of an open connection since
     *         statsReset() called. Undefined if setStatsOn(false).
     */
    public long getConnectionsDurationMax()
    {
        return _connectionDurationStats.getMax();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Standard deviation of duration in milliseconds of open
     *         connections since statsReset() called. Undefined if
     *         setStatsOn(false).
     */
    public double getConnectionsDurationStdDev()
    {
        return _connectionDurationStats.getStdDev();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Mean number of requests per connection since statsReset() called.
     *         Undefined if setStatsOn(false).
     */
    public double getConnectionsRequestsMean()
    {
        return _requestStats.getMean();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Maximum number of requests per connection since statsReset()
     *         called. Undefined if setStatsOn(false).
     */
    public int getConnectionsRequestsMax()
    {
        return (int)_requestStats.getMax();
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Standard deviation of number of requests per connection since
     *         statsReset() called. Undefined if setStatsOn(false).
     */
    public double getConnectionsRequestsStdDev()
    {
        return _requestStats.getStdDev();
    }

    /* ------------------------------------------------------------ */
    /**
     * Reset statistics.
     */
    public void statsReset()
    {
        updateNotEqual(_statsStartedAt,-1,System.currentTimeMillis());

        _requestStats.reset();
        _connectionStats.reset();
        _connectionDurationStats.reset();
    }

    /* ------------------------------------------------------------ */
    public void setStatsOn(boolean on)
    {
        if (on && _statsStartedAt.get() != -1)
            return;

        Log.debug("Statistics on = " + on + " for " + this);

        statsReset();
        _statsStartedAt.set(on?System.currentTimeMillis():-1);
    }

    /* ------------------------------------------------------------ */
    /**
     * @return True if statistics collection is turned on.
     */
    public boolean getStatsOn()
    {
        return _statsStartedAt.get() != -1;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Timestamp stats were started at.
     */
    public long getStatsOnMs()
    {
        long start = _statsStartedAt.get();

        return (start != -1)?(System.currentTimeMillis() - start):0;
    }

    /* ------------------------------------------------------------ */
    protected void connectionOpened(Connection connection)
    {
        if (_statsStartedAt.get() == -1)
            return;

        _connectionStats.increment();
    }

    /* ------------------------------------------------------------ */
    protected void connectionUpgraded(Connection oldConnection, Connection newConnection)
    {
        _requestStats.set((oldConnection instanceof HttpConnection)?((HttpConnection)oldConnection).getRequests():0);
    }

    /* ------------------------------------------------------------ */
    protected void connectionClosed(Connection connection)
    {
        if (_statsStartedAt.get() == -1)
            return;

        long duration = System.currentTimeMillis() - connection.getTimeStamp();
        int requests = (connection instanceof HttpConnection)?((HttpConnection)connection).getRequests():0;

        _requestStats.set(requests);
        _connectionStats.decrement();
        _connectionDurationStats.set(duration);
    }

    /* ------------------------------------------------------------ */
    /**
     * @return the acceptorPriority
     */
    public int getAcceptorPriorityOffset()
    {
        return _acceptorPriorityOffset;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the priority offset of the acceptor threads. The priority is adjusted
     * by this amount (default 0) to either favour the acceptance of new threads
     * and newly active connections or to favour the handling of already
     * dispatched connections.
     * 
     * @param offset
     *            the amount to alter the priority of the acceptor threads.
     */
    public void setAcceptorPriorityOffset(int offset)
    {
        _acceptorPriorityOffset = offset;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return True if the the server socket will be opened in SO_REUSEADDR
     *         mode.
     */
    public boolean getReuseAddress()
    {
        return _reuseAddress;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param reuseAddress
     *            True if the the server socket will be opened in SO_REUSEADDR
     *            mode.
     */
    public void setReuseAddress(boolean reuseAddress)
    {
        _reuseAddress = reuseAddress;
    }

    /* ------------------------------------------------------------ */
    public boolean isLowResources()
    {
        if (_threadPool != null)
            return _threadPool.isLowOnThreads();
        return _server.getThreadPool().isLowOnThreads();
    }

    /* ------------------------------------------------------------ */
    private void updateNotEqual(AtomicLong valueHolder, long compare, long value)
    {
        long oldValue = valueHolder.get();
        while (compare != oldValue)
        {
            if (valueHolder.compareAndSet(oldValue,value))
                break;
            oldValue = valueHolder.get();
        }
    }
}

Back to the top