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

/* Forward Decls */
static int ref_array_del(Ref **target, int write, int read);
static int ref_array_add(const char *dn, struct berval *referral, int write, int read);
static Ref **ref_array_find(const char *dn);
static int ref_array_mod(Ref **target, struct berval *referral, int write, int read);
static void strcat_escaped( char *s1, char *s2 );
static void adjust_referral_basedn( char **urlp, const Slapi_DN *refcontainerdn, char *opdn_norm, int isreference );
static int dn_is_below( const char *dn_norm, const char *ancestor_norm );
static Ref_Array *g_get_global_referrals(void);
static void ref_free (Ref **goner);
static Ref_Array global_referrals;

struct refCb {
    int type;
    char *cbName;
    void (*cb)(Slapi_PBlock *, void *);
    void *cbData;
    struct refCb *next;
};

struct refCb *refCbList=NULL;

int
ref_register_callback(int type, char *description, 
		      void (*cb)(Slapi_PBlock *, void *), void *cbData);
int
ref_remove_callback(char *description);
static
int ref_call_cbs(int type, Slapi_PBlock *pb);


#define SLAPD_DEFAULT_REFARRAY_SIZE 10

/*
 *  Function: g_get_global_referrals
 *
 *  Returns: nothing
 *
 *  Description: Fills the global_referrals referral array.
 *               The size is set to "size". The mutex is created.
 *               The array is calloc'd.
 */
static Ref_Array *
g_get_global_referrals(void)
{
    if (global_referrals.ra_rwlock == NULL)
	{
        /* Make a new lock */
        global_referrals.ra_rwlock = rwl_new();
      
        if (global_referrals.ra_rwlock == NULL) {
            LDAPDebug( LDAP_DEBUG_ANY,
    		   "ref_array_init: new lock creation failed\n", 0, 0, 0);
        	exit (-1);
        }
        
        /* Initialize all the fields. */
        global_referrals.ra_size = SLAPD_DEFAULT_REFARRAY_SIZE;
        global_referrals.ra_nextindex = 0;
        global_referrals.ra_readcount = 0;
        global_referrals.ra_refs = (Ref **) slapi_ch_calloc(SLAPD_DEFAULT_REFARRAY_SIZE, sizeof( Ref * ));
	}
    return( &global_referrals );
}

/*
 *  Function: ref_array_del
 *
 *  Returns: 0 good, -1 bad.
 *
 *  Description: finds "dn" in the list and unsets the read or write
 *               flag(s). If both are then zero, then it frees up that entry.
 *               target should point to the referral that is to be deleted.
 *               Note: This does NOT lock global_referrals.ra_rwlock.
 *               
 * Author: RJP
 */
static int
ref_array_del(Ref **target, int write, int read)
{
  Ref           **lastref = NULL;
  Ref_Array      *grefs = NULL;

  grefs = g_get_global_referrals();

  if (target == NULL) {
    return(-1); 
  }

  /*Unset either or both flags*/
  if (write) {
    (*target)->ref_writes = 0;
  }
  if (read) {
    (*target)->ref_reads = 0;
    grefs->ra_readcount--;
  }
  
  /*If there is a flag set, then don't delete the referral*/
  if (((*target)->ref_writes == 1) || (*target)->ref_reads == 1){
    return(0);
  }
  
  /* Free up target */
  ref_free(target);


  /*
   * Okay, we want to maintain our array's compactedness, 
   * so we take the referral that's in the last position, and 
   * put that in target's place. If they are one and the 
   * same, then no problem. This shouldn't ever seg fault.
   * (famous last words).
   */
  lastref = &grefs->ra_refs[grefs->ra_nextindex - 1];

  *target = *lastref;

  grefs->ra_refs[grefs->ra_nextindex - 1] = NULL;

  /*reset the next_index*/
  grefs->ra_nextindex--;

  return(0);

}


/*
 *  Function: ref_array_replace
 *
 *  Returns: 0 good, -1 bad.
 *
 *  Description: Locks the mutex associated with global_referrals,
 *               adds that referral and "dn" to the global_referrals if it
 *               doesn't exist already. If it does exist, and the new
 *               referral is different, then the old one gets clobbered.
 *               If referral is NULL, then it deletes the referral 
 *               associated with dn.
 *               Note: This locks global_referrals.ra_rwlock.
 *               
 * Author: RJP
 */
int
ref_array_replace(const char *dn, struct berval *referral, int write, int read)
{
  Ref           **target = NULL;
  int            err;
  Ref_Array      *grefs = NULL;

  grefs = g_get_global_referrals();

  if (dn == NULL) {
    return(0);
  }

  GR_LOCK_WRITE();
  
  /* Find the referral, if any. */
  target = ref_array_find(dn);

  /* If datasource is NULL, then delete target. */
  if ( referral == NULL ){

    /* If target is null, then there is nothing to do. */
    if (target == NULL) {
      GR_UNLOCK_WRITE();
      return(0);
    }
    err = ref_array_del(target, write, read);
        
    GR_UNLOCK_WRITE();

    return(err);
  }

  /* If target is NULL, then add target to the end. */
  if ( target == NULL) {
    err = ref_array_add(dn, referral, write, read);
    GR_UNLOCK_WRITE();
    return(err);
  }

  /* Else, the referral already exists and we should modify it. */
  err = ref_array_mod(target, referral, write, read);
  GR_UNLOCK_WRITE();
  return(err);
}


/*
 *  Function: ref_array_mod
 *
 *  Returns: 0 good, -1 bad.
 *
 *  Description: modifies the existing referral.
 *               First it checks the host:port in datasource 
 *               against the host:port in the existing referral.
 *               If they don't match, then it replaces the referral
 *
 *               Note: This does NOT lock global_referrals.ra_rwlock.
 *               
 * Author: RJP
 */
static int
ref_array_mod(Ref **target, struct berval *referral, int write, int read)
{
  Ref_Array     *grefs  = NULL;

  grefs = g_get_global_referrals();

  if (referral == NULL || target == NULL) {
    return(0);
  }

  /* Actually, instead of comparing them, we might as well just swap */
  ber_bvfree( (*target)->ref_referral );

  (*target)->ref_referral = referral ;

  /* 
   * We have to update the read/write flags which
   * refer reads and writes, respectively
   */
  if (write) {
    (*target)->ref_writes = 1;
  }
  if (read) {
    /*Don't update the readcount unnecessarily*/
    if ((*target)->ref_reads == 0) {
      grefs->ra_readcount++;
    }
    
    (*target)->ref_reads = 1;
  }

  return(0);
  
}



/*
 *  Function: ref_array_add
 *
 *  Returns: 0 good, -1 bad.
 *
 *  Description: adds that referral and "dn" to the global_referrals 
 *               Note: This does NOT lock global_referrals.ra_rwlock.
 *               
 * Author: RJP
 */
static int
ref_array_add(const char *dn, struct berval *referral, int write, int read)
{
  Ref           **target = NULL;
  Ref_Array     *grefs = NULL;

  grefs = g_get_global_referrals();

  if (dn == NULL || referral == NULL) {
    return(0);
  }


  /* We may have to realloc if we are about to index an out-of-range slot */
  if (grefs->ra_nextindex >= grefs->ra_size){
    /* reset the size */
    grefs->ra_size += 10;
    
    /* reallocate */
    grefs->ra_refs = (Ref **) slapi_ch_realloc((char *) grefs->ra_refs, 
						  grefs->ra_size * (sizeof(Ref *)));
  }

  /* Tack the new referral to the end. */
  target = &(grefs->ra_refs[grefs->ra_nextindex]);
  
  /* Malloc and fill the fields of the new referral */
  (*target) = (Ref *) slapi_ch_malloc( sizeof(Ref));
  (*target)->ref_dn = slapi_dn_normalize_case(slapi_ch_strdup(dn));
  (*target)->ref_referral = referral;
  
  /* Update the next available index */
  grefs->ra_nextindex++;

  (*target)->ref_writes = 0;
  (*target)->ref_reads = 0;

  /* 
   * We have to update the read/write flags which
   * refer reads and writes, respectively
   */
  if (write) {
    (*target)->ref_writes = 1;
  }
  if (read) {
    (*target)->ref_reads = 1;
    grefs->ra_readcount++;
  }

  return(0);
}

/*
 * Function: ref_array_find
 *
 * Returns: a pointer to a pointer to a Ref, or NULL
 *
 * Description: Traverses the array of referrals, until
 *              it either finds a match or gets to the end.
 *              Note: This DOES NOT lock global_referrals.ra_rwlock.
 *
 * Author: RJP
 *
 */
static Ref **
ref_array_find(const char *dn)
{
  int walker;
  Ref_Array  *grefs = NULL;

  grefs = g_get_global_referrals();

  if (dn == NULL) {
    return(NULL);
  }

  /* Walk down the array, testing for a match */
  for (walker = 0; walker < grefs->ra_nextindex; walker++){

    if (strcasecmp (grefs->ra_refs[walker]->ref_dn, dn) == 0) {
      return(&grefs->ra_refs[walker]);
    }
  }
  return(NULL);
}

/*
 * Function: send_read_referrals
 *
 * Returns: A copy of global_referrals
 *
 * Description: Given a dn, this function sends all the copyingfrom
 *              referrals beneath "dn" that are within "scope."
 *              returns a copy of the global_referrals array
 *              that it makes for use later. This is to avoid
 *              any race conditions of ORC ending in the middle
 *              of the search and scewing things up. NULL is returned
 *              if there are no copyingfrom referrals in there.
 *
 *              If "dn" does not exactly match a referral's dn, we append
 *              "/referralDN" to the referral itself, i.e, we send a
 *              referral like this:
 *                   ldap://host:port/dn
 *              instead of one like this:
 *                   ldap://host:port
 *              We do not append the referral DN to the referrals present
 *              in the copy of the global_referrals array that we return.
 *
 * Author: RJP
 *
 */
Ref_Array * 
send_read_referrals(Slapi_PBlock *pb, int scope, char *dn,
	struct berval ***urls)
{
  int             walker, urllen, dnlen;
  struct berval  *refs[2], refcopy;
  char           *urlcopy;
  Ref_Array      *grefs     = NULL;
  Ref_Array      *the_copy  = NULL;
  int             found_one = 0;

  /* Get a pointer to global_referrals */
  grefs = g_get_global_referrals();
  
  GR_LOCK_READ();

  /*If no copyingfroms, just return*/
  if (grefs->ra_readcount <= 0) {
    GR_UNLOCK_READ();
    return(NULL);
  }
  
  refs[1] = NULL;

  /*
   * Walk through the refs in the_copy and send any referrals
   * that are below "dn".  Take "scope" into account as well.
   */
  for (walker = 0; walker < grefs->ra_nextindex; walker++) {
    if ( grefs->ra_refs[walker]->ref_reads && 
	 (( scope == LDAP_SCOPE_BASE &&
	     strcasecmp(grefs->ra_refs[walker]->ref_dn, dn) == 0 ) ||
	 ( scope == LDAP_SCOPE_ONELEVEL &&
	     slapi_dn_isparent(dn, grefs->ra_refs[walker]->ref_dn)) ||
	 ( scope == LDAP_SCOPE_SUBTREE &&
	     slapi_dn_issuffix(grefs->ra_refs[walker]->ref_dn, dn)))) {
      found_one = 1;
      
      /*
       * Make an array of 1 referral.  If the referral DN is below "dn",
       * i.e, it is not the same as "dn", we make a copy and append a
       * URL-escaped version of the referral DN to the original referral.
       */
      if ( scope == LDAP_SCOPE_BASE ||
	    strcasecmp( grefs->ra_refs[walker]->ref_dn, dn ) == 0 ) {
	refs[0] = grefs->ra_refs[walker]->ref_referral;
	urlcopy = NULL;
      } else {
	urllen = strlen( grefs->ra_refs[walker]->ref_referral->bv_val );
	dnlen = strlen( grefs->ra_refs[walker]->ref_dn );
	/* space for worst-case expansion due to escape plus room for '/' */
	urlcopy = slapi_ch_malloc( urllen + 3 * dnlen + 2 );

	strcpy( urlcopy, grefs->ra_refs[walker]->ref_referral->bv_val );
	urlcopy[urllen] = '/';
	++urllen;
	urlcopy[urllen] = '\0';
	strcat_escaped( urlcopy + urllen, grefs->ra_refs[walker]->ref_dn );

	refcopy.bv_val = urlcopy;
	refcopy.bv_len = strlen( urlcopy );
	refs[0] = &refcopy;
      }

      send_ldap_referral( pb, NULL, refs, urls ); 
      slapi_pblock_set( pb, SLAPI_SEARCH_REFERRALS, *urls );

      if ( urlcopy != NULL ) {
        slapi_ch_free( (void **)&urlcopy );
      }
    }
  }
  
  /* Make a copy of global_referrals to avoid any race conditions */
  if (found_one) {
    the_copy = ref_array_dup();
  }
  
  GR_UNLOCK_READ();

  /*
   * After we sent all the referrals, return the copy of
   * global_referrals for use later. If there were none found, return
   * NULL 
   */
  return(the_copy);
}

/*
 * Function: ref_array_dup
 *
 * Returns: a copy of global_referrals 
 *
 * Description: Makes a copy of global_referrals and returns that puppy
 *              Note: Does not lock global_referrals.
 *
 * Author: RJP
 *
 */
Ref_Array *
ref_array_dup(void)
{
  Ref_Array *grefs    = NULL;
  Ref_Array *the_copy = NULL;
  int        walker;

  /*Allocate the first structure*/
  the_copy = (Ref_Array *) slapi_ch_calloc(1, sizeof(Ref_Array));

  /* Don't bother with the lock, it's only a local copy. */
  the_copy->ra_rwlock = NULL;

  /*Grab a reference to the global_referrals*/
  grefs = g_get_global_referrals();

  /* Initialize all the fields of the copy. */
  the_copy->ra_size      = grefs->ra_size;
  the_copy->ra_nextindex = grefs->ra_nextindex;
  the_copy->ra_readcount = grefs->ra_readcount;
  the_copy->ra_refs = (Ref **) slapi_ch_calloc(the_copy->ra_size, sizeof( Ref * ));

  /*Walk down grefs, copying each Ref struct */
  for (walker = 0; walker < grefs->ra_nextindex; walker++) {
    the_copy->ra_refs[walker] = (Ref *)slapi_ch_calloc(1, sizeof(Ref));						       
    the_copy->ra_refs[walker]->ref_dn = slapi_ch_strdup(grefs->ra_refs[walker]->ref_dn);
    the_copy->ra_refs[walker]->ref_referral = slapi_ch_bvdup(grefs->ra_refs[walker]->ref_referral);
    the_copy->ra_refs[walker]->ref_reads = grefs->ra_refs[walker]->ref_reads;
    the_copy->ra_refs[walker]->ref_writes = grefs->ra_refs[walker]->ref_writes;
  }

  return(the_copy);

}


/*
 * Function: ref_free
 *
 * Returns: nothing
 *
 * Description: frees up "goner"
 *
 * Author: RJP
 *
 */
static void
ref_free (Ref **goner)
{
  slapi_ch_free((void**) &((*goner)->ref_dn));
  ber_bvfree( (*goner)->ref_referral );
  slapi_ch_free((void**) goner);
}

/*
 * Function: ref_array_dup_free
 *
 * Returns: nothingness
 *
 * Description: takes a Ref_Array dup and frees that puppy
 *
 * Author: RJP
 *
 */
void
ref_array_dup_free(Ref_Array *the_copy)
{
	int walker;

	if (the_copy == NULL) {
		return;
	}

	/* Walk down the array, deleting each referral */
	for (walker = 0; walker < the_copy->ra_nextindex; walker++)
	{
		ref_free (&the_copy->ra_refs[walker]);
	} 

	/* free the array of pointers */
	slapi_ch_free((void **) &the_copy->ra_refs);
	slapi_ch_free((void **) &the_copy);

	return;
}



/*
 * Function: referrals_free
 *
 * Returns: nothing
 *
 * Description: frees up everything.
 *
 * Author: RJP
 *
 */
void
referrals_free (void)
{
  int walker;
  Ref_Array *grefs = NULL;

  grefs = g_get_global_referrals();

  GR_LOCK_WRITE();

  /* Walk down the array, deleting each referral */
  for (walker = 0; walker < grefs->ra_nextindex; walker++){
   ref_free (&grefs->ra_refs[walker]);

  } 
  
  slapi_ch_free ((void **) &grefs->ra_refs);

  GR_UNLOCK_WRITE();

  rwl_free( &grefs->ra_rwlock );
}

/*
 *  Function: ref_array_moddn
 *
 *  Returns: 0 good, -1 bad.
 *
 *  Description: modifies the existing referral's dn.
 *               First it locks global_referrals.ra_rwlock.
 *               Then it clobbers the existing dn.
 *               Then it replaces it with a new dn constructed 
 *               from newrdn.
 *               Note: This locks global_referrals.ra_rwlock.
 *               
 * Author: RJP
 */
void
ref_array_moddn(const char *dn, char *newrdn, Slapi_PBlock *pb)
{
  char  *pdn = NULL;
  char  *newdn = NULL;
  Ref  **target = NULL;
  Ref_Array      *grefs = NULL;

  grefs = g_get_global_referrals();

  if (dn == NULL) {
    return;
  }
  
  GR_LOCK_WRITE();
  
  /* Find the referral. */
  target = ref_array_find(dn);
  
  /* 
   * If we can't find it, then we're done. This is okay, because this
   * is the only check that is made to see if the entry has a
   * copiedfrom in it.
   */
  if (target == NULL) {
    GR_UNLOCK_WRITE();
    return;
  }
  /* construct the new dn */
  if ( (pdn = slapi_dn_beparent( pb, dn )) != NULL ) {
    /* parent + rdn + separator(s) + null */
    newdn = (char *) slapi_ch_malloc( strlen( pdn ) + strlen( newrdn ) + 3 );
    strcpy( newdn, newrdn );
    strcat( newdn, ", " );
    strcat( newdn, pdn );
  } else {
    newdn = (char *) slapi_ch_strdup( newrdn );
  }
  slapi_ch_free((void **) &pdn );
  (void) slapi_dn_normalize_case( newdn );


  /* We have found the referral. blow away the dn*/
  slapi_ch_free((void**) &((*target)->ref_dn));

  /* stick in the new one. */
  (*target)->ref_dn = newdn;

  GR_UNLOCK_WRITE();

  return;
}


/*
 * HREF_CHAR_ACCEPTABLE was copied from libldap/tmplout.c
 */
/* Note: an identical function is in ../plugins/replication/replutil.c */
#define HREF_CHAR_ACCEPTABLE( c )	(( c >= '-' && c <= '9' ) ||	\
					 ( c >= '@' && c <= 'Z' ) ||	\
					 ( c == '_' ) ||		\
					 ( c >= 'a' && c <= 'z' ))

/*
 *  Function: strcat_escaped
 *
 *  Returns: nothing
 *
 *  Description: Appends string s2 to s1, URL-escaping (%HH) unsafe
 *               characters in s2 as appropriate.  This function was
 *               copied from libldap/tmplout.c.
 *               
 * Author: MCS
 */
/*
 * append s2 to s1, URL-escaping (%HH) unsafe characters
 */
/* Note: an identical function is in ../plugins/replication/replutil.c */
static void
strcat_escaped( char *s1, char *s2 )
{
    char	*p, *q;
    char	*hexdig = "0123456789ABCDEF";

    p = s1 + strlen( s1 );
    for ( q = s2; *q != '\0'; ++q ) {
	if ( HREF_CHAR_ACCEPTABLE( *q )) {
	    *p++ = *q;
	} else {
	    *p++ = '%';
	    *p++ = hexdig[ 0x0F & ((*(unsigned char*)q) >> 4) ];
	    *p++ = hexdig[ 0x0F & *q ];
	}
    }

    *p = '\0';
}

void
update_global_referrals(Slapi_PBlock *pb)
{
    ref_call_cbs(0,pb);
    return;
}

/*
 * ref_adjust() -- adjust referrals based on operation-specific data.
 * The general idea is for us (the server) to be smart so LDAP clients
 * can be as dumb as possible.
 *
 * XXXmcs: We always duplicate the referrals even if no adjustments need to
 * be made.  It would be more efficient but more complicated to avoid making
 * a copy if we don't need to change anything.  If that were done, the
 * interface to this function would need to change since the caller would
 * need to know whether the returned memory needed to be freed or not.
 *
 * Parameters:
 *     pb is the pblock for the operation we are working on.
 *     urls is a list of referrals.
 *     refsdn is the Slapi_DN of the entry where the referral is stored.
 *     is_reference is true if a searchResultReference is being returned.
 *
 * Returns:
 *    a (possibly modified) copy of the urls.  It should be freed by
 *         calling ber_bvecfree().
 *
 *
 * First we strip off any labels from the referral URLs.  For example, a
 * referral like this:
 *
 *    ldap://directory.airius.com/ou=people,o=airius.com  Ref to people tree
 *
 * is changed to:
 *
 *    ldap://directory.airius.com/ou=people,o=airius.com
 *
 * Next, if the referral includes a baseDN we potentially modify it or strip
 * it off entirely. If the referral doesn't include a baseDN and we're
 * processing a continuation reference, we add a baseDN.
 *
 * Finally, if we are processing a continuation reference that resulted from
 * a one-level search, we append "??base" to the referral so the client will
 * use the correct scope when chasing the reference.
 */
struct berval **
ref_adjust( Slapi_PBlock *pb, struct berval **urls, const Slapi_DN *refsdn,
	int is_reference )
{
    int			i, len, scope;
    char		*p, *opdn_norm;
    struct berval	**urlscopy;
    Operation		*op;

    if ( NULL == urls || NULL == urls[0] ) {
	return( NULL );
    }

    PR_ASSERT( pb != NULL );

    /*
     * grab the operation target DN and operation structure.
     * if the operation is a search, get the scope as well.
     */
    if ( slapi_pblock_get( pb, SLAPI_TARGET_DN, &p ) != 0 || p == NULL ||
	    slapi_pblock_get( pb, SLAPI_OPERATION, &op ) != 0 || op == NULL ||
	    ( operation_get_type(op) == SLAPI_OPERATION_SEARCH && slapi_pblock_get( pb,
	    SLAPI_SEARCH_SCOPE, &scope ) != 0 )) {
	LDAPDebug( LDAP_DEBUG_ANY, "ref_adjust: referrals suppressed "
		"(could not get target DN, operation, or scope from pblock)\n",
		0, 0, 0 );
	return( NULL );
    }

    /*
     * normalize the DNs we plan to compare with others later.
     */
    opdn_norm = slapi_dn_normalize( slapi_ch_strdup( p ));


    /*
     * count referrals and duplicate the array
     */
    for ( i = 0; urls[i] != NULL; ++i ) {
	;
    }
    urlscopy = (struct berval **) slapi_ch_malloc(( i + 1 ) *
	    sizeof( struct berval * ));

    for ( i = 0; urls[i] != NULL; ++i ) {
	/*
	 * duplicate the URL, stripping off the label if there is one and
	 * leaving extra room for "??base" in case we need to append that.
	 */
	urlscopy[i] = (struct berval *)slapi_ch_malloc(
		sizeof( struct berval ));
	if (( p = strchr( urls[i]->bv_val, ' ' )) == NULL ) {
	    len = strlen( urls[i]->bv_val );
	} else {
	    len = p - urls[i]->bv_val;
	}
	urlscopy[i]->bv_val = (char *)slapi_ch_malloc( len + 7 );
	memcpy( urlscopy[i]->bv_val, urls[i]->bv_val, len );
	urlscopy[i]->bv_val[len] = '\0';

	/*
	 * adjust the baseDN as needed and set the length
	 */
	adjust_referral_basedn( &urlscopy[i]->bv_val, refsdn,
		opdn_norm, is_reference );
	urlscopy[i]->bv_len = strlen( urlscopy[i]->bv_val );

	/*
	 * if we are dealing with a continuation reference that resulted
	 * from a one-level search, add a scope of base to the URL.
	 */
	if ( is_reference && operation_get_type(op) == SLAPI_OPERATION_SEARCH &&
		scope == LDAP_SCOPE_ONELEVEL ) {
	    strcat( urlscopy[i]->bv_val, "??base" );
	    urlscopy[i]->bv_len += 6;
	}
    }

    urlscopy[i] = NULL;	/* NULL terminate the new referrals array */

    /*
     * log what we did (for debugging purposes)
     */
	if ( LDAPDebugLevelIsSet( LDAP_DEBUG_ARGS )) {
	for ( i = 0; urlscopy[i] != NULL; ++i ) {
	    LDAPDebug( LDAP_DEBUG_ARGS, "ref_adjust: \"%s\" -> \"%s\"\n",
		urls[i]->bv_val, urlscopy[i]->bv_val, 0 );
	}
    }

    /*
     * done -- clean up and return the new referrals array
     */
    slapi_ch_free( (void **)&opdn_norm );

    return( urlscopy );
}



/*
 * adjust_referral_basedn() -- pull the referral apart and modify the
 * baseDN contained in the referral if appropriate not.
 * If the referral does not have baseDN and we're not processing a
 * continuation reference, we do not need to do anything. If we're
 * processing a continuation reference, we need to add a baseDN.
 *
 * If it does have one, there are two special cases we deal with:
 *
 *  1) The referral's baseDN is an ancestor of the operation's baseDN,
 *     which means that the LDAP client already has a more specific
 *     baseDN than is contained in the referral.  If so, we strip off
 *     the baseDN so the client will re-use its operation DN when
 *     chasing the referral.
 *
 *  2) The referral's baseDN is not an ancestor of the operation's
 *     baseDN and the DN of the entry that contains the referral is
 *     an ancestor of the operation DN.  If so, we remove the portion
 *     of the operation DN that matches the DN of the entry containing
 *     the referral and prepend what's left to the referral base DN.
 *
 * We assume that the baseDN is the right-most piece of the URL, i.e., there
 * is no attribute list, scope, or options after the baseDN.
 *
 * The code also assumes that the baseDN doesn't contain any '/' character.
 * This later assumption NEED to be removed and code changed appropriately.
 */
static void
adjust_referral_basedn( char **urlp, const Slapi_DN *refsdn,
	char *opdn_norm, int isreference )
{
    LDAPURLDesc		*ludp = NULL;
    char		*p, *refdn_norm;
	int rc = 0;
	
    PR_ASSERT( urlp != NULL );
    PR_ASSERT( *urlp != NULL );
    PR_ASSERT( refsdn != NULL );
    PR_ASSERT( opdn_norm != NULL );

	if (opdn_norm == NULL){
		/* Be safe but this should never ever happen */
		return;
	}
	
	rc = ldap_url_parse( *urlp, &ludp );

	if	((rc != 0) && 
		 (rc != LDAP_URL_ERR_NODN)) 
		/* 
		 * rc != LDAP_URL_ERR_NODN is to circumvent a pb in the C-SDK
		 * in ldap_url_parse. The function will return an error if the
		 * URL contains no DN (though it is a valid URL according to
		 * RFC 2255.
		 */
	{
		/* Nothing to do, just return */
		return;
	}
	
    if (ludp && (ludp->lud_dn != NULL)) {

		refdn_norm = slapi_dn_normalize( slapi_ch_strdup( ludp->lud_dn ));
		
		if ( dn_is_below( opdn_norm, refdn_norm )) {
			/*
			 * Strip off the baseDN.
			 */
			if (( p = strrchr( *urlp, '/' )) != NULL ) {
				*p = '\0';
			}

		} else if ( dn_is_below( opdn_norm, slapi_sdn_get_ndn(refsdn) )) {
			int		cur_len, add_len;
			
			/*
			 * Prepend the portion of the operation DN that does not match
			 * the ref container DN to the referral baseDN.
			 */
			add_len = strlen( opdn_norm ) - strlen( slapi_sdn_get_ndn(refsdn) );
			cur_len = strlen( *urlp );
			/* + 7 because we keep extra space in case we add ??base */
			*urlp = slapi_ch_realloc( *urlp, cur_len + add_len + 7 );
			
			if (( p = strrchr( *urlp, '/' )) != NULL ) {
				++p;
				memmove( p + add_len, p, strlen( p ) + 1 );
				memmove( p, opdn_norm, add_len );
			}
			
		}	/* else: leave the original referral baseDN intact. */
		
		slapi_ch_free( (void **)&refdn_norm );
    } else if (isreference) { 
		int		cur_len, add_len;

		/* If ludp->lud_dn == NULL and isreference : Add the DN of the ref entry*/
		if ( dn_is_below( opdn_norm, slapi_sdn_get_ndn(refsdn) )){
			add_len = strlen(opdn_norm);
			p = opdn_norm;
		} else {
			add_len = strlen(slapi_sdn_get_ndn(refsdn));
			p = (char *)slapi_sdn_get_ndn(refsdn);
		}
		
		cur_len = strlen( *urlp );
		/* + 8 because we keep extra space in case we add a / and/or ??base  */
		*urlp = slapi_ch_realloc( *urlp, cur_len + add_len + 8 );
		if ((*urlp)[cur_len - 1] != '/'){
			/* The URL is not ending with a /, let's add one */
			strcat(*urlp, "/");
		}
		strcat(*urlp, p);
	}
	
    if ( ludp != NULL ) {
		ldap_free_urldesc( ludp );
    }
	return;
}


/*
 * dn_is_below(): return non-zero if "dn_norm" is below "ancestor_norm" in
 * the DIT and return zero if not.
 */
static int
dn_is_below( const char *dn_norm, const char *ancestor_norm )
{
    PR_ASSERT( dn_norm != NULL );
    PR_ASSERT( ancestor_norm != NULL );

    if ( 0 == strcasecmp( dn_norm, ancestor_norm )) {
	return( 0 );	/* same DN --> not an ancestor relationship */
    }

    return( slapi_dn_issuffix( dn_norm, ancestor_norm ));
}



/*
 * This function is useful to discover the source of data and provide
 * this as a referral. It is also useful if someone simply wants
 * to know if a dn is mastered somewhere else.
 *
 * For a given dn, traverse the referral list and look for the copiedFrom
 * attribute. If such an attribute is found get the server hostname
 * and port in the form "ldap://hostname:port".
 * Else return NULL.
 * 
 * ORC extension: if orc == 1, this function will search for copyingFrom
 * which will refer searches and compares on trees that are half-baked.
 *
 * ORC extension: if cf_refs is NULL, then global_referrals is consulted,
 * otherwise, cf_refs is consulted. 
 */
struct berval **
get_data_source(Slapi_PBlock *pb, const Slapi_DN *sdn, int orc, void *cfrp)
{
  int             walker;
  struct berval **bvp;
  struct berval  *bv;
  int             found_it;
  Ref_Array      *grefs = NULL;
  Ref_Array      *the_refs = NULL;
  Ref_Array      *cf_refs = (Ref_Array *)cfrp;

  /* If no Ref_Array is given, use global_referrals */
  if (cf_refs == NULL) {
    grefs = g_get_global_referrals();
    the_refs = grefs;
    GR_LOCK_READ();
  } else {
    the_refs = cf_refs;
  }

  /* optimization: if orc is 1 (a read), then check the readcount*/
  if (orc && the_refs->ra_readcount == 0) {
    if (cf_refs == NULL) {
      GR_UNLOCK_READ();
    }
    return (NULL);
  }
  

  bvp = NULL;
  bv = NULL;
  found_it = 0;

  /* Walk down the array, testing each dn to make see if it's a parent of "dn" */
  for (walker = 0; walker < the_refs->ra_nextindex; walker++){

    if ( slapi_dn_issuffix(slapi_sdn_get_ndn(sdn), the_refs->ra_refs[walker]->ref_dn)) {
      found_it = 1;
      break;

    }
  }
  
  /* no referral, so return NULL */
  if (!found_it) {
    if (cf_refs == NULL) {
      GR_UNLOCK_READ();
    }
    return (NULL);
  }

  /* 
   * Gotta make sure we're returning the right one. If orc is 1, then
   * only return a read referral. if orc is 0, then only return a
   * write referral.
   */
  if (orc && the_refs->ra_refs[walker]->ref_reads != 1) {
    if (cf_refs == NULL) {
      GR_UNLOCK_READ();
    }
    return (NULL);
  }

  if (!orc && the_refs->ra_refs[walker]->ref_writes != 1) {
    if (cf_refs == NULL) {
      GR_UNLOCK_READ();
    }
    return (NULL);
  }


  /* Fix for 310968 --- return an SSL referral to an SSL client */
	if ( 0 != ( pb->pb_conn->c_flags & CONN_FLAG_SSL )) {
		/* SSL connection */
		char * old_referral_string = NULL;
		char * new_referral_string = NULL;
		char *p = NULL;
		/* Get the basic referral */
		bv = slapi_ch_bvdup(the_refs->ra_refs[walker]->ref_referral);
		old_referral_string = bv->bv_val;
		/* Re-write it to replace ldap with ldaps, and remove the port information */
		/* The original string will look like this: ldap://host:port */
		/* We need to make it look like this: ldaps://host */
		/* Potentially the ":port" part might be missing from the original */
		new_referral_string = slapi_ch_smprintf("%s%s" , LDAPS_URL_PREFIX, old_referral_string + strlen(LDAP_URL_PREFIX) );
		/* Go looking for the port */
		p = new_referral_string + (strlen(LDAPS_URL_PREFIX) + 1);
		while (*p != '\0' && *p != ':') p++;
		if (':' == *p) {
			/* It had a port, zap it */
			*p = '\0';
		}
		/* Fix the bv to point to this new string */
		bv->bv_val = new_referral_string;
		/* Fix its length */
		bv->bv_len = strlen(bv->bv_val);
		/* Free the copy we made of the original */
		slapi_ch_free((void**)&old_referral_string);
	} else {
		/* regular connection */
		bv = (struct berval *) slapi_ch_bvdup(the_refs->ra_refs[walker]->ref_referral);
	}  

  /* Package it up and send that puppy. */
  bvp = (struct berval **) slapi_ch_malloc( 2 * sizeof(struct berval *) );
  bvp[0] = bv;
  bvp[1] = NULL;

  if (cf_refs == NULL) {
    GR_UNLOCK_READ();
  }

  return(bvp);

}


int
ref_register_callback(int type, char *description, 
		      void (*cb)(Slapi_PBlock *, void *), void *cbData)
{
    struct refCb *cbPtr;
    struct refCb *newCb;

    if(NULL == (newCb = 
		(struct refCb *)slapi_ch_calloc(1,sizeof(struct refCb)))) {
	/* out of memory? */
	return(-1);
    }
    newCb->type = type;
    newCb->next = NULL;
    newCb->cb = cb;
    newCb->cbData = cbData;
    newCb->cbName = slapi_ch_strdup(description);

    if(NULL == refCbList) {
	refCbList = newCb;
	return(0);
    }
    cbPtr = refCbList;
    while(NULL != cbPtr->next) cbPtr = cbPtr->next;
    cbPtr->next=newCb;
    
    return(0);
}

int
ref_remove_callback(char *description)
{
    struct refCb *cbPtr = refCbList;
    struct refCb *cbPrev = refCbList;

    if((NULL == description) || (NULL == cbPtr)) 
	return(-1);

    while(cbPtr) {
	if(!strcmp(description,cbPtr->cbName)) {
	    if(cbPrev == refCbList) {
		refCbList = cbPtr->next;
	    } else {
		cbPrev->next = cbPtr->next;
	    }
	    slapi_ch_free((void **)&cbPtr->cbName);
	    /* we don't know how the cbData was allocated...we won't attempt
	       to free it */
	    slapi_ch_free((void **)&cbPtr);
	    break;
	}
	cbPrev = cbPtr;
	cbPtr = cbPtr->next;
    }
    
    return(0);
}

static
int ref_call_cbs(int type, Slapi_PBlock *pb)
{
  struct refCb *cbPtr = refCbList;

  if(NULL == cbPtr) {
    return(0);
  }

  while(cbPtr) {
   (*cbPtr->cb)(pb, cbPtr->cbData);
   cbPtr = cbPtr->next;
  }
     
  return(0);
}