summaryrefslogtreecommitdiffstats
path: root/ldap/clients/dsgw/ldaputil.c
blob: 750fee6738f89b00ac19776dd3f86bf074d3472d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
/** --- BEGIN COPYRIGHT BLOCK ---
 * This Program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 2 of the License.
 * 
 * This Program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA.
 * 
 * In addition, as a special exception, Red Hat, Inc. gives You the additional
 * right to link the code of this Program with code not covered under the GNU
 * General Public License ("Non-GPL Code") and to distribute linked combinations
 * including the two, subject to the limitations in this paragraph. Non-GPL Code
 * permitted under this exception must only link to the code of this Program
 * through those well defined interfaces identified in the file named EXCEPTION
 * found in the source code files (the "Approved Interfaces"). The files of
 * Non-GPL Code may instantiate templates or use macros or inline functions from
 * the Approved Interfaces without causing the resulting work to be covered by
 * the GNU General Public License. Only Red Hat, Inc. may make changes or
 * additions to the list of Approved Interfaces. You must obey the GNU General
 * Public License in all respects for all of the Program code and other code used
 * in conjunction with the Program except the Non-GPL Code covered by this
 * exception. If you modify this file, you may extend this exception to your
 * version of the file, but you are not obligated to do so. If you do not wish to
 * provide this exception without modification, you must delete this exception
 * statement from your version and license this file solely under the GPL without
 * exception. 
 * 
 * 
 * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
  --- END COPYRIGHT BLOCK ---  */
/*
 * ldaputil.c -- LDAP utility functions -- HTTP gateway
 */

#include "dsgw.h"
#include "dbtdsgw.h"
#include "../../include/disptmpl.h"
#ifndef NO_LIBLCACHE
#include <lcache.h>
#endif
#if XP_WIN32
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#endif
#include "libadminutil/distadm.h"

static dsgwtmplinfo *init_listdisplay( char *tmplname, unsigned long options );
static int do_search( dsgwtmplinfo *tip, LDAP *ld, char *base, int scope,
	char *filter, LDAPMessage **msgpp );
static void handle_search_results( dsgwtmplinfo *tip, LDAP *ld, int rc,
	LDAPMessage *msgp, unsigned long options );
static int LDAP_CALL LDAP_CALLBACK
	get_rebind_credentials( LDAP *ld, char **whop, char **credp,
	int *methodp, int freeit, void *arg );
static void strcpy_special_undo( char *d, char *s );
static int entry2htmlwrite( void *fp, char *buf, int len );
static void emit_one_loc_dn( char *dn, char *friendlyname, char *rootname,
	int only_one );
static char *uid2dn( LDAP *ld, char *uid, char *base, int *ldaprc,
	char **lderrtxtp, char **errsp );
static void return_one_attr( LDAP *ld, LDAPMessage *entry, char *attrtype,
	char *mimetype, int valindex );
static void break_up_one_attr( char *attr, char **attrtypep, char **mimetypep,
	int *valindexp );

/* binddn and bindpasswd are used in get_rebind_credentials() */
static char *binddn = NULL, *bindpasswd = NULL;

#ifndef DSGW_NO_SSL
/*static CERTCertDBHandle certdbh;*/
static char * certdbh;

#endif

/*
 * initialize various LDAP library things -- any non-NULL parameters are
 *	initialized and set.  If an error occurs, this function will not
 *	return at all.
 * If an LDAP connection was opened, this function will return either
 * DSGW_BOUND_ASUSER if a valid cookie was found in the environment
 * and we were able to bind to the directory as that user.  If no
 * cookie was found, or the cookie would not be used to bind, then
 * an anonymous bind is performed and DSGW_BOUND_ANONYMOUS is returned.
 * If skipac (skip authentication check) is non-zero, then this
 * function will always authenticate as NULL.
 *
 * If we are configured to use a local LDAP database instead of a real
 * directory server, we always do an unauthenticated bind but we return
 * DSGW_BOUND_ASUSER.  This is done to keep our CGIs that check for a
 * return code of DSGW_BOUND_ASUSER happy.
 *
 * If skipauthwarning is set, then we don't display the javascript
 * auth warning for searches. - RJP
 */
int
dsgw_init_ldap( LDAP **ldp, LDAPFiltDesc **lfdpp, int skipac, int skipauthwarning )
{
    char	*path;
    char	*userid, *dn, *rndstr, *passwd, *cookie, *p;
    int		ret = 0, optval, limit;
#ifdef XP_WIN32
    WSADATA	wsadata;
#endif

    /* LDAP search filters */
    if ( lfdpp != NULL ) {
	path = dsgw_file2path( gc->gc_configdir, DSGW_FILTERFILE );
	if (( *lfdpp = ldap_init_getfilter( path )) == NULL ) {
	    dsgw_error( DSGW_ERR_BADCONFIG, path, DSGW_ERROPT_EXIT, 0, NULL );
	}
	free( path );
	ret =  0;
    }

#ifdef XP_WIN32

    if( ret = WSAStartup(0x0101, &wsadata ) != 0 )
	dsgw_error( DSGW_ERR_WSAINIT, NULL, DSGW_ERROPT_EXIT, 0, NULL );

#endif /* XP_WIN32 */

    /* LDAP connection */
    if ( ldp != NULL ) {
	if ( gc == NULL ) {
	    dsgw_error( DSGW_ERR_INTERNAL, 
		    XP_GetClientStr(DBT_ldapInitLcacheInitAttemptedBefor_),
		    DSGW_ERROPT_EXIT, 0, NULL );
	}
	if ( gc->gc_localdbconf == NULL ) {
	    /* "Real LDAP server" case */
#ifdef DSGW_NO_SSL
	    *ldp = ldap_init( gc->gc_ldapserver, gc->gc_ldapport );
#else /* DSGW_NO_SSL */
	    if ( gc->gc_ldapssl ) {
		if ( gc->gc_securitypath == NULL ) {
		    dsgw_error( DSGW_ERR_NOSECPATH, NULL, DSGW_ERROPT_EXIT,
			    0, NULL );
		}
		if ( ldapssl_client_init( gc->gc_securitypath,
			&certdbh ) < 0 ) {
		    dsgw_error( DSGW_ERR_SSLINIT, gc->gc_securitypath,
			    DSGW_ERROPT_EXIT, 0, NULL );
		}
		*ldp = ldapssl_init( gc->gc_ldapserver, gc->gc_ldapport, 1 );
		dsgw_NSSInitializedAlready = 1;
	    } else {
		*ldp = ldap_init( gc->gc_ldapserver, gc->gc_ldapport );
	    }
#endif /* !DSGW_NO_SSL */
	    if ( *ldp == NULL ) {
		dsgw_error( DSGW_ERR_LDAPINIT, NULL, DSGW_ERROPT_EXIT, 0,
			NULL );
	    }

	} 
#ifndef NO_LIBLCACHE
else {
	    /* Local DB case */
	    if (( *ldp = ldap_init( NULL, 0 )) == NULL ) {
		dsgw_error( DSGW_ERR_LDAPINIT, NULL, DSGW_ERROPT_EXIT, 0,
			NULL );
	    }
	    if ( lcache_init( *ldp, gc->gc_localdbconf ) != 0 ) {
		dsgw_error( DSGW_ERR_LCACHEINIT, strerror(errno),
			DSGW_ERROPT_EXIT, 0, NULL );
	    }
	    optval = 1;
	    (void) ldap_set_option( *ldp, LDAP_OPT_CACHE_ENABLE, &optval );
	    optval = LDAP_CACHE_LOCALDB;
	    (void) ldap_set_option( *ldp, LDAP_OPT_CACHE_STRATEGY, &optval );
	}
#endif
	rndstr = dn = NULL;
	passwd = dsgw_get_cgi_var( "passwd", DSGW_CGIVAR_OPTIONAL );

	if (( p = dsgw_get_cgi_var( "ldapsizelimit", DSGW_CGIVAR_OPTIONAL ))
		!= NULL ) {
	    limit = atoi( p );
	    (void) ldap_set_option( *ldp, LDAP_OPT_SIZELIMIT, &limit );
	}

	if (( p = dsgw_get_cgi_var( "ldaptimelimit", DSGW_CGIVAR_OPTIONAL ))
		!= NULL ) {
	    limit = atoi( p );
	    (void) ldap_set_option( *ldp, LDAP_OPT_TIMELIMIT, &limit );
	}

	/*
	 * we don't bother with authentication if:
	 *  the "skipac" flag is non-zero OR
	 *  no "passwd" form element was passed in and we are using local db
	 */
	if ( !skipac && ( passwd != NULL || gc->gc_localdbconf == NULL )) {
	    /*
	     * There are several ways in which authentication might
	     * happen.
	     */
	    if ( gc->gc_admserv ) {
		/*
		 * We're running under the admin server, so ask libadmin
		 * for the user's credentials.  If a password comes as a form
		 * field, it overrides value we get from admin server
		 */
		(void)dsgw_get_adm_identity( *ldp, &userid, &dn,
			( passwd == NULL ) ? &passwd : NULL, DSGW_ERROPT_EXIT );

#ifdef DSGW_DEBUG
		dsgw_log( "dsgw_init_ldap: run under admserv, user id = %s, "
			"dn = %s, passwd = %s, skipac = %d, dn = 0x%x\n",
			userid == NULL ? "NULL" : userid,
			dn == NULL ? "NULL" : dn,
			passwd == NULL ? "NULL" : passwd,
			skipac, dn );
#endif
	    } else {
		/*
		 * Not running under admin server.  The DN and password
		 * might come in as form fields, or the authentication
		 * might be accomplished via a client-side cookie which
		 * gets looked up in the gateway's cookie database.
		 */

		/* check for dn/binddn in request */
		if ( passwd != NULL ) {
		    if (( dn = dsgw_get_escaped_cgi_var( "escapedbinddn",
			    "binddn", DSGW_CGIVAR_OPTIONAL )) == NULL &&
			    ( dn = dsgw_get_cgi_var( "dn",
			    DSGW_CGIVAR_OPTIONAL )) == NULL ) {
			free( passwd );
			passwd = NULL;
		    } else {
			/* got DN:  undo extra level of escaping */
			dsgw_form_unescape( dn );
		    }
		}

		if ( passwd == NULL ) {
		    /* Check for a valid authentication cookie */
		    cookie = dsgw_get_auth_cookie();
		    if ( cookie != NULL ) {
			if ( dsgw_parse_cookie( cookie, &rndstr, &dn ) == 0 ) {
			    int ckrc;
			    if (( ckrc = dsgw_ckdn2passwd( rndstr, dn,
				    &passwd )) != 0 ) {

				passwd = NULL;
				dn = NULL;
				/* 
				 * Delete the cookie and print out the error message.
				 * dn2passwd_error() returns 1 if the CGI should exit,
				 * 0 if it should continue.
				 */
				if (dsgw_dn2passwd_error( ckrc, skipauthwarning )) {
				    exit( 0 );
				}

			    }
			}
		    }

		    if ( rndstr != NULL ) {
			free( rndstr );
		    }
		    if ( cookie != NULL ) {
			free( cookie );
		    }
		}
	    }
	}

	/*
	 * try to use LDAP version 3 but fall back to v2 if bind fails
	 */
	optval = LDAP_VERSION3;
	(void)ldap_set_option( *ldp, LDAP_OPT_PROTOCOL_VERSION, &optval );

	/*
	 * If everything above failed to set the dn/password, then use
	 * the binddn and bindpw, if any.
	 */
	if (dn == NULL && passwd == NULL && 
	    strlen(gc->gc_binddn) > 0 && strlen(gc->gc_bindpw) > 0) {
	  dn = dsgw_ch_strdup(gc->gc_binddn);
	  passwd = dsgw_ch_strdup(gc->gc_bindpw);
	}

	if (( ret = ldap_simple_bind_s( *ldp, dn, passwd ))
	    == LDAP_PROTOCOL_ERROR ) {
		optval = LDAP_VERSION2;
		(void)ldap_set_option( *ldp, LDAP_OPT_PROTOCOL_VERSION,
			&optval );
		ret = ldap_simple_bind_s( *ldp, dn, passwd );
	}

	if ( ret != LDAP_SUCCESS ){
	    dsgw_ldap_error( *ldp, DSGW_ERROPT_DURINGBIND );

	    /* Display back button */
	    dsgw_form_begin( NULL, NULL );
	    dsgw_emits( "\n<CENTER><TABLE border=2 width=\"100%\"><TR>\n" );
	    dsgw_emits( "<TD WIDTH=\"100%\" ALIGN=\"center\">\n" );
	    dsgw_emitf( "<INPUT TYPE=\"button\" VALUE=\"%s\" "
		       "onClick=\"history.back()\">\n",
		       XP_GetClientStr(DBT_goBack_) );
	    dsgw_emits( "\n</TABLE></CENTER></FORM>\n" );
	    exit(0);
	}

	if (( dn != NULL ) && ( passwd != NULL )) {
	    ret = DSGW_BOUND_ASUSER;
	    binddn = dn;
	    bindpasswd = passwd;
	    ldap_set_rebind_proc( *ldp, get_rebind_credentials, NULL );
	} else if ( gc->gc_localdbconf != NULL ) {
	    ret = DSGW_BOUND_ASUSER;	/* a small, harmless lie */
	} else {
	    ret = DSGW_BOUND_ANONYMOUS;
	}

    }
    return ret;
}


/* 
 * get user identity from the admin. server (if running under it)
 *	if uidp is non-NULL, it is set to point to user's login id.
 *	if dnp is non-NULL, it is set to point to user's DN.
 *	if pwdp is non-NULL, it is set to point to user's password.
 * Returns: 0 if all goes well, -1 if an error occurs.
 *
 * Note that ld is used only if dnp != NULL, and then only if the admin server
 * returns NULL when asked for the DN.
 */
int
dsgw_get_adm_identity( LDAP *ld, char **uidp, char **dnp, char **pwdp,
	int erropts  )
{
    int		rc, need_to_get_dn;
    char	*uid;
    static int	adm_inited = 0;

    if ( !gc->gc_admserv ) {
	dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		XP_GetClientStr(DBT_notRunningUnderTheAdministration_),
		erropts, 0, NULL );
	return( -1 );
    }

    if ( !adm_inited ) {
	if ( ADM_InitializePermissions( &rc ) < 0 ) {
	    dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		    XP_GetClientStr(DBT_couldNotInitializePermissions_),
		    erropts, 0, NULL );
	    return( -1 );
	}
	adm_inited = 1;
    }

    need_to_get_dn = ( dnp != NULL );

    if ( need_to_get_dn && ADM_GetUserDNString( &rc, dnp ) < 0 ) {
	dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		XP_GetClientStr(DBT_couldNotMapUsernameToADnErrorFro_),
		erropts, 0, NULL );
	return( -1 );
    }

    /*
     * get userid if:
     *    1. requested by caller (uidp != NULL)
     * or 2. DN was requested but Admin Server didn't return the DN
     */
    if (( uidp != NULL || ( need_to_get_dn && *dnp == NULL )) &&
	    ( ADM_GetCurrentUsername( &rc, &uid ) < 0 || uid == NULL )) {
	dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		XP_GetClientStr(DBT_couldNotGetCurrentUsername_), erropts,
		0, NULL );
	return( -1 );
    }

    if ( uidp != NULL ) {
	*uidp = uid;
    }

    if ( need_to_get_dn && *dnp == NULL ) {
	/*
	 * try to map userid to DN using LDAP search
	 */
	int	lderr;
	char	*errstr, *lderrtxt;

	if (( *dnp = uid2dn( ld, uid, gc->gc_ldapsearchbase, &lderr,
		&lderrtxt, &errstr )) == NULL ) {
	    dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL, errstr, erropts, lderr,
		    lderrtxt );
	    return( -1 );
	}
    }

    if ( pwdp != NULL && ADM_GetCurrentPassword( &rc, pwdp ) < 0 ) {
	dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		XP_GetClientStr(DBT_couldNotGetCurrentUserPassword_), erropts,
		0, NULL );
	return( -1 );
    }

    return( 0 );
}


void
dsgw_ldap_error( LDAP *ld, int erropts )
{
    int		lderr;
    char	*lderrtxt = NULL;

    lderr = ldap_get_lderrno( ld, NULL, &lderrtxt );
    dsgw_error( DSGW_ERR_LDAPGENERAL, dsgw_ldaperr2string( lderr ),
		erropts, lderr, lderrtxt );
}


struct ldap_searchobj *
dsgw_type2searchobj( struct ldap_searchobj *solistp, char *type )
{
    struct ldap_searchobj	*sop;

    for ( sop = ldap_first_searchobj( solistp ); sop != NULL;
	    sop = ldap_next_searchobj( solistp, sop )) {
	if ( strcasecmp( type, sop->so_objtypeprompt ) == 0 ) {
	    return( sop );
	}
    }

    return( NULL );
}


struct ldap_searchattr *
dsgw_label2searchattr( struct ldap_searchobj *sop, char *label )
{
    struct ldap_searchattr *sap;

    for ( sap = sop->so_salist; sap != NULL; sap = sap->sa_next ) {
	if ( strcasecmp( label, sap->sa_attrlabel ) == 0 ) {
	    return( sap );
	}
    }

    return( NULL );
}


struct ldap_searchmatch *
dsgw_prompt2searchmatch( struct ldap_searchobj *sop, char *prompt )
{
    struct ldap_searchmatch *smp;

    for ( smp = sop->so_smlist; smp != NULL; smp = smp->sm_next ) {
	if ( strcasecmp( prompt, smp->sm_matchprompt ) == 0 ) {
	    return( smp );
	}
    }

    return( NULL );
}


static dsgwtmplinfo *
init_listdisplay( char *tmplname, unsigned long options )
{
    char	*s;

    if (( s = dsgw_get_cgi_var( "listtemplate", DSGW_CGIVAR_OPTIONAL ))
	    != NULL ) {
	tmplname = s;
    }

    return( dsgw_display_init( DSGW_TMPLTYPE_LIST, tmplname, options ));
}


void
dsgw_smart_search( LDAP *ld, struct ldap_searchobj *sop, LDAPFiltDesc *lfdp,
	char *base, char *value, unsigned long options )
{
    int			rc;
    LDAPFiltInfo	*lfip;
    dsgwtmplinfo	*tip;
    LDAPMessage		*msgp;

    ldap_setfilteraffixes( lfdp, sop->so_filterprefix, NULL );
    tip = init_listdisplay( sop->so_objtypeprompt, options );

    if (( lfip = ldap_getfirstfilter( lfdp, sop->so_filtertag, value ))
	    == NULL ) {
	dsgw_error( DSGW_ERR_NOFILTERS, sop->so_objtypeprompt,
		DSGW_ERROPT_EXIT, 0, NULL );
    }

    for ( ; lfip != NULL; lfip = ldap_getnextfilter( lfdp )) {
	dsgw_set_searchdesc( tip, NULL, lfip->lfi_desc, value );

	rc = do_search( tip, ld, base, sop->so_defaultscope, lfip->lfi_filter,
		&msgp );

	if ( rc != LDAP_SUCCESS ||
		( msgp != NULL && ldap_count_entries( ld, msgp ) > 0 )) {
	    if ( strstr( lfip->lfi_filter, "~=" ) != NULL ) {
		/* always list if approximate filter used to find entry */
		options |= DSGW_DISPLAY_OPT_LIST_IF_ONE;
	    }
	    break;	/* error or got some entries:  stop searching */
	}
    }

    handle_search_results( tip, ld, rc, msgp, options );
}


void
dsgw_pattern_search( LDAP *ld, char *listtmpl,
	char *searchdesc2, char *searchdesc3, char *searchdesc4,
	char *filtpattern, char *filtprefix, char *filtsuffix, char *attr,
	char *base, int scope, char *value, unsigned long options )
{
    char		buf[ 4096 ];
    int			rc;
    dsgwtmplinfo	*tip;
    LDAPMessage		*msgp;

    tip = init_listdisplay( listtmpl, options );

    ldap_build_filter( buf, sizeof( buf ), filtpattern,
	    filtprefix, filtsuffix, attr, value, NULL );

    dsgw_set_searchdesc( tip, searchdesc2, searchdesc3, searchdesc4 );

    rc = do_search( tip, ld, base, scope, buf, &msgp );
    handle_search_results( tip, ld, rc, msgp, options );
}


/*
 * Perform URL-based search.
 * Note that if "ld" is NULL, this routine sets gc->gc_ldapserver and
 * gc->gc_ldapport globals itself, calls dsgw_init_ldap(), and then does
 * the URL-based search.  If "ld" is not NULL, no initialization is done
 * here.
 */
void
dsgw_ldapurl_search( LDAP *ld, char *ldapurl )
{
    int			rc, ec, saveport, did_init_ldap;
    LDAPMessage		*msgp;
    LDAPURLDesc		*ludp;
    char		*saveserver;
    unsigned long	no_options = 0;
    int                 one_attr = 0;

    if (( rc = ldap_url_parse( ldapurl, &ludp )) != 0 ) {
	switch ( rc ) {
	case LDAP_URL_ERR_NODN:
	    ec = DSGW_ERR_LDAPURL_NODN;
	    break;
	case LDAP_URL_ERR_BADSCOPE:
	    ec = DSGW_ERR_LDAPURL_BADSCOPE;
	    break;
	case LDAP_URL_ERR_MEM:
	    ec = DSGW_ERR_NOMEMORY;
	    break;
	case LDAP_URL_ERR_NOTLDAP:
	default:
	    ec = DSGW_ERR_LDAPURL_NOTLDAP;
	    break;
	}
	dsgw_error( ec, ldapurl, DSGW_ERROPT_EXIT, 0, NULL );
    }

    if ( ld == NULL ) {
	saveserver = gc->gc_ldapserver;
	gc->gc_ldapserver = ludp->lud_host;
	saveport = gc->gc_ldapport;
	gc->gc_ldapport = ludp->lud_port;
	one_attr = ( ludp->lud_attrs != NULL && ludp->lud_attrs[ 0 ] != NULL && ludp->lud_attrs[ 1 ] == NULL );
	(void)dsgw_init_ldap( &ld, NULL, 0, one_attr );
	did_init_ldap = 1;
    } else {
	did_init_ldap = 0;
    }

    /* XXX a bit of a hack:  if it looks like only a DN was included, we
     * assume that a read of the entry is desired.
     */
    if ( ludp->lud_scope == LDAP_SCOPE_BASE && strcasecmp( ludp->lud_filter,
	    "(objectClass=*)" ) == 0 ) {
	dsgw_read_entry( ld, ludp->lud_dn, NULL, NULL, ludp->lud_attrs,
		no_options );
    } else {
	dsgwtmplinfo	*tip;

	dsgw_send_header();
	tip = init_listdisplay( "urlsearch", no_options );
	dsgw_set_searchdesc( tip, NULL, XP_GetClientStr(DBT_theLDAPFilterIs_), ldapurl );
	rc = do_search( tip, ld, ludp->lud_dn, ludp->lud_scope,
		ludp->lud_filter, &msgp );
	handle_search_results( tip, ld, rc, msgp, no_options );
    }

    if ( did_init_ldap ) {
	ldap_unbind( ld );
	gc->gc_ldapserver = saveserver;
	gc->gc_ldapport = saveport;
    }
}


/*
 * do the actual search over LDAP.  Return an LDAP error code.
 */
static int
do_search( dsgwtmplinfo *tip, LDAP *ld, char *base, int scope, char *filter,
	LDAPMessage **msgpp )
{
    char		**attrlist, *attrs[ 3 ];

    *msgpp = NULL;

    if ( tip == NULL || tip->dsti_attrs == NULL ) {
	attrs[ 0 ] = DSGW_ATTRTYPE_OBJECTCLASS;
	if ( tip != NULL && tip->dsti_sortbyattr != NULL ) {
	    attrs[ 1 ] = tip->dsti_sortbyattr;
	    attrs[ 2 ] = NULL;
	} else {
	    attrs[ 1 ] = NULL;
	}
	attrlist = attrs;
    } else {
	attrlist = tip->dsti_attrs;
    }
#ifdef DSGW_DEBUG
    dsgw_log ("ldap_search_s(ld,\"%s\",%i,\"%s\")\n", base, scope, filter);
#endif
    return( ldap_search_s( ld, base, scope, filter, attrlist, 0, msgpp ));
}


static int
is_subtype( const char *sub, const char *sup )
{
    auto const size_t subLen = strlen( sub );
    auto const size_t supLen = strlen( sup );
    if ( subLen < supLen ) return 0;
    if ( subLen == supLen ) return !strcasecmp( sub, sup );
    if ( sub[supLen] != ';' ) return 0;
    return !strncasecmp( sub, sup, strlen( sup ));
}

static const struct berval* LDAP_C LDAP_CALLBACK
dsgw_keygen( void *arg, LDAP *ld, LDAPMessage *entry )
{
    auto const char* sortbyattr = (char*)arg;
    auto struct berval* result = NULL;

    if (sortbyattr == NULL) {	/* sort by DN */
	auto char* DN = ldap_get_dn( ld, entry );
	if (DN) {
	    result = dsgw_strkeygen( CASE_INSENSITIVE, DN );
	    ldap_memfree( DN );
	}
    } else {
	auto char* attr;
	auto BerElement *ber;
	for (attr = ldap_first_attribute( ld, entry, &ber ); attr != NULL; 
	     attr = ldap_next_attribute ( ld, entry, ber ) ) {
	    auto char **vals;
	    if ( is_subtype( attr, sortbyattr ) &&
		NULL != ( vals = ldap_get_values( ld, entry, attr ))) {
		auto size_t i;
		for ( i = 0; vals[i] != NULL; ++i ) {
		    auto struct berval* key = dsgw_strkeygen( CASE_INSENSITIVE, vals[i] );
		    if ( result == NULL || dsgw_keycmp( NULL, key, result ) < 0 ) {
			auto struct berval* tmp = result;
			result = key;
			key = tmp;
#ifdef DSGW_DEBUG
			{
			    auto char* ev = dsgw_strdup_escaped( vals[i] );
			    auto char* DN = ldap_get_dn( ld, entry );
			    dsgw_log( "dsgw_keygen(%s,%s) %p %s\n", sortbyattr, DN, (void*)result, ev );
			    ldap_memfree( DN );
			    free( ev );
			}
#endif
		    }
		    if ( key != NULL ) {
			dsgw_keyfree( arg, key );
		    }
		}
		ldap_value_free( vals );
	    }
	    ldap_memfree( attr );
	}
	if ( ber != NULL ) {
	    ldap_ber_free( ber, 0 );
	}
    }
    return result ? result : /* no such attribute */ dsgw_key_last;
}

static void
handle_search_results( dsgwtmplinfo *tip, LDAP *ld, int rc, LDAPMessage *msgp,
	unsigned long options )
{
    int		count;
    LDAPMessage	*entry;
    char	*dn, *errortext, *lderrtxt, **ocvals;

    count = ( msgp == NULL ) ? 0 : ldap_count_entries( ld, msgp );
    if ( rc == LDAP_SUCCESS ) {
	errortext = NULL;
	lderrtxt = NULL;
    } else {
	errortext = dsgw_ldaperr2string( rc );
	(void)ldap_get_lderrno( ld, NULL, &lderrtxt );
    }
    dsgw_set_search_result( tip, count, errortext, lderrtxt );

    if ( count > 0 ) {
	entry = ldap_first_entry( ld, msgp );

	if ( count == 1 && ( options & DSGW_DISPLAY_OPT_LIST_IF_ONE ) == 0 ) {
	    /* found exactly one entry:  read and display it */
	    dn = ldap_get_dn( ld, entry );
	    ocvals = ldap_get_values( ld, entry, DSGW_ATTRTYPE_OBJECTCLASS );
	    ldap_msgfree( msgp );

	    dsgw_read_entry( ld, dn, ocvals, NULL, NULL, options );

	    if ( ocvals != NULL ) {
		ldap_value_free( ocvals );
	    }
	    return;
	}

	/* list entries */
#ifdef DSGW_DEBUG
	dsgw_log( "handle_search_results: sort entries by %s\n",
		  tip->dsti_sortbyattr ? tip->dsti_sortbyattr : "DN" );
#endif
	ldap_keysort_entries( ld, &msgp, tip->dsti_sortbyattr,
		dsgw_keygen, dsgw_keycmp, dsgw_keyfree );
	for ( entry = ldap_first_entry( ld, msgp ); entry != NULL;
		entry = ldap_next_entry( ld, entry )) {
	    dsgw_display_entry( tip, ld, entry, NULL, NULL );
	}
	if ( options & DSGW_DISPLAY_OPT_DNLIST_JS ) {
	    int i;
	    char *edn, *js0, *js1;
	    char **xdn;
	    char **sn;

	    dsgw_emits( "<SCRIPT LANGUAGE=\"JavaScript\">\n" );
	    dsgw_emits( "var dnlist = new Array;\n" );
	    for ( i = 0, entry = ldap_first_entry( ld, msgp ); entry != NULL;
		    i++, entry = ldap_next_entry( ld, entry )) {
		dn = ldap_get_dn( ld, entry );
		edn = dsgw_strdup_escaped( dn );
		xdn = ldap_explode_dn( dn, 1 );
		dsgw_emitf( "dnlist[%d] = new Object\n", i );
		dsgw_emitf( "dnlist[%d].edn = '%s';\n", i, edn );
		js0 = dsgw_escape_quotes( xdn[ 0 ] );
		if ( xdn[1] != NULL ) {
		    js1 = dsgw_escape_quotes( xdn[ 1 ] );
		    dsgw_emitf( "dnlist[%d].rdn = '%s, %s';\n", i, js0, js1 );
		    free( js1 );
		} else {
		    dsgw_emitf( "dnlist[%d].rdn = '%s';\n", i, js0 );
		}
		free( js0 );
		if (( sn = ldap_get_values( ld, entry, "sn" )) == NULL ) {
		    js0 = NULL;
		} else {
		    js0 = dsgw_escape_quotes( sn[ 0 ] );
		    ldap_value_free( sn );
		}
		dsgw_emitf( "dnlist[%d].sn = '%s';\n", i, ( js0 == NULL ) ?
			" " : js0 );
		if ( js0 != NULL ) {
		    free( js0 );
		}

		dsgw_emitf( "dnlist[%d].selected = false;\n", i );
		free( edn );
		ldap_value_free( xdn );
		ldap_memfree( dn );
	    }
	    dsgw_emitf( "dnlist.count = %d;\n", i );
	    dsgw_emitf( "</SCRIPT>\n" );
	}
	ldap_msgfree( msgp );
    } else {
	/* Count <= 0 */
	if ( options & DSGW_DISPLAY_OPT_DNLIST_JS ) {
	    dsgw_emitf( "<SCRIPT LANGUAGE=\"JavaScript\">\n" );
	    dsgw_emitf( "var dnlist = new Array;\n" );
	    dsgw_emitf( "dnlist.count = 0;\n" );
	    dsgw_emitf( "</SCRIPT>\n" );
	}
    }

    dsgw_display_done( tip );
}


/*
 * read and display a single entry.  If ocvals is non-NULL, it should
 * contain the list of objectClass values for this entry.
 */ 
void
dsgw_read_entry( LDAP *ld, char *dn, char **ocvals, char *tmplname,
	char **attrs, unsigned long options )
{
    int			rc, one_attr, freeocvals, valindex;
    char		*tmpattr, *attr0, *mimetype;
    LDAPMessage		*msgp, *entry, *aomsgp, *aoentry;
    dsgwtmpl		*tmpl;
    dsgwtmplinfo	*tip;

    if (( options & DSGW_DISPLAY_OPT_AUTH ) != 0 ) {
	/*
	 * XXX hack -- if we are trying to authenticate, we don't generate an
	 * entry display at all.  Instead, we generate an authenticate form.
	 */
	dsgw_send_header();
	dsgw_emit_auth_form( dn );
	return;
    }

    one_attr = ( attrs != NULL && attrs[ 0 ] != NULL && attrs[ 1 ] == NULL );
    if ( one_attr ) {
	break_up_one_attr( attrs[ 0 ], &tmpattr, &mimetype, &valindex );
	if ( strcasecmp( tmpattr, "_vcard" ) == 0 ) {	/* VCards are special */
	    dsgw_vcard_from_entry( ld, dn, mimetype );
	    return;
	}
	attr0 = attrs[ 0 ];     /* replace first & only attr. */
	attrs[ 0 ] = tmpattr;
    } else {
	attr0 = NULL;
    }

    if ( tmplname == NULL && ( tmplname = dsgw_get_cgi_var( "displaytemplate",
	    DSGW_CGIVAR_OPTIONAL )) == NULL && attrs == NULL ) {
	/* determine what display template to use based on objectClass values */
	freeocvals = 0;
	if ( ocvals == NULL ) {	/* read entry to get objectClasses */
	    char	*attrs[ 2 ];

	    attrs[ 0 ] = DSGW_ATTRTYPE_OBJECTCLASS;
	    attrs[ 1 ] = NULL;

	    if (( rc = ldap_search_s( ld, dn, LDAP_SCOPE_BASE, "objectClass=*",
		    attrs, 0, &msgp )) != LDAP_SUCCESS ||
		    ( entry = ldap_first_entry( ld, msgp )) == NULL ) {
		dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
	    }
	    ocvals = ldap_get_values( ld, msgp, DSGW_ATTRTYPE_OBJECTCLASS );
	    freeocvals = 1;
	    ldap_msgfree( msgp );
	}


	if ( ocvals == NULL || ( tmpl = dsgw_oc2template( ocvals )) == NULL ) {
	    tmplname = NULL;
	} else {
	    tmplname = tmpl->dstmpl_name;
	}

	if ( freeocvals ) {
	    ldap_value_free( ocvals );
	}
    }

    if ( tmplname == NULL ) {
	tip = NULL;

	if ( !one_attr ) {
	    char	*title;

	    if (( title = ldap_dn2ufn( dn )) == NULL ) {
		title = dn;
	    }
	    dsgw_send_header();
	    dsgw_html_begin( title, 1 );
	    dsgw_emitf( "<FONT SIZE=\"+1\">\n%s\n</FONT>\n",
	    XP_GetClientStr(DBT_noteThereIsNoDisplayTemplateForT_) );
	} 

    } else if (( tip = dsgw_display_init( DSGW_TMPLTYPE_DISPLAY, tmplname,
	    options )) != NULL ) {
	dsgw_send_header();
	attrs = tip->dsti_attrs;
    }

    /* now read the attributes needed for the template */
    if (( rc = ldap_search_s( ld, dn, LDAP_SCOPE_BASE, "objectClass=*",
	    attrs, 0, &msgp )) != LDAP_SUCCESS ) {
	dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
    }

    if (( entry = ldap_first_entry( ld, msgp )) == NULL ) {
	ldap_msgfree( msgp );
	dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
    }

    /* and retrieve attribute types only if we need any of them */
    if ( one_attr || tip == NULL || tip->dsti_attrsonly_attrs == NULL ) {
	aomsgp = NULL;
    } else {
	if (( rc = ldap_search_s( ld, dn, LDAP_SCOPE_BASE, "objectClass=*",
		tip->dsti_attrsonly_attrs, 1, &aomsgp )) != LDAP_SUCCESS ) {
	    dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
	}

	/*
	 * if no entries were returned, "aoentry" will be set to NULL by the
	 * next statement.  We don't treat that as an error since we know the
	 * entry exists.  It probably just means none of the "attrsonly" types
	 * were present in the entry.
	 */
	aoentry = ldap_first_entry( ld, aomsgp );
    }

    /* display it (finally!) */
    if ( one_attr ) {
	return_one_attr( ld, entry, attrs[ 0 ], mimetype, valindex );
    } else if ( tip == NULL ) {
	/* no template available -- display in an ugly but complete manner */
	if (( rc = ldap_entry2html( ld, NULL, entry, NULL, NULL, NULL,
		entry2htmlwrite, stdout, "\n", 0, LDAP_DISP_OPT_HTMLBODYONLY,
		NULL, NULL )) != LDAP_SUCCESS ) {
	    dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
	}
	dsgw_html_end();
    } else {
	/* use template to create a nicely formatted display */
	dsgw_display_entry( tip, ld, entry, aoentry, NULL );
	dsgw_display_done( tip );
    }

    if ( attr0 != NULL ) {
	attrs[ 0 ] = attr0;     /* if we replaced this, put original back */
    }

    if ( msgp != NULL ) {
	ldap_msgfree( msgp );
    }
    if ( aomsgp != NULL ) {
	ldap_msgfree( aomsgp );
    }
}


/*
 * return 1 if the entry already exists, 0 if not, -1 if some error occurs
 */
int
dsgw_ldap_entry_exists( LDAP *ld, char *dn, char **matchedp,
	unsigned long erropts )
{
    LDAPMessage *msgp;
    int		rc;

    msgp = NULL;
    if ( matchedp != NULL ) {
	*matchedp = NULL;
    }

    if (( rc = do_search( NULL, ld, dn, LDAP_SCOPE_BASE, "(objectClass=*)",
	    &msgp )) != LDAP_SUCCESS && rc != LDAP_NO_SUCH_OBJECT ) {
	dsgw_ldap_error( ld, erropts );
    }

    if ( msgp == NULL || rc == LDAP_NO_SUCH_OBJECT ) {
	rc = 0;
	if ( matchedp != NULL ) {
	    (void)ldap_get_lderrno( ld, matchedp, NULL );
	}
    } else {
	rc = ( ldap_count_entries( ld, msgp ) > 0 ? 1 : 0 );
	ldap_msgfree( msgp );
    }

    return( rc );
}


static int
entry2htmlwrite( void *fp, char *buf, int len )
{
        return( fwrite( buf, len, 1, (FILE *)fp ) == 0 ? -1 : len );
}


/*
 * return 1 if the entry's parent exists, 0 if not, -1 if some error occurs.
 * If the entry is the same as gc->gc_ldapsearchbase, then we return 1,
 * so we don't prevent people from adding their organizational entry.
 */
int
dsgw_ldap_parent_exists( LDAP *ld, char *dn, unsigned long erropts )
{
    LDAPMessage *msgp;
    int		rc;

    /* Is "dn" == gc->gc_ldapsearchbase? */
    msgp = NULL;
    if (( rc = do_search( NULL, ld, dn, LDAP_SCOPE_BASE, "(objectClass=*)",
	    &msgp )) != LDAP_SUCCESS && rc != LDAP_NO_SUCH_OBJECT ) {
	dsgw_ldap_error( ld, erropts );
    }

    if ( msgp == NULL ) {
	rc = 0;
    } else {
	rc = ( ldap_count_entries( ld, msgp ) > 0 ? 1 : 0 );
	ldap_msgfree( msgp );
    }

    return( rc );
}



/*
 * this function is called back by LIBLDAP when chasing referrals
 */
static int LDAP_CALL LDAP_CALLBACK
get_rebind_credentials( LDAP *ld, char **whop, char **credp,
	int *methodp, int freeit, void *arg )
{
    if ( !freeit ) {
	*whop = binddn;
	*credp = bindpasswd;
	*methodp = LDAP_AUTH_SIMPLE;
    }

    return( LDAP_SUCCESS );
}


char *
dsgw_get_binddn()
{
    return( binddn );
}

/*
 * return 1 if bound using "dn"
 * return 0 if definitely bound as someone else
 * return "def_answer" is we can't tell for sure
 */
int
dsgw_bound_as_dn( char *dn, int def_answer )
{
    int		i, rc;
    char	**rdns1, **rdns2;

    if ( binddn == NULL ) {
	/*
	 * not authenticated: if not using local db or using it as an
	 * end-user, return the default
	 */
	if ( gc->gc_localdbconf == NULL || gc->gc_enduser ) {
	    return( def_answer );
	}

	/*
         * if using local db as an admin, return "bound as someone else"
	 * since there is no access control enforced anyways.
	 */
	return( 0 );
    }

    /* first try a simple case-insensitive comparison */
    if ( strcasecmp( binddn, dn ) == 0 ) {
	return( 1 );	/* DNs are the same */
    }

    /*
     * These DNs may not have the same spacing or punctuation.  Compare RDN
     * components to eliminate any differences.
     */
    if (( rdns1 = ldap_explode_dn( binddn, 0 )) == NULL ) {
	return( def_answer );	/* we don't know: return the default */
    }

    if (( rdns2 = ldap_explode_dn( dn, 0 )) == NULL ) {
	ldap_value_free( rdns1 );
	return( def_answer );	/* we don't know: return the default */
    }

    for ( i = 0; rdns1[ i ] != NULL && rdns2[ i ] != NULL; ++i ) {
	if ( strcasecmp( rdns1[ i ], rdns2[ i ] ) != 0 ) {
	    break;	/* DNs are not the same */
	}
    }

    rc = ( rdns1[ i ] == NULL && rdns2[ i ] == NULL );

    ldap_value_free( rdns1 );
    ldap_value_free( rdns2 );

    return( rc );
}



/*
 * Compare 2 DNs.  Return 1 if they are equivalent, 0 if not.
 */
int
dsgw_dn_cmp( char *dn1, char *dn2 )
{
    int		i, rc;
    char	**rdns1, **rdns2;

    /* first try a simple case-insensitive comparison */
    if ( dsgw_utf8casecmp( (unsigned char *)dn1, (unsigned char *)dn2 ) == 0 ) {
	return( 1 );	/* DNs are the same */
    }

    /*
     * These DNs may not have the same spacing or punctuation.  Compare RDN
     * components to eliminate any differences.
     */
    if (( rdns1 = ldap_explode_dn( dn1, 0 )) == NULL ) {
	return( 0 );	/* we don't know: return 0 */
    }

    if (( rdns2 = ldap_explode_dn( dn2, 0 )) == NULL ) {
	ldap_value_free( rdns1 );
	return( 0 );	/* we don't know: return 0 */
    }

    for ( i = 0; rdns1[ i ] != NULL && rdns2[ i ] != NULL; ++i ) {
	if ( dsgw_utf8casecmp( (unsigned char *)rdns1[ i ], (unsigned char *)rdns2[ i ] ) != 0 ) {
	    break;	/* DNs are not the same */
	}
    }

    rc = ( rdns1[ i ] == NULL && rdns2[ i ] == NULL );

    ldap_value_free( rdns1 );
    ldap_value_free( rdns2 );

    return( rc );
}


/*
 * Return the parent of dn.  The caller is responsible for freeing the
 * returned value.  Returns NULL on error.
 */
char *
dsgw_dn_parent( char *dn )
{
    char *dnp;
    int i;
    char **rdns;

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

    dnp = dsgw_ch_malloc( strlen( dn ));
    dnp[ 0 ] = '\0';
    if (( rdns = ldap_explode_dn( dn, 0 )) == NULL ) {
	return NULL;
    }
    for ( i = 1; rdns[ i ] != NULL; i++ ) {
	strcat( dnp, rdns[ i ] );
	strcat( dnp, "," );
    }
    /* Get rid of the trailing "," we just appended */
    dnp[ strlen( dnp ) - 1 ] = '\0';
    ldap_value_free( rdns );
    return( dnp );
}
    

/*
 * Return 1 if dn1 is the immediate ancestor of dn2, 0 otherwise.
 */
int
dsgw_is_dnparent( char *dn1, char *dn2 )
{
    char *dnp;
    int rc;

    /* A null or zero-length DN cannot have a parent */
    if ( dn2 == NULL || strlen( dn2 ) == 0 ) {
	return 0;
    }

    dnp = dsgw_dn_parent( dn2 );
    rc = dsgw_dn_cmp( dn1, dnp );
    free( dnp );

    return rc;
}


/*
 * return malloc'd array of RDN attribute value pairs
 * each element of the array is a string that looks like:  TAG=VALUE
 * this is used to extract values from the RDN when a new entry is added
 */
char **
dsgw_rdn_values( char *dn )
{
    char	**rdns, **rdncomps, *val;
    int		i;

    if (( rdns = ldap_explode_dn( dn, 0 )) == NULL ) {
	return( NULL );
    }

    rdncomps = ldap_explode_rdn( rdns[0], 0 );
    ldap_value_free( rdns );
    if ( rdncomps == NULL ) {
	return( NULL );
    }

    for ( i = 0; rdncomps[ i ] != NULL; ++i ) {
	if (( val = strchr( rdncomps[ i ], '=' )) == NULL ) {
	    ldap_value_free( rdncomps );
	    return( NULL );
	}
	++val;
	strcpy_special_undo( val, val );	/* undo in place */
    }

    return( rdncomps );
}


/*
 * the following routine was lifted from servers/slapd/ava.c
 * it removes special quoting, etc. from values that appear in an LDAP DN
 */
static void
strcpy_special_undo( char *d, char *s )
{
    int     quote;
 
    quote = 0;
    if ( *s == '"' ) {
	    s++;
	    quote = 1;
    }
    for ( ; *s; LDAP_UTF8INC(s)) {
	switch ( *s ) {
	case '"':
	    break;
	case '\\':
	    s++;
	    /* FALL */
	default:
	    d += LDAP_UTF8COPY (d, s);
	    break;
	}
    }
    *d = '\0'; LDAP_UTF8DEC(d);
    if ( quote && *d == '"' ) {
	*d = '\0';
    }
}


static char *
uid2dn( LDAP *ld, char *uid, char *base, int *ldaprc, char **lderrtxtp,
	char **errsp )
{
    char *attrs[] = { "objectclass", NULL };
    char filtbuf[ 85 ];	/* max of 80 char. uid + "uid=" + zero terminator */
    int rc, count;
    LDAPMessage *result;
    LDAPMessage *e;
    char *dn;
    
    *ldaprc = LDAP_SUCCESS;	/* optimistic */
    *errsp = *lderrtxtp = NULL;

    if ( ld == NULL || uid == NULL || strlen( uid ) > 80 ) {
	*errsp = XP_GetClientStr(DBT_invalidUserIdOrNullLdapHandle_);
	return NULL;
    }
    PR_snprintf( filtbuf, sizeof(filtbuf), "uid=%s", uid );

    if (( rc = ldap_search_s( ld, base, LDAP_SCOPE_SUBTREE, filtbuf,
	    attrs, 1, &result )) != LDAP_SUCCESS ) {
	*ldaprc = rc;
	(void)ldap_get_lderrno( ld, NULL, lderrtxtp );
	return NULL;
    }
    if (( count = ldap_count_entries( ld, result )) != 1 ) {
	/* Search either returned no entries, or more than one entry */
	ldap_msgfree( result );
	if ( count == 0 ) {
	    *errsp = XP_GetClientStr(DBT_noMatchForUserId_);
	} else {
	    *errsp = XP_GetClientStr(DBT_moreThanOneMatchForUserId_);
	}
	return NULL;
    }

    dn = NULL;
    if (( e = ldap_first_entry( ld, result )) == NULL ||
	    ( dn = ldap_get_dn( ld, e )) == NULL ) {
	*ldaprc = ldap_get_lderrno( ld, NULL, NULL );
    }
    ldap_msgfree( result );
    return( dn );
}


/*
 * Emit an HTML "SELECT" object that contains all the o's and ou's that
 * are underneath our default searchbase.  If there are none other than
 * the searchbase, we emit a hidden HTML TEXT object that contains the
 * searchbase and the "prefix" and "suffix" are not used.  The values for
 * the SELECT options and for the TEXT object are all escaped DNs.
 *  
 * Location popup directives look like this:
 *	<-- DS_LOCATIONPOPUP "name=VARNAME" "prefix=PREFIX" "suffix=SUFFIX" -->
 *
 * If "prefix" and/or "suffix" are omitted, they default to "".
 * If "name" is omitted it defaults to "base".
 *
 * If there are "location" directives in the dsgw.conf file, we use those
 * instead of actually searching the directory.
 */
void
dsgw_emit_location_popup( LDAP *ld, int argc, char **argv, int erropts )
{
    char	line[BIG_LINE];
    char	*varname, *prefix, *suffix, *rootname, *dn;
    int		i, count, did_init_ldap;
    LDAPMessage	*res, *e;

    if (( varname = get_arg_by_name( "name", argc, argv )) == NULL ) {
	varname = "base";
    }
    if (( prefix = get_arg_by_name( "prefix", argc, argv )) == NULL ) {
	prefix = "";
    }
    if (( suffix = get_arg_by_name( "suffix", argc, argv )) == NULL ) {
	suffix = "";
    }
    rootname = get_arg_by_name( "rootname", argc, argv );

    did_init_ldap = 0;
    res = NULL;

    if ( gc->gc_newentryloccount > 0 ) {
	count = gc->gc_newentryloccount;
    } else {
	char		*attrs[ 3 ];
	int		rc;

	if ( ld == NULL ) {
	    (void)dsgw_init_ldap( &ld, NULL, 0, 0 );
	    did_init_ldap = 1;
	}
	attrs[ 0 ] = "o";
	attrs[ 1 ] = "ou";
	attrs[ 2 ] = NULL;

	rc = ldap_search_s( ld, gc->gc_ldapsearchbase, LDAP_SCOPE_SUBTREE,
		"(|(objectclass=organization)(objectclass=organizationalunit))",
		attrs, 1, &res );
	if ( rc != LDAP_SUCCESS || res == NULL ) {
	    dsgw_ldap_error( ld, erropts );
	    return;
	}

	count = ldap_count_entries( ld, res );
	if ( gc->gc_ldapsearchbase == NULL || *gc->gc_ldapsearchbase == '\0' ) {
	    ++count;	/* include base DN even if it is "" */
	} else {
	    /*
	     * check to see if search base was one of the entries returned
	     * we want to always list the base entry, so we need to check
	     */
	    for ( e = ldap_first_entry( ld, res ); e != NULL;
		    e = ldap_next_entry( ld, e )) {
		if (( dn = ldap_get_dn( ld, e )) == NULL ) {
		    dsgw_ldap_error( ld, erropts );
		    ldap_msgfree( res );
		    return;
		}

		rc = dsgw_dn_cmp( dn, gc->gc_ldapsearchbase );
		free( dn );
		if ( rc ) {	/* base DN was returned */
		    break;
		}
	    }
	    if ( e == NULL ) {
		++count;	/* include base DN even if was not returned */
	    }
	}
    }

    if ( count > 1 ) {
	util_snprintf( line, sizeof(line), "%s\n<SELECT NAME=\"%s\">\n",
		prefix, varname );
    } else {
	util_snprintf( line, sizeof(line), "<INPUT TYPE=\"hidden\" NAME=\"%s\" ",
		varname );
    }
    dsgw_emits( line );

    if ( gc->gc_newentryloccount > 0 ) {
	for ( i = 0; i < gc->gc_newentryloccount; ++i ) {
	    emit_one_loc_dn( gc->gc_newentrylocs[ i ].dsloc_dnsuffix,
		    gc->gc_newentrylocs[i].dsloc_fullname, rootname,
		    ( count < 2 ));
	}
    } else {
	/* always include the base dn first */
	emit_one_loc_dn( gc->gc_ldapsearchbase, NULL, rootname, ( count < 2 ));

	/* XXXmcs it would be nice to do a more intelligent sort here */
#ifdef DSGW_DEBUG
	dsgw_log( "dsgw_emit_location_popup: ldap_sort_entries(NULL)\n" );
#endif
	ldap_sort_entries( ld, &res, NULL, dsgw_strcmp (CASE_INSENSITIVE));

	for ( e = ldap_first_entry( ld, res ); e != NULL;
		e = ldap_next_entry( ld, e )) {
	    if (( dn = ldap_get_dn( ld, e )) == NULL ) {
		dsgw_ldap_error( ld, erropts );
		ldap_msgfree( res );
		return;
	    }

	    if ( !dsgw_dn_cmp( dn, gc->gc_ldapsearchbase )) {
		emit_one_loc_dn( dn, NULL, rootname, ( count < 2 ));
	    }
	    free( dn );
	}
    }

    if ( count > 1 ) {
	util_snprintf( line, sizeof(line), "</SELECT>\n%s\n", suffix );
	dsgw_emits( line );
    }

    if ( res != NULL ) {
	ldap_msgfree( res );
    }
    if ( did_init_ldap ) {
	ldap_unbind( ld );
    }
}


static void
emit_one_loc_dn( char *dn, char *friendlyname, char *rootname, int only_one )
{
    char	*escapeddn, **rdns, line[ BIG_LINE ];

    rdns = NULL;
    escapeddn = dsgw_strdup_escaped( dn );

    if ( !only_one ) {
	dsgw_emits( "<OPTION" );
    }

    if ( friendlyname == NULL ) {	/* use first component of DN */
	if ( *dn == '\0' ) {
	    friendlyname = ( rootname == NULL ? XP_GetClientStr(DBT_theEntireDirectory_)
		    : rootname );
	} else if (( rdns = ldap_explode_dn( dn, 1 )) == NULL
		|| rdns[ 0 ] == NULL ) {
	    friendlyname = dn;
	} else {
	    friendlyname = rdns[ 0 ];
	}
    }

    util_snprintf( line, sizeof(line), " VALUE=\"%s\">%s\n", escapeddn,
	    only_one ? "" : friendlyname );
    free( escapeddn );
    if ( rdns != NULL ) {
	ldap_value_free( rdns );
    }
    dsgw_emits( line );
}


/*
 * Return a MIME document that contains a single value.
 * XXX:  does this really belong in ldaputil.c?
 */
static void
return_one_attr( LDAP *ld, LDAPMessage *entry, char *attrtype, char *mimetype,
	int valindex )
{
    char		*val;
    struct berval	**bvals;
    unsigned long	vlen;

    if (( bvals = ldap_get_values_len( ld, entry, attrtype )) == NULL ) {
	dsgw_error( DSGW_ERR_NOATTRVALUE, attrtype, DSGW_ERROPT_EXIT, 0, NULL );
    }

    if ( valindex > ldap_count_values_len( bvals )) {
	dsgw_error( DSGW_ERR_NOATTRVALUE, attrtype, DSGW_ERROPT_EXIT, 0, NULL );
    }

    val = bvals[ valindex ]->bv_val;
    vlen = bvals[ valindex ]->bv_len;

    fprintf( stdout, "Content-Type: %s\n", mimetype );
    fprintf( stdout, "Content-Length: %ld\n\n", vlen );

#ifdef XP_WIN32
    /* flush any data on stdout before changing the mode */
    fflush( stdout );

    /* set the mode to binary 
       so windows doesn't replace with carriage
       return line feed and mess everything up
    */
    _setmode( _fileno( stdout ), _O_BINARY );
#endif

    fwrite( val, vlen, 1, stdout );

#ifdef XP_WIN32
    /* flush any remaining binary data */
    fflush( stdout );

    /* set the mode back to text */
    _setmode( _fileno( stdout ), _O_TEXT );
#endif

    ldap_value_free_len( bvals );
    free( attrtype );
}


/*
 * The general format of attrtype is:
 *	<attrtype> [ &<mimetype> ] [ &<valindex> ]
 * This routine breaks it up.  Callers should free( *attrtypep ) after they
 * are done using attrtypep and mimetypep.
 */
static void
break_up_one_attr( char *attr, char **attrtypep, char **mimetypep,
	int *valindexp )
{
    char	*p;

    *attrtypep = dsgw_ch_strdup( attr );

    *mimetypep = "text/plain";	/* default */
    *valindexp = 0;		/* default: retrieve first value */

    if (( p = strchr( *attrtypep, '&' )) != NULL ) {
	*p++ = '\0';
	if ( *p != '\0' ) {
	    *mimetypep = p;
	    if (( p = strchr( *mimetypep, '&' )) != NULL ) {
		*p++ = '\0';
		*valindexp = atoi( p );
	    }
	}
    }
}