File: IpMap.cc

package info (click to toggle)
trafficserver 6.2.0-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 45,456 kB
  • sloc: cpp: 271,894; ansic: 80,740; sh: 6,032; makefile: 3,364; python: 2,135; perl: 2,040; java: 277; lex: 128; sql: 94; yacc: 68; sed: 8
file content (1223 lines) | stat: -rw-r--r-- 33,823 bytes parent folder | download | duplicates (2)
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
#include "ts/IpMap.h"

/** @file
    IP address map support.

    Provide the ability to create a range based mapping for the IP
    address space. Addresses can be added and removed and each address
    is associated with arbitrary client data.

    @internal Don't bother to look at this code if you don't know how
    a red/black tree works. There are so many good references on the
    subject it's a waste to have some inferior version here. The
    methods on @c Node follow the standard implementation except for
    being parameterized by direction (so that, for instance, right
    rotate and left rotate are both done by the @c rotate method with
    a direction argument).

    @section license License

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
 */

// Validation / printing disabled until I figure out how to generalize so
// as to not tie reporting into a particular project environment.

/* @internal It is a bit ugly to store a @c sockaddr equivalent in the table
    as all that is actually needed is the raw address. Unfortunately some clients
    require a @c sockaddr* return via the iterator and that's expensive to
    compute all the time. I should, at some point, re-examine this and see if we
    can do better and have a more compact internal format. I suspect I did this
    before we had IpAddr as a type.
*/

namespace ts
{
namespace detail
{
  // Helper functions

  inline int
  cmp(sockaddr_in6 const &lhs, sockaddr_in6 const &rhs)
  {
    return memcmp(lhs.sin6_addr.s6_addr, rhs.sin6_addr.s6_addr, TS_IP6_SIZE);
  }

  /// Less than.
  inline bool
  operator<(sockaddr_in6 const &lhs, sockaddr_in6 const &rhs)
  {
    return ts::detail::cmp(lhs, rhs) < 0;
  }
  inline bool
  operator<(sockaddr_in6 const *lhs, sockaddr_in6 const &rhs)
  {
    return ts::detail::cmp(*lhs, rhs) < 0;
  }
  /// Less than.
  inline bool
  operator<(sockaddr_in6 const &lhs, sockaddr_in6 const *rhs)
  {
    return ts::detail::cmp(lhs, *rhs) < 0;
  }
  /// Equality.
  inline bool
  operator==(sockaddr_in6 const &lhs, sockaddr_in6 const *rhs)
  {
    return ts::detail::cmp(lhs, *rhs) == 0;
  }
  /// Equality.
  inline bool
  operator==(sockaddr_in6 const *lhs, sockaddr_in6 const &rhs)
  {
    return ts::detail::cmp(*lhs, rhs) == 0;
  }
  /// Equality.
  inline bool
  operator==(sockaddr_in6 const &lhs, sockaddr_in6 const &rhs)
  {
    return ts::detail::cmp(lhs, rhs) == 0;
  }
  /// Less than or equal.
  inline bool
  operator<=(sockaddr_in6 const &lhs, sockaddr_in6 const *rhs)
  {
    return ts::detail::cmp(lhs, *rhs) <= 0;
  }
  /// Less than or equal.
  inline bool
  operator<=(sockaddr_in6 const &lhs, sockaddr_in6 const &rhs)
  {
    return ts::detail::cmp(lhs, rhs) <= 0;
  }
  /// Greater than or equal.
  inline bool
  operator>=(sockaddr_in6 const &lhs, sockaddr_in6 const &rhs)
  {
    return ts::detail::cmp(lhs, rhs) >= 0;
  }
  /// Greater than or equal.
  inline bool
  operator>=(sockaddr_in6 const &lhs, sockaddr_in6 const *rhs)
  {
    return ts::detail::cmp(lhs, *rhs) >= 0;
  }
  /// Greater than.
  inline bool
  operator>(sockaddr_in6 const &lhs, sockaddr_in6 const *rhs)
  {
    return ts::detail::cmp(lhs, *rhs) > 0;
  }

  /** Base template class for IP maps.
      This class is templated by the @a N type which must be a subclass
      of @c RBNode. This class carries information about the addresses stored
      in the map. This includes the type, the common argument type, and
      some utility methods to operate on the address.
  */
  template <typename N ///< Node type.
            >
  struct IpMapBase {
    friend class ::IpMap;

    typedef IpMapBase self;              ///< Self reference type.
    typedef typename N::ArgType ArgType; ///< Import type.
    typedef typename N::Metric Metric;   ///< Import type.g482

    IpMapBase() : _root(0) {}
    ~IpMapBase() { this->clear(); }
    /** Mark a range.
        All addresses in the range [ @a min , @a max ] are marked with @a data.
        @return This object.
    */
    self &mark(ArgType min,   ///< Minimum value in range.
               ArgType max,   ///< Maximum value in range.
               void *data = 0 ///< Client data payload.
               );
    /** Unmark addresses.

        All addresses in the range [ @a min , @a max ] are cleared
        (removed from the map), no longer marked.

        @return This object.
    */
    self &unmark(ArgType min, ArgType max);

    /** Fill addresses.

        This background fills using the range. All addresses in the
        range that are @b not present in the map are added. No
        previously present address is changed.

        @note This is useful for filling in first match tables.

        @return This object.
    */
    self &fill(ArgType min, ArgType max, void *data = 0);

    /** Test for membership.

        @return @c true if the address is in the map, @c false if not.
        If the address is in the map and @a ptr is not @c NULL, @c *ptr
        is set to the client data for the address.
    */
    bool contains(ArgType target, ///< Search target value.
                  void **ptr = 0  ///< Client data return.
                  ) const;

    /** Remove all addresses in the map.

        @note This is much faster than using @c unmark with a range of
        all addresses.

        @return This object.
    */
    self &clear();

    /** Lower bound for @a target.  @return The node whose minimum value
        is the largest that is not greater than @a target, or @c NULL if
        all minimum values are larger than @a target.
    */
    N *lowerBound(ArgType target);

    /** Insert @a n after @a spot.
        Caller is responsible for ensuring that @a spot is in this container
        and the proper location for @a n.
    */
    void insertAfter(N *spot, ///< Node in list.
                     N *n     ///< Node to insert.
                     );
    /** Insert @a n before @a spot.
        Caller is responsible for ensuring that @a spot is in this container
        and the proper location for @a n.
    */
    void insertBefore(N *spot, ///< Node in list.
                      N *n     ///< Node to insert.
                      );
    /// Add node @a n as the first node.
    void prepend(N *n);
    /// Add node @a n as the last node.
    void append(N *n);
    /// Remove a node.
    void remove(N *n ///< Node to remove.
                );

    /** Validate internal data structures.
        @note Intended for debugging, not general client use.
    */
    void validate();

    /// @return The number of distinct ranges.
    size_t getCount() const;

    /// Print all spans.
    /// @return This map.
    self &print();

    // Helper methods.
    N *
    prev(RBNode *n) const
    {
      return static_cast<N *>(n->_prev);
    }
    N *
    next(RBNode *n) const
    {
      return static_cast<N *>(n->_next);
    }
    N *
    parent(RBNode *n) const
    {
      return static_cast<N *>(n->_parent);
    }
    N *
    left(RBNode *n) const
    {
      return static_cast<N *>(n->_left);
    }
    N *
    right(RBNode *n) const
    {
      return static_cast<N *>(n->_right);
    }
    N *
    getHead()
    {
      return static_cast<N *>(_list.getHead());
    }
    N *
    getTail()
    {
      return static_cast<N *>(_list.getTail());
    }

    N *_root; ///< Root node.
    /// In order list of nodes.
    /// For ugly compiler reasons, this is a list of base class pointers
    /// even though we really store @a N instances on it.
    typedef IntrusiveDList<RBNode, &RBNode::_next, &RBNode::_prev> NodeList;
    /// This keeps track of all allocated nodes in order.
    /// Iteration depends on this list being maintained.
    NodeList _list;
  };

  template <typename N>
  N *
  IpMapBase<N>::lowerBound(ArgType target)
  {
    N *n    = _root; // current node to test.
    N *zret = 0;     // best node so far.
    while (n) {
      if (target < n->_min)
        n = left(n);
      else {
        zret = n; // this is a better candidate.
        if (n->_max < target)
          n = right(n);
        else
          break;
      }
    }
    return zret;
  }

  template <typename N>
  IpMapBase<N> &
  IpMapBase<N>::clear()
  {
    // Delete everything.
    N *n = static_cast<N *>(_list.getHead());
    while (n) {
      N *x = n;
      n    = next(n);
      delete x;
    }
    _list.clear();
    _root = 0;
    return *this;
  }

  template <typename N>
  IpMapBase<N> &
  IpMapBase<N>::fill(ArgType rmin, ArgType rmax, void *payload)
  {
    // Rightmost node of interest with n->_min <= min.
    N *n = this->lowerBound(rmin);
    N *x = 0; // New node (if any).
    // Need copies because we will modify these.
    Metric min = N::deref(rmin);
    Metric max = N::deref(rmax);

    // Handle cases involving a node of interest to the left of the
    // range.
    if (n) {
      if (n->_min < min) {
        Metric min_1 = min;
        N::dec(min_1);         // dec is OK because min isn't zero.
        if (n->_max < min_1) { // no overlap or adj.
          n = next(n);
        } else if (n->_max >= max) { // incoming range is covered, just discard.
          return *this;
        } else if (n->_data != payload) { // different payload, clip range on left.
          min = n->_max;
          N::inc(min);
          n = next(n);
        } else { // skew overlap with same payload, use node and continue.
          x = n;
          n = next(n);
        }
      }
    } else {
      n = this->getHead();
    }

    // Work through the rest of the nodes of interest.
    // Invariant: n->_min >= min

    // Careful here -- because max_plus1 might wrap we need to use it only
    // if we can certain it didn't. This is done by ordering the range
    // tests so that when max_plus1 is used when we know there exists a
    // larger value than max.
    Metric max_plus1 = max;
    N::inc(max_plus1);
    /* Notes:
       - max (and thence max_plus1) never change during the loop.
       - we must have either x != 0 or adjust min but not both.
    */
    while (n) {
      if (n->_data == payload) {
        if (x) {
          if (n->_max <= max) {
            // next range is covered, so we can remove and continue.
            this->remove(n);
            n = next(x);
          } else if (n->_min <= max_plus1) {
            // Overlap or adjacent with larger max - absorb and finish.
            x->setMax(n->_max);
            this->remove(n);
            return *this;
          } else {
            // have the space to finish off the range.
            x->setMax(max);
            return *this;
          }
        } else {                // not carrying a span.
          if (n->_max <= max) { // next range is covered - use it.
            x = n;
            x->setMin(min);
            n = next(n);
          } else if (n->_min <= max_plus1) {
            n->setMin(min);
            return *this;
          } else { // no overlap, space to complete range.
            this->insertBefore(n, new N(min, max, payload));
            return *this;
          }
        }
      } else { // different payload
        if (x) {
          if (max < n->_min) { // range ends before n starts, done.
            x->setMax(max);
            return *this;
          } else if (max <= n->_max) { // range ends before n, done.
            x->setMaxMinusOne(n->_min);
            return *this;
          } else { // n is contained in range, skip over it.
            x->setMaxMinusOne(n->_min);
            x   = 0;
            min = n->_max;
            N::inc(min); // OK because n->_max maximal => next is null.
            n = next(n);
          }
        } else {               // no carry node.
          if (max < n->_min) { // entirely before next span.
            this->insertBefore(n, new N(min, max, payload));
            return *this;
          } else {
            if (min < n->_min) { // leading section, need node.
              N *y = new N(min, n->_min, payload);
              y->decrementMax();
              this->insertBefore(n, y);
            }
            if (max <= n->_max) // nothing past node
              return *this;
            min = n->_max;
            N::inc(min);
            n = next(n);
          }
        }
      }
    }
    // Invariant: min is larger than any existing range maximum.
    if (x) {
      x->setMax(max);
    } else {
      this->append(new N(min, max, payload));
    }
    return *this;
  }

  template <typename N>
  IpMapBase<N> &
  IpMapBase<N>::mark(ArgType min, ArgType max, void *payload)
  {
    N *n = this->lowerBound(min); // current node.
    N *x = 0;                     // New node, gets set if we re-use an existing one.
    N *y = 0;                     // Temporary for removing and advancing.

    // Several places it is handy to have max+1. Must be careful
    // about wrapping.
    Metric max_plus = N::deref(max);
    N::inc(max_plus);

    /* Some subtlety - for IPv6 we overload the compare operators to do
       the right thing, but we can't overload pointer
       comparisons. Therefore we carefully never compare pointers in
       this logic. Only @a min and @a max can be pointers, everything
       else is an instance or a reference. Since there's no good reason
       to compare @a min and @a max this isn't particularly tricky, but
       it's good to keep in mind. If we were somewhat more clever, we
       would provide static less than and equal operators in the
       template class @a N and convert all the comparisons to use only
       those two via static function call.
    */

    /*  We have lots of special cases here primarily to minimize memory
        allocation by re-using an existing node as often as possible.
    */
    if (n) {
      // Watch for wrap.
      Metric min_1 = N::deref(min);
      N::dec(min_1);
      if (n->_min == min) {
        // Could be another span further left which is adjacent.
        // Coalesce if the data is the same. min_1 is OK because
        // if there is a previous range, min is not zero.
        N *p = prev(n);
        if (p && p->_data == payload && p->_max == min_1) {
          x = p;
          n = x; // need to back up n because frame of reference moved.
          x->setMax(max);
        } else if (n->_max <= max) {
          // Span will be subsumed by request span so it's available for use.
          x = n;
          x->setMax(max).setData(payload);
        } else if (n->_data == payload) {
          return *this; // request is covered by existing span with the same data
        } else {
          // request span is covered by existing span.
          x = new N(min, max, payload); //
          n->setMin(max_plus);          // clip existing.
          this->insertBefore(n, x);
          return *this;
        }
      } else if (n->_data == payload && n->_max >= min_1) {
        // min_1 is safe here because n->_min < min so min is not zero.
        x = n;
        // If the existing span covers the requested span, we're done.
        if (x->_max >= max)
          return *this;
        x->setMax(max);
      } else if (n->_max <= max) {
        // Can only have left skew overlap, otherwise disjoint.
        // Clip if overlap.
        if (n->_max >= min)
          n->setMax(min_1);
        else if (next(n) && n->_max <= max) {
          // request region covers next span so we can re-use that node.
          x = next(n);
          x->setMin(min).setMax(max).setData(payload);
          n = x; // this gets bumped again, which is correct.
        }
      } else {
        // Existing span covers new span but with a different payload.
        // We split it, put the new span in between and we're done.
        // max_plus is valid because n->_max > max.
        N *r;
        x = new N(min, max, payload);
        r = new N(max_plus, n->_max, n->_data);
        n->setMax(min_1);
        this->insertAfter(n, x);
        this->insertAfter(x, r);
        return *this; // done.
      }
      n = next(n); // lower bound span handled, move on.
      if (!x) {
        x = new N(min, max, payload);
        if (n)
          this->insertBefore(n, x);
        else
          this->append(x); // note that since n == 0 we'll just return.
      }
    } else if (0 != (n = this->getHead()) &&           // at least one node in tree.
               n->_data == payload &&                  // payload matches
               (n->_max <= max || n->_min <= max_plus) // overlap or adj.
               ) {
      // Same payload with overlap, re-use.
      x = n;
      n = next(n);
      x->setMin(min);
      if (x->_max < max)
        x->setMax(max);
    } else {
      x = new N(min, max, payload);
      this->prepend(x);
    }

    // At this point, @a x has the node for this span and all existing spans of
    // interest start at or past this span.
    while (n) {
      if (n->_max <= max) { // completely covered, drop span, continue
        y = n;
        n = next(n);
        this->remove(y);
      } else if (max_plus < n->_min) { // no overlap, done.
        break;
      } else if (n->_data == payload) { // skew overlap or adj., same payload
        x->setMax(n->_max);
        y = n;
        n = next(n);
        this->remove(y);
      } else if (n->_min <= max) { // skew overlap different payload
        n->setMin(max_plus);
        break;
      }
    }

    return *this;
  }

  template <typename N>
  IpMapBase<N> &
  IpMapBase<N>::unmark(ArgType min, ArgType max)
  {
    N *n = this->lowerBound(min);
    N *x; // temp for deletes.

    // Need to handle special case where first span starts to the left.
    if (n && n->_min < min) {
      if (n->_max >= min) { // some overlap
        if (n->_max > max) {
          // request span is covered by existing span - split existing span.
          x = new N(max, N::argue(n->_max), n->_data);
          x->incrementMin();
          n->setMaxMinusOne(N::deref(min));
          this->insertAfter(n, x);
          return *this; // done.
        } else {
          n->setMaxMinusOne(N::deref(min)); // just clip overlap.
        }
      } // else disjoint so just skip it.
      n = next(n);
    }
    // n and all subsequent spans start at >= min.
    while (n) {
      x = n;
      n = next(n);
      if (x->_max <= max) {
        this->remove(x);
      } else {
        if (x->_min <= max) { // clip overlap
          x->setMinPlusOne(N::deref(max));
        }
        break;
      }
    }
    return *this;
  }

  template <typename N>
  void
  IpMapBase<N>::insertAfter(N *spot, N *n)
  {
    N *c = right(spot);
    if (!c)
      spot->setChild(n, N::RIGHT);
    else
      spot->_next->setChild(n, N::LEFT);

    _list.insertAfter(spot, n);
    _root = static_cast<N *>(n->rebalanceAfterInsert());
  }

  template <typename N>
  void
  IpMapBase<N>::insertBefore(N *spot, N *n)
  {
    N *c = left(spot);
    if (!c)
      spot->setChild(n, N::LEFT);
    else
      spot->_prev->setChild(n, N::RIGHT);

    _list.insertBefore(spot, n);
    _root = static_cast<N *>(n->rebalanceAfterInsert());
  }

  template <typename N>
  void
  IpMapBase<N>::prepend(N *n)
  {
    if (!_root)
      _root = n;
    else
      _root = static_cast<N *>(_list.getHead()->setChild(n, N::LEFT)->rebalanceAfterInsert());
    _list.prepend(n);
  }

  template <typename N>
  void
  IpMapBase<N>::append(N *n)
  {
    if (!_root)
      _root = n;
    else
      _root = static_cast<N *>(_list.getTail()->setChild(n, N::RIGHT)->rebalanceAfterInsert());
    _list.append(n);
  }

  template <typename N>
  void
  IpMapBase<N>::remove(N *n)
  {
    _root = static_cast<N *>(n->remove());
    _list.take(n);
    delete n;
  }

  template <typename N>
  bool
  IpMapBase<N>::contains(ArgType x, void **ptr) const
  {
    bool zret = false;
    N *n      = _root; // current node to test.
    while (n) {
      if (x < n->_min)
        n = left(n);
      else if (n->_max < x)
        n = right(n);
      else {
        if (ptr)
          *ptr = n->_data;
        zret   = true;
        break;
      }
    }
    return zret;
  }

  template <typename N>
  size_t
  IpMapBase<N>::getCount() const
  {
    return _list.getCount();
  }
  //----------------------------------------------------------------------------
  template <typename N>
  void
  IpMapBase<N>::validate()
  {
#if 0
  if (_root) _root->validate();
  for ( Node* n = _list.getHead() ; n ; n = n->_next ) {
    Node* x;
    if (0 != (x = n->_next)) {
      if (x->_prev != n)
        std::cout << "Broken list" << std::endl;
      if (n->_max >= x->_min)
        std::cout << "Out of order - " << n->_max << " > " << x->_min << std::endl;
      if (n->_parent == n || n->_left == n || n->_right == n)
        std::cout << "Looped node" << std::endl;
    }
  }
#endif
  }

  template <typename N>
  IpMapBase<N> &
  IpMapBase<N>::print()
  {
#if 0
  for ( Node* n = _list.getHead() ; n ; n = n->_next ) {
    std::cout
      << n << ": " << n->_min << '-' << n->_max << " [" << n->_data << "] "
      << (n->_color == Node::BLACK ? "Black " : "Red   ") << "P=" << n->_parent << " L=" << n->_left << " R=" << n->_right
      << std::endl;
  }
#endif
    return *this;
  }

  //----------------------------------------------------------------------------
  typedef Interval<in_addr_t, in_addr_t> Ip4Span;

  /** Node for IPv4 map.
      We store the address in host order in the @a _min and @a _max
      members for performance. We store copies in the @a _sa member
      for API compliance (which requires @c sockaddr* access).
  */
  class Ip4Node : public IpMap::Node, protected Ip4Span
  {
    friend struct IpMapBase<Ip4Node>;

  public:
    typedef Ip4Node self; ///< Self reference type.

    /// Construct with values.
    Ip4Node(ArgType min, ///< Minimum address (host order).
            ArgType max, ///< Maximum address (host order).
            void *data   ///< Client data.
            )
      : Node(data), Ip4Span(min, max)
    {
      ats_ip4_set(ats_ip_sa_cast(&_sa._min), htonl(min));
      ats_ip4_set(ats_ip_sa_cast(&_sa._max), htonl(max));
    }
    /// @return The minimum value of the interval.
    virtual sockaddr const *
    min() const
    {
      return ats_ip_sa_cast(&_sa._min);
    }
    /// @return The maximum value of the interval.
    virtual sockaddr const *
    max() const
    {
      return ats_ip_sa_cast(&_sa._max);
    }
    /// Set the client data.
    self &
    setData(void *data ///< Client data.
            )
    {
      _data = data;
      return *this;
    }

  protected:
    /// Set the minimum value of the interval.
    /// @return This interval.
    self &
    setMin(ArgType min ///< Minimum value (host order).
           )
    {
      _min                     = min;
      _sa._min.sin_addr.s_addr = htonl(min);
      return *this;
    }

    /// Set the maximum value of the interval.
    /// @return This interval.
    self &
    setMax(ArgType max ///< Maximum value (host order).
           )
    {
      _max                     = max;
      _sa._max.sin_addr.s_addr = htonl(max);
      return *this;
    }

    /** Set the maximum value to one less than @a max.
        @return This object.
    */
    self &
    setMaxMinusOne(ArgType max ///< One more than maximum value.
                   )
    {
      return this->setMax(max - 1);
    }
    /** Set the minimum value to one more than @a min.
        @return This object.
    */
    self &
    setMinPlusOne(ArgType min ///< One less than minimum value.
                  )
    {
      return this->setMin(min + 1);
    }
    /** Decremement the maximum value in place.
        @return This object.
    */
    self &
    decrementMax()
    {
      this->setMax(_max - 1);
      return *this;
    }
    /** Increment the minimum value in place.
        @return This object.
    */
    self &
    incrementMin()
    {
      this->setMin(_min + 1);
      return *this;
    }

    /// Increment a metric.
    static void
    inc(Metric &m ///< Incremented in place.
        )
    {
      ++m;
    }

    /// Decrement a metric.
    static void
    dec(Metric &m ///< Decremented in place.
        )
    {
      --m;
    }

    /// @return Dereferenced @a addr.
    static Metric
    deref(ArgType addr ///< Argument to dereference.
          )
    {
      return addr;
    }

    /// @return The argument type for the @a metric.
    static ArgType
    argue(Metric const &metric)
    {
      return metric;
    }

    struct {
      sockaddr_in _min;
      sockaddr_in _max;
    } _sa; ///< Addresses in API compliant form.
  };

  class Ip4Map : public IpMapBase<Ip4Node>
  {
    friend class ::IpMap;
  };

  //----------------------------------------------------------------------------
  typedef Interval<sockaddr_in6> Ip6Span;

  /** Node for IPv6 map.
  */
  class Ip6Node : public IpMap::Node, protected Ip6Span
  {
    friend struct IpMapBase<Ip6Node>;

  public:
    typedef Ip6Node self; ///< Self reference type.
    /// Override @c ArgType from @c Interval because the convention
    /// is to use a pointer, not a reference.
    typedef Metric const *ArgType;

    /// Construct from pointers.
    Ip6Node(ArgType min, ///< Minimum address (network order).
            ArgType max, ///< Maximum address (network order).
            void *data   ///< Client data.
            )
      : Node(data), Ip6Span(*min, *max)
    {
    }
    /// Construct with values.
    Ip6Node(Metric const &min, ///< Minimum address (network order).
            Metric const &max, ///< Maximum address (network order).
            void *data         ///< Client data.
            )
      : Node(data), Ip6Span(min, max)
    {
    }
    /// @return The minimum value of the interval.
    virtual sockaddr const *
    min() const
    {
      return ats_ip_sa_cast(&_min);
    }
    /// @return The maximum value of the interval.
    virtual sockaddr const *
    max() const
    {
      return ats_ip_sa_cast(&_max);
    }
    /// Set the client data.
    self &
    setData(void *data ///< Client data.
            )
    {
      _data = data;
      return *this;
    }

  protected:
    /// Set the minimum value of the interval.
    /// @return This interval.
    self &
    setMin(ArgType min ///< Minimum value (host order).
           )
    {
      ats_ip_copy(ats_ip_sa_cast(&_min), ats_ip_sa_cast(min));
      return *this;
    }

    /// Set the minimum value of the interval.
    /// @note Convenience overload.
    /// @return This interval.
    self &
    setMin(Metric const &min ///< Minimum value (host order).
           )
    {
      return this->setMin(&min);
    }

    /// Set the maximum value of the interval.
    /// @return This interval.
    self &
    setMax(ArgType max ///< Maximum value (host order).
           )
    {
      ats_ip_copy(ats_ip_sa_cast(&_max), ats_ip_sa_cast(max));
      return *this;
    }
    /// Set the maximum value of the interval.
    /// @note Convenience overload.
    /// @return This interval.
    self &
    setMax(Metric const &max ///< Maximum value (host order).
           )
    {
      return this->setMax(&max);
    }
    /** Set the maximum value to one less than @a max.
        @return This object.
    */
    self &
    setMaxMinusOne(Metric const &max ///< One more than maximum value.
                   )
    {
      this->setMax(max);
      dec(_max);
      return *this;
    }
    /** Set the minimum value to one more than @a min.
        @return This object.
    */
    self &
    setMinPlusOne(Metric const &min ///< One less than minimum value.
                  )
    {
      this->setMin(min);
      inc(_min);
      return *this;
    }
    /** Decremement the maximum value in place.
        @return This object.
    */
    self &
    decrementMax()
    {
      dec(_max);
      return *this;
    }
    /** Increment the mininimum value in place.
        @return This object.
    */
    self &
    incrementMin()
    {
      inc(_min);
      return *this;
    }

    /// Increment a metric.
    static void
    inc(Metric &m ///< Incremented in place.
        )
    {
      uint8_t *addr = m.sin6_addr.s6_addr;
      uint8_t *b    = addr + TS_IP6_SIZE;
      // Ripple carry. Walk up the address incrementing until we don't
      // have a carry.
      do {
        ++*--b;
      } while (b > addr && 0 == *b);
    }

    /// Decrement a metric.
    static void
    dec(Metric &m ///< Decremented in place.
        )
    {
      uint8_t *addr = m.sin6_addr.s6_addr;
      uint8_t *b    = addr + TS_IP6_SIZE;
      // Ripple borrow. Walk up the address decrementing until we don't
      // have a borrow.
      do {
        --*--b;
      } while (b > addr && static_cast<uint8_t>(0xFF) == *b);
    }
    /// @return Dereferenced @a addr.
    static Metric const &
    deref(ArgType addr ///< Argument to dereference.
          )
    {
      return *addr;
    }

    /// @return The argument type for the @a metric.
    static ArgType
    argue(Metric const &metric)
    {
      return &metric;
    }
  };

  // We declare this after the helper operators and inside this namespace
  // so that the template uses these for comparisons.

  class Ip6Map : public IpMapBase<Ip6Node>
  {
    friend class ::IpMap;
  };
}
} // end ts::detail
//----------------------------------------------------------------------------
IpMap::~IpMap()
{
  delete _m4;
  delete _m6;
}

inline ts::detail::Ip4Map *
IpMap::force4()
{
  if (!_m4)
    _m4 = new ts::detail::Ip4Map;
  return _m4;
}

inline ts::detail::Ip6Map *
IpMap::force6()
{
  if (!_m6)
    _m6 = new ts::detail::Ip6Map;
  return _m6;
}

bool
IpMap::contains(sockaddr const *target, void **ptr) const
{
  bool zret = false;
  if (AF_INET == target->sa_family) {
    zret = _m4 && _m4->contains(ntohl(ats_ip4_addr_cast(target)), ptr);
  } else if (AF_INET6 == target->sa_family) {
    zret = _m6 && _m6->contains(ats_ip6_cast(target), ptr);
  }
  return zret;
}

bool
IpMap::contains(in_addr_t target, void **ptr) const
{
  return _m4 && _m4->contains(ntohl(target), ptr);
}

IpMap &
IpMap::mark(sockaddr const *min, sockaddr const *max, void *data)
{
  ink_assert(min->sa_family == max->sa_family);
  if (AF_INET == min->sa_family) {
    this->force4()->mark(ntohl(ats_ip4_addr_cast(min)), ntohl(ats_ip4_addr_cast(max)), data);
  } else if (AF_INET6 == min->sa_family) {
    this->force6()->mark(ats_ip6_cast(min), ats_ip6_cast(max), data);
  }
  return *this;
}

IpMap &
IpMap::mark(in_addr_t min, in_addr_t max, void *data)
{
  this->force4()->mark(ntohl(min), ntohl(max), data);
  return *this;
}

IpMap &
IpMap::unmark(sockaddr const *min, sockaddr const *max)
{
  ink_assert(min->sa_family == max->sa_family);
  if (AF_INET == min->sa_family) {
    if (_m4)
      _m4->unmark(ntohl(ats_ip4_addr_cast(min)), ntohl(ats_ip4_addr_cast(max)));
  } else if (AF_INET6 == min->sa_family) {
    if (_m6)
      _m6->unmark(ats_ip6_cast(min), ats_ip6_cast(max));
  }
  return *this;
}

IpMap &
IpMap::unmark(in_addr_t min, in_addr_t max)
{
  if (_m4)
    _m4->unmark(ntohl(min), ntohl(max));
  return *this;
}

IpMap &
IpMap::fill(sockaddr const *min, sockaddr const *max, void *data)
{
  ink_assert(min->sa_family == max->sa_family);
  if (AF_INET == min->sa_family) {
    this->force4()->fill(ntohl(ats_ip4_addr_cast(min)), ntohl(ats_ip4_addr_cast(max)), data);
  } else if (AF_INET6 == min->sa_family) {
    this->force6()->fill(ats_ip6_cast(min), ats_ip6_cast(max), data);
  }
  return *this;
}

IpMap &
IpMap::fill(in_addr_t min, in_addr_t max, void *data)
{
  this->force4()->fill(ntohl(min), ntohl(max), data);
  return *this;
}

size_t
IpMap::getCount() const
{
  size_t zret = 0;
  if (_m4)
    zret += _m4->getCount();
  if (_m6)
    zret += _m6->getCount();
  return zret;
}

IpMap &
IpMap::clear()
{
  if (_m4)
    _m4->clear();
  if (_m6)
    _m6->clear();
  return *this;
}

IpMap::iterator
IpMap::begin() const
{
  Node *x = 0;
  if (_m4)
    x = _m4->getHead();
  if (!x && _m6)
    x = _m6->getHead();
  return iterator(this, x);
}

IpMap::iterator &IpMap::iterator::operator++()
{
  if (_node) {
    // If we go past the end of the list see if it was the v4 list
    // and if so, move to the v6 list (if it's there).
    Node *x = static_cast<Node *>(_node->_next);
    if (!x && _tree->_m4 && _tree->_m6 && _node == _tree->_m4->getTail())
      x   = _tree->_m6->getHead();
    _node = x;
  }
  return *this;
}

inline IpMap::iterator &IpMap::iterator::operator--()
{
  if (_node) {
    // At a node, try to back up. Handle the case where we back over the
    // start of the v6 addresses and switch to the v4, if there are any.
    Node *x = static_cast<Node *>(_node->_prev);
    if (!x && _tree->_m4 && _tree->_m6 && _node == _tree->_m6->getHead())
      x   = _tree->_m4->getTail();
    _node = x;
  } else if (_tree) {
    // We were at the end. Back up to v6 if possible, v4 if not.
    if (_tree->_m6)
      _node = _tree->_m6->getTail();
    if (!_node && _tree->_m4)
      _node = _tree->_m4->getTail();
  }
  return *this;
}

//----------------------------------------------------------------------------
//----------------------------------------------------------------------------