forked from ibv/LDAP-Admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLDAPClasses.pas
2331 lines (2151 loc) · 64.6 KB
/
LDAPClasses.pas
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
{ LDAPAdmin - LDAPClasses.pas
* Copyright (C) 2003-2016 Tihomir Karlovic
*
* Author: Tihomir Karlovic
*
* Modifications: Ivo Brhel, 2016
*
*
* This file 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; either version 2 of the License, or
* (at your option) any later version.
*
* This file 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
}
unit LDAPClasses;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$M+}
interface
uses
{$IFnDEF FPC}
Windows, WinLDAP,
{$ELSE}
LCLIntf, LCLType, LazUtils, LinLDAP, lDapSend, lazutf8,
{$ENDIF}
Sysutils, Classes, Events, Constant;
const
LdapOpRead = $FFFFFFFF;
LdapOpNoop = $FFFFFFFE;
LdapOpAdd = LDAP_MOD_ADD;
LdapOpReplace = LDAP_MOD_REPLACE;
LdapOpDelete = LDAP_MOD_DELETE;
SESS_TIMEOUT = 0;
SESS_SIZE_LIMIT = 0;
SESS_PAGE_SIZE = 100;
SESS_REFF_HOP_LIMIT = 32;
AUTH_SIMPLE = $00;
AUTH_GSS = $01;
AUTH_GSS_SASL = $03;
StandardOperationalAttributes = 'createTimestamp,' +
'modifyTimestamp,' +
'creatorsName,' +
'modifiersName,' +
'subschemaSubentry,' +
'structuralObjectClass,' +
'hasSubordinates,' +
'entryCSN,' +
'entryUUID';
LdapInvalidChars = ['=','+','"','\',',','>','<','#',';'];
LdapEscapableChars = LdapInvalidChars + [' ']; // Space is invalid only at the end or the beginning of the sting
type
ErrLDAP = class(Exception);
PBytes = array of Byte;
PCharArray = array of PChar;
PPLDAPMod = array of PLDAPMod;
PPLdapBerValA = array of PLdapBerVal;
TLdapAttributeData = class;
TLdapAttribute = class;
TLdapAttributeList = class;
TLdapEntry = class;
TLdapEntryList = class;
TDataType = (dtUnknown, dtText, dtBinary, dtJpeg, dtCert);
TLdapAttributeStates = set of (asNew, asBrowse, asModified, asDeleted);
TLdapEntryStates = set of (esNew, esBrowse, esReading, esWriting, esModified, esDeleted);
TLdapAttributeSortType = (AT_Attribute, AT_DN, AT_RDN, AT_Path);
TSearchCallback = procedure (Sender: TLdapEntryList; var AbortSearch: Boolean) of object;
TCompareLdapEntry = procedure(Entry1, Entry2: TLdapEntry; Data: pointer; out Result: Integer) of object;
TDataNotifyEvent = procedure(Sender: TLdapAttributeData) of object;
TLdapAuthMethod = Integer;
TLdapAttributeData = class
private
fBerval: record
Bv_Len: Cardinal;
Bv_Val: PBytes;
end;
fAttribute: TLdapAttribute;
fEntry: TLdapEntry;
fModOp: Cardinal;
//fType: TDataType; there is no need to determine this on per value basis
fUtf8: Boolean;
function GetType: TDataType;
function GetString: string;
procedure SetString(AValue: string);
function BervalAddr: PLdapBerval;
public
constructor Create(Attribute: TLdapAttribute); virtual;
function CompareData(P: Pointer; Length: Integer): Boolean;
procedure SetData(AData: Pointer; ADataSize: Cardinal);
procedure Delete;
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
property DataType: TDataType read GetType;
property AsString: string read GetString write SetString;
property DataSize: Cardinal read fBerval.Bv_Len;
property Data: PBytes read fBerval.Bv_Val;
property Berval: PLdapBerval read BervalAddr;
property ModOp: Cardinal read fModOp;
property Attribute: TLdapAttribute read fAttribute;
end;
TLdapAttribute = class
private
fState: TLdapAttributeStates;
fName: string;
fValues: TList;
fOwnerList: TLdapAttributeList;
fEntry: TLdapEntry;
fDataType: TDataType;
function GetCount: Integer;
function GetValue(Index: Integer): TLdapAttributeData;
function GetString: string;
procedure SetString(AValue: string);
function GetDataType: TDataType;
function GetEmpty: Boolean;
public
constructor Create(const AName: string; OwnerList: TLdapAttributeList); virtual;
destructor Destroy; override;
function AddValue: TLdapAttributeData; overload;
procedure AddValue(const AValue: string); overload; virtual;
procedure AddValue(const AData: Pointer; const ADataSize: Cardinal); overload; virtual;
procedure DeleteValue(const AValue: string); virtual;
procedure Delete;
function IndexOf(const AValue: string): Integer; overload;
function IndexOf(const AData: Pointer; const ADataSize: Cardinal): Integer; overload;
property Values[Index: Integer]: TLdapAttributeData read GetValue; default;
published
property State: TLdapAttributeStates read fState;
property Name: string read fName;
property ValueCount: Integer read GetCount;
property AsString: string read GetString write SetString;
property Entry: TLdapEntry read fEntry;
property DataType: TDataType read GetDataType;
property Empty: Boolean read GetEmpty;
end;
TLdapAttributeList = class
private
fList: TList;
fEntry: TLdapEntry;
function GetCount: Integer;
function GetNode(Index: Integer): TLdapAttribute;
public
constructor Create(Entry: TLdapEntry); virtual;
destructor Destroy; override;
function Add(const AName: string): TLdapAttribute;
function IndexOf(const Name: string): Integer;
function AttributeOf(const Name: string): TLdapAttribute;
procedure Clear;
property Items[Index: Integer]: TLdapAttribute read GetNode; default;
property Count: Integer read GetCount;
end;
TLDAPSession = class
private
{$ifdef mswindows}
ldappld: PLDAP;
{$else}
ldappld: TLDAPsend;
{$endif}
ldapServer: string;
ldapUser, ldapPassword: string;
ldapPort: Integer;
ldapVersion: Integer;
ldapBase: string;
ldapSSL: Boolean;
ldapTLS: Boolean;
ldapAuthMethod: TLdapAuthMethod;
fTimeLimit: Integer;
fSizeLimit: Integer;
fPagedSearch: Boolean;
fPageSize: Integer;
fDerefAliases: Integer;
fChaseReferrals: Boolean;
fReferralHops: Integer;
fOnConnect: TNotifyEvents;
fOnDisconnect: TNotifyEvents;
fOperationalAttrs: PCharArray;
procedure LDAPCheck(const err: ULONG; const Critical: Boolean = true);
procedure SetServer(Server: string);
procedure SetUser(User: string);
procedure SetPassword(Password: string);
procedure SetPort(Port: Integer);
procedure SetVersion(Version: Integer);
procedure SetConnect(DoConnect: Boolean);
procedure SetSSL(Value: Boolean);
procedure SetTLS(Value: Boolean);
procedure SetLdapAuthMethod(Method: TLdapAuthMethod);
procedure SetTimeLimit(const Value: Integer);
procedure SetSizeLimit(const Value: Integer);
procedure SetDerefAliases(const Value: Integer);
procedure SetChaseReferrals(const Value: boolean);
procedure SetReferralHops(const Value: Integer);
function GetOperationalAttrs: string;
procedure SetOperationalAttrs(const Value: string);
{$ifdef mswindows}
procedure ProcessSearchEntry(const plmEntry: PLDAPMessage; Attributes: TLdapAttributeList);
procedure ProcessSearchMessage(const plmSearch: PLDAPMessage; const NoValues: LongBool; Result: TLdapEntryList);
{$else}
procedure ProcessSearchEntry(const plmEntry: TLDAPResult; Attributes: TLdapAttributeList);
procedure ProcessSearchMessage(const plmSearch: TLDAPsend; const NoValues: LongBool; Result: TLdapEntryList);
{$endif}
protected
function ISConnected: Boolean; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Connect; virtual;
procedure Disconnect; virtual;
{$ifdef mswindows}
property pld: PLDAP read ldappld;
{$else}
property pld: TLDAPsend read ldappld;
{$endif}
property Server: string read ldapServer write SetServer;
property User: string read ldapUser write SetUser;
property Password: string read ldapPassword write SetPassword;
property Port: Integer read ldapPort write SetPort;
property Version: Integer read ldapVersion write SetVersion;
property SSL: Boolean read ldapSSL write SetSSL;
property TLS: Boolean read ldapTLS write SetTLS;
property AuthMethod: TLdapAuthMethod read ldapAuthMethod write SetLdapAuthMethod;
property Base: string read ldapBase write ldapBase;
property TimeLimit: Integer read fTimeLimit write SetTimeLimit;
property SizeLimit: Integer read fSizeLimit write SetSizeLimit;
property PagedSearch: Boolean read fPagedSearch write fPagedSearch;
property PageSize: Integer read fPageSize write fPageSize;
property DereferenceAliases: Integer read fDerefAliases write SetDerefAliases;
property ChaseReferrals: Boolean read fChaseReferrals write SetChaseReferrals;
property ReferralHops: Integer read fReferralHops write SetReferralHops;
property Connected: Boolean read IsConnected write SetConnect;
function Lookup(sBase, sFilter, sResult: string; Scope: ULONG): string; virtual;
function GetDn(sFilter: string): string; virtual;
procedure Search(const Filter, Base: string; const Scope: Cardinal; QueryAttrs: array of string; const NoValues: LongBool; Result: TLdapEntryList; SearchProc: TSearchCallback = nil); overload;
procedure Search(const Filter, Base: string; const Scope: Cardinal; attrs: PCharArray; const NoValues: LongBool; Result: TLdapEntryList; SearchProc: TSearchCallback = nil); overload; virtual;
procedure ModifySet(const Filter, Base: string;
const Scope: Cardinal;
argNames: array of string;
argVals: array of string;
argNewVals: array of string;
const ModOp: Cardinal);
procedure WriteEntry(Entry: TLdapEntry); virtual;
procedure ReadEntry(Entry: TLdapEntry); virtual;
procedure DeleteEntry(const adn: string); virtual;
property OnConnect: TNotifyEvents read FOnConnect;
property OnDisconnect: TNotifyEvents read FOnDisconnect;
property OperationalAttrs: string read GetOperationalAttrs write SetOperationalAttrs;
end;
TLDAPEntry = class
private
fSession: TLDAPSession;
fdn: string;
fAttributes: TLdapAttributeList;
fOperationalAttributes: TLdapAttributeList;
fObjectClass: TLdapAttribute;
fState: TLdapEntryStates;
fOnChangeProc: TDataNotifyEvent;
fOnRead: TNotifyEvent;
fOnWrite: TNotifyEvent;
function GetNamedAttribute(const AName: string): TLdapAttribute;
function GetObjectClass: TLdapAttribute;
protected
procedure SetDn(const adn: string);
procedure SetUtf8Dn(const adn: AnsiString);
function GetUtf8Dn: AnsiString;
public
ObjectId: Integer;
property Session: TLDAPSession read fSession;
constructor Create(const ASession: TLDAPSession; const adn: string); virtual;
destructor Destroy; override;
procedure Read; virtual;
procedure Write; virtual;
procedure Delete; virtual;
procedure Clone(ToEntry: TLdapEntry); virtual;
property Attributes: TLdapAttributeList read fAttributes;
property AttributesByName[const Name: string]: TLdapAttribute read GetNamedAttribute;
property OperationalAttributes: TLdapAttributeList read fOperationalAttributes;
published
{ dn is internally saved as escaped LDAP string, as returned from LDAP server.
We cannot encode dn on write, since we cannot decide reliably if the
particular ',' or '=' character should be escaped or not. This means that we
have to deal with encoding before we assign a value to the dn property which
is basically only when we deal with a user input. And, since vast majority of
dn assignments happens internally we have an advantage of no performance impact }
property dn: string read fdn write SetDn;
{ To avoid perpetual conversions, fdn is internaly coded as UNICODE and not as
Utf8. The ldap_add_s and ldap_modify_s Windows API functions need no converting,
since the corresponding API UNICODE functions, which insure propper handling,
are called. That leavs us with neccessity to convert dn specificaly to UTF8
for base64 encoding when exporting entry to LDIF or DSML, hence utf8dn property }
property utf8dn: AnsiString read GetUtf8Dn write SetUtf8Dn;
property State: TLdapEntryStates read fState;
property OnChange: TDataNotifyEvent read fOnChangeProc write fOnChangeProc;
property OnRead: TNotifyEvent read fOnRead write fOnRead;
property OnWrite: TNotifyEvent read fOnWrite write fOnWrite;
property ObjectClass: TLdapAttribute read GetObjectClass;
end;
TLdapEntryList = class
private
fList: TList;
fOwnsEntries: Boolean;
function GetCount: Integer;
function GetNode(Index: Integer): TLdapEntry;
public
constructor Create(AOwnsObjects: Boolean = true);
destructor Destroy; override;
procedure Add(Entry: TLdapEntry);
procedure Delete(Index: Integer);
procedure Extract(Index: Integer);
procedure Clear;
function IndexOf(adn: string): Integer;
property Items[Index: Integer]: TLdapEntry read GetNode; default;
property Count: Integer read GetCount;
procedure Sort(const Attributes: array of string; const Asc: boolean); overload;
procedure Sort(const Compare: TCompareLdapEntry; const Asc: boolean; const Data: pointer=nil); overload;
property OwnsEntries: Boolean read fOwnsEntries write fOwnsEntries;
end;
{ Name handling routines }
function DecodeLdapString(const Src: string; const Escape: Char ='\'): string;
function EncodeLdapString(const Src: string; const Escape: Char ='\'): string;
function IsValidDn(Value: string): Boolean;
function CanonicalName(dn: string): string;
procedure SplitRdn(const dn: string; var attrib, value: string);
function GetAttributeFromDn(const dn: string): string;
function GetNameFromDn(const dn: string): string;
function GetRdnFromDn(const dn: string): string;
function GetDirFromDn(const dn: string): string;
function GetAttributeSortType(Attribute: string): TLdapAttributeSortType;
const
PSEUDOATTR_DN = '*DN*';
PSEUDOATTR_RDN = '*RDN*';
PSEUDOATTR_PATH = '*PATH*';
var
RawLdapStrings: Boolean = false;
implementation
{$I LdapAdmin.inc}
uses Misc, Input, Dialogs, Cert, Gss{$IFDEF VER_XEH}, System.UITypes{$ENDIF};
{ Name handling routines }
function DecodeLdapString(const Src: string; const Escape: Char ='\'): string;
var
i, d, l: Integer;
begin
Result := Src;
if RawLdapStrings then
exit;
l := Length(Src);
if l = 0 then
exit;
i := 1;
d := 1;
while i < l do
begin
if Src[i] = Escape then
begin
Delete(Result, d, 1);
inc(i);
if not (Src[i] in LdapEscapableChars) then
begin
HexToBin(PChar(@Src[i]), @Result[d], 1);
inc(i);
Delete(Result, d + 1, 1);
end;
end;
inc(d);
inc(i);
end;
end;
function EncodeLdapString(const Src: string; const Escape: Char ='\'): string;
var
i, d, l: Integer;
begin
Result := Src;
if RawLdapStrings then
exit;
l := Length(Src);
if l = 0 then
exit;
d := 2;
for i := 2 to l - 1 do
begin
if Src[i] in LdapInvalidChars then
begin
Insert(Escape, Result, d);
inc(d);
end;
inc(d);
end;
if Src[1] in LdapEscapableChars then
Insert(Escape, Result, 1);
if Src[l] in LdapEscapableChars then
Insert(Escape, Result, Length(Result));
end;
{$ifdef mswindows}
function IsValidDn(Value: string): Boolean;
var
i: Integer;
comp: PPChar;
begin
i := 0;
comp := ldap_explode_dn(PChar(Value), 0);
if Assigned(comp) then
while PCharArray(comp)[i] <> nil do
begin
if StrScan(PCharArray(comp)[i], '=') = nil then
break;
inc(i);
end;
Result := PCharArray(comp)[i] = nil;
ldap_value_free(comp);
end;
function CanonicalName(dn: string): string;
var
comp: PPChar;
i: Integer;
begin
Result := '';
comp := ldap_explode_dn(PChar(dn), 1);
i := 0;
if Assigned(comp) then
while PCharArray(comp)[i] <> nil do
begin
Result := Result + PCharArray(comp)[i] + '/';
inc(i);
end;
ldap_value_free(comp);
end;
{$else}
function IsValidDn(Value: string): Boolean;
var
i: Integer;
comp: TStringList;
begin
result:=true;
comp:=TStringList.Create;
if ldap_explode_dn(PChar(Value), 0, comp) then
for i:=0 to comp.Count-1 do
begin
if StrScan(PChar(comp[i]), '=') = nil then
begin
result:=false;
break;
end;
end;
comp.Free;
end;
function CanonicalName(dn: string): string;
var
comp: TStringList;
i: Integer;
begin
Result := '';
comp:=TStringList.Create;
if ldap_explode_dn(PChar(dn), 1, comp) then
for i:=0 to comp.Count-1 do
begin
Result := Result + comp[i] + '/';
end;
comp.Free;
end;
{$endif}
function SkipEscaped(p: PChar): PChar; inline;
begin
Result := CharNext(p);
if Result^ = #0 then
exit;
if not (Result^ in LdapEscapableChars) then
begin
Result := CharNext(p); // skip the two-byte hex code
if Result^ = #0 then
exit;
Result := CharNext(p);
end;
end;
procedure SplitRdn(const dn: string; var attrib, value: string);
var
p, p0, p1: PChar;
begin
p := PChar(dn);
p0 := p;
while (p^ <> #0) and (p^ <> '=') do
p := CharNext(p);
SetString(attrib, p0, p - p0);
p := CharNext(p);
p1 := p;
while (p1^ <> #0) and (p1^ <> ',') do
begin
if p1^ = '\' then
begin
p1 := SkipEscaped(p1);
if p1^ = #0 then
break;
end;
p1 := CharNext(p1);
end;
SetString(value, P, P1 - P);
end;
function GetAttributeFromDn(const dn: string): string;
var
p, p1: PChar;
begin
p := PChar(dn);
p1 := p;
while (p1^ <> #0) and (p1^ <> '=') do
p1 := CharNext(p1);
SetString(Result, P, P1 - P);
end;
function GetNameFromDn(const dn: string): string;
var
p, p1: PChar;
begin
p := PChar(dn);
while (p^ <> #0) and (p^ <> '=') do
p := CharNext(p);
p := CharNext(p);
p1 := p;
while (p1^ <> #0) and (p1^ <> ',') do
begin
if p1^ = '\' then
begin
p1 := SkipEscaped(p1);
if p1^ = #0 then
break;
end;
p1 := CharNext(p1);
end;
SetString(Result, P, P1 - P);
end;
function GetRdnFromDn(const dn: string): string;
var
p, p1: PChar;
begin
p := PChar(dn);
p1 := p;
while (p1^ <> #0) and (p1^ <> ',') do
begin
if p1^ = '\' then
begin
p1 := SkipEscaped(p1);
if p1^ = #0 then
break;
end;
p1 := CharNext(p1);
end;
SetString(Result, P, P1 - P);
end;
function GetDirFromDn(const dn: string): string;
var
p: PChar;
begin
p := PChar(dn);
while (p^ <> #0) do
begin
if p^ = '\' then
begin
p := SkipEscaped(p);
if p^ = #0 then
break;
end
else
if (p^ = ',') then
begin
p := CharNext(p);
break;
end;
p := CharNext(p);
end;
Result := p;
end;
function GetAttributeSortType(Attribute: string): TLdapAttributeSortType;
begin
if Attribute=PSEUDOATTR_DN then result:=AT_DN else
if Attribute=PSEUDOATTR_RDN then result:=AT_RDN else
if Attribute=PSEUDOATTR_PATH then result:=AT_Path else
result:=AT_Attribute;
end;
{ TLdapSession }
procedure TLdapSession.LDAPCheck(const err: ULONG; const Critical: Boolean = true);
var
ErrorEx: PChar;
msg: string;
begin
if (err = LDAP_SUCCESS) then exit;
if ((ldap_get_option(pld, LDAP_OPT_SERVER_ERROR, @ErrorEx)=LDAP_SUCCESS) and Assigned(ErrorEx)) then
begin
{$ifdef mswindows}
msg := Format(stLdapErrorEx, [ldap_err2string(err), ErrorEx]);
{$else}
msg := Format(stLdapErrorEx, [ldap_err2string(pld,err), ErrorEx]);
{$endif}
ldap_memfree(ErrorEx);
end
else
{$ifdef mswindows}
msg := Format(stLdapError, [ldap_err2string(err)]);
{$else}
msg := Format(stLdapError, [ldap_err2string(pld,err)]);
{$endif}
if Critical then
raise ErrLDAP.Create(msg);
MessageDlg(msg, mtError, [mbOk], 0);
end;
{$ifdef mswidnows}
procedure TLdapSession.ProcessSearchEntry(const plmEntry: PLDAPMessage; Attributes: TLdapAttributeList);
{$else}
procedure TLdapSession.ProcessSearchEntry(const plmEntry: TLDAPResult; Attributes: TLdapAttributeList);
{$endif}
var
Attr: TLdapAttribute;
i,j: Integer;
pszAttr:string;
pszdn: string;
pbe: PBerElement;
ppBer: PPLdapBerVal;
data: TLDAPAttributeData;
begin
// loop thru attributes
{$ifdef mswindows}
pszAttr := ldap_first_attribute(pld, plmEntry, pbe);
while Assigned(pszAttr) do
begin
Attr := Attributes.Add(pszattr);
Attr.fState := Attr.fState + [asBrowse];
// get value
ppBer := ldap_get_values_len(pld, plmEntry, pszAttr);
if Assigned(ppBer) then
try
i := 0;
while Assigned(PPLdapBervalA(ppBer)[i]) do
begin
Attr.AddValue(PPLdapBervalA(ppBer)[i]^.bv_val, PPLdapBervalA(ppBer)[i]^.bv_len);
Inc(I);
end;
finally
LDAPCheck(ldap_value_free_len(ppBer), false);
end;
ber_free(pbe, 0);
pszAttr := ldap_next_attribute(pld, plmEntry, pbe);
end;
{$else}
for i := 0 to plmEntry.Attributes.Count - 1 do
begin
pszAttr := plmEntry.Attributes[i].AttributeName;
Attr := Attributes.Add(pszAttr);
Attr.fState := Attr.fState + [asBrowse];
for j:=0 to plmEntry.Attributes[i].Count-1 do
begin
pszdn:= plmEntry.Attributes[i][j];
data:=TLdapAttributeData.Create(Attr);
if plmEntry.Attributes[i].IsBinary then
data:=@pszdn[1]
else
data.AsString:=trim(pszdn);
Attr.AddValue(data.Data,data.DataSize);
end;
end;
{$endif}
end;
{$ifdef mswindows}
procedure TLDAPSession.ProcessSearchMessage(const plmSearch: PLDAPMessage; const NoValues: LongBool; Result: TLdapEntryList);
{$else}
procedure TLDAPSession.ProcessSearchMessage(const plmSearch: TLDAPsend; const NoValues: LongBool; Result: TLdapEntryList);
{$endif}
var
{$ifdef mswindows}
plmEntry: PLDAPMessage;
pszdn: PChar;
{$else}
plmEntry: TLDAPResult;
pszdn: string;
{$endif}
Entry: TLdapEntry;
i,j : integer;
begin
try
{$ifdef mswindows}
// loop thru entries
plmEntry := ldap_first_entry(pld, plmSearch);
while Assigned(plmEntry) do
begin
pszdn := ldap_get_dn(pld, plmEntry);
Entry := TLdapEntry.Create(Self, pszdn);
Result.Add(Entry);
if not NoValues then
begin
Entry.fState := [esReading];
try
ProcessSearchEntry(plmEntry, Entry.Attributes);
Entry.fState := Entry.fState + [esBrowse];
finally
Entry.fState := Entry.fState - [esReading];
end;
end;
if Assigned(pszdn) then
ldap_memfree(pszdn);
plmEntry := ldap_next_entry(pld, plmEntry);
end;
{$else}
if plmSearch=nil then exit;
for i:=0 to plmSearch.SearchResult.Count -1 do
begin
pszdn:= plmSearch.SearchResult[i].ObjectName;
Entry := TLdapEntry.Create(Self, pszdn);
Result.Add(Entry);
if not NoValues then
begin
Entry.fState := [esReading];
try
ProcessSearchEntry(plmSearch.SearchResult[i], Entry.Attributes);
Entry.fState := Entry.fState + [esBrowse];
finally
Entry.fState := Entry.fState - [esReading];
end;
end;
end;
{$endif}
finally
// free search results
{$ifdef mswindows}
LDAPCheck(ldap_msgfree(plmSearch), false);
{$endif}
end;
end;
procedure TLDAPSession.Search(const Filter, Base: string; const Scope: Cardinal; attrs: PCharArray; const NoValues: LongBool; Result: TLdapEntryList; SearchProc: TSearchCallback = nil);
var
{$ifdef mswindows}
plmSearch: PLDAPMessage;
{$else}
plmSearch: TLDAPsend;
{$endif}
Err: Integer;
ServerControls: PLDAPControl;
ClientControls: PLDAPControl;
SortKeys: PLDAPSortKey;
HSrch: PLDAPSearch;
TotalCount: Cardinal;
Timeout: LDAP_TIMEVAL;
AbortSearch: Boolean;
begin
if not fPagedSearch then
begin
Err := ldap_search_s(pld, PChar(Base), Scope, PChar(Filter), PChar(attrs), Ord(NoValues), plmSearch);
if Err = LDAP_SIZELIMIT_EXCEEDED then
{$ifdef mswindows}
MessageDlg(ldap_err2string(err), mtWarning, [mbOk], 0)
{$else}
MessageDlg(ldap_err2string(pld,err), mtWarning, [mbOk], 0)
{$endif}
else
LdapCheck(Err);
ProcessSearchMessage(pld, NoValues, Result);
Exit;
end;
ServerControls:=nil;
ClientControls:=nil;
SortKeys:=nil;
hsrch:=ldap_search_init_page(pld, PChar(Base), Scope, PChar(Filter), PChar(attrs), Ord(NoValues),
ServerControls, ClientControls, 60, SizeLimit, SortKeys);
if not Assigned(hsrch) then
begin
Err := LdapGetLastError;
if Err <> LDAP_NOT_SUPPORTED then
LdapCheck(Err); // raises exception
fPagedSearch := false;
LdapCheck(ldap_search_s(pld, PChar(Base), Scope, PChar(Filter), PChar(attrs), Ord(NoValues), plmSearch)); // try ordinary search
ProcessSearchMessage(pld, NoValues, Result);
Exit;
end;
Timeout.tv_sec := 60;
TotalCount := 1;
while true do
begin
Err := ldap_get_next_page_s(pld, hsrch, Timeout, fPageSize, TotalCount, plmSearch);
case Err of
LDAP_UNAVAILABLE_CRIT_EXTENSION, LDAP_UNWILLING_TO_PERFORM:
begin
fPagedSearch := false;
ldap_search_abandon_page(hsrch);
LdapCheck(ldap_search_s(pld, PChar(Base), Scope, PChar(Filter), PChar(attrs), Ord(NoValues), plmSearch)); // try ordinary search
ProcessSearchMessage(pld, NoValues, Result);
Break;
end;
LDAP_NO_RESULTS_RETURNED, LDAP_SIZELIMIT_EXCEEDED:
begin
if Err = LDAP_SIZELIMIT_EXCEEDED then
begin
ProcessSearchMessage(pld, NoValues, Result);
{$ifdef mswindows}
MessageDlg(ldap_err2string(err), mtWarning, [mbOk], 0)
{$else}
MessageDlg(ldap_err2string(pld,err), mtWarning, [mbOk], 0);
{$endif}
end;
LdapCheck(ldap_search_abandon_page(hsrch));
break;
end;
LDAP_SUCCESS:
begin
if not Assigned(plmSearch) then
Continue;
ProcessSearchMessage(pld, NoValues, Result);
if Assigned(SearchProc) then
begin
AbortSearch := false;
SearchProc(Result, AbortSearch);
if AbortSearch then
begin
LdapCheck(ldap_search_abandon_page(hsrch));
break;
end;
end;
end
else
LdapCheck(Err);
end;
end;
end;
procedure TLdapSession.Search(const Filter, Base: string; const Scope: Cardinal; QueryAttrs: array of string; const NoValues: LongBool; Result: TLdapEntryList; SearchProc: TSearchCallback = nil);
var
attrs: PCharArray;
len: Integer;
begin
attrs := nil;
len := Length(QueryAttrs);
if Len > 0 then
begin
SetLength(attrs, len + 1);
attrs[len] := nil;
repeat
dec(len);
attrs[len] := PChar(QueryAttrs[len]);
until len = 0;
end;
Search(Filter, Base, Scope, attrs, NoValues, Result, SearchProc);
end;
{ Modify set of attributes in every entry set returned by search filter }
procedure TLdapSession.ModifySet(const Filter, Base: string;
const Scope: Cardinal;
argNames: array of string;
argVals: array of string;
argNewVals: array of string;
const ModOp: Cardinal);
var
List: TLdapEntryList;
attrs: PCharArray;
Entry: TLDapEntry;
h, i: Integer;
begin
List := TLdapEntryList.Create;
try
h := High(argNames);
SetLength(attrs, h + 2);
for i := 0 to High(argNames) do
attrs[i] := PChar(argNames[i]);
attrs[h + 1] := nil;
Search(Filter, Base, Scope, attrs, false, List);
for i := 0 to List.Count - 1 do
begin
Entry := TLdapEntry(List[i]);
for h := 0 to High(argNames) do with Entry.AttributesByName[argNames[h]] do
begin
case ModOp of
LdapOpDelete: DeleteValue(argVals[h]);
LdapOpAdd: AddValue(argNewVals[h]);
LdapOpReplace: if IndexOf(argVals[h]) <> -1 then
begin
DeleteValue(argVals[h]);
AddValue(argNewVals[h]);
end;
end;
Entry.Write;
end;
end;
finally
List.Free;
end;
end;
{$ifdef mswindows}
procedure TLDAPSession.WriteEntry(Entry: TLdapEntry);
var
i, j, acnt, addidx, delidx, repidx: Integer;
attrs: PPLDapMod;
AttributeList: TLdapAttributeList;
procedure ValueModOp(AValue: TLdapAttributeData; var idx: Integer);
var
pix: Integer;
begin
if idx < 0 then // new entry
begin
if acnt = High(attrs) then // we need trailing NULL
SetLength(attrs, acnt + 10); // expand array if neccessary
idx := acnt;
GetMem(attrs[acnt], SizeOf(LDAPMod));
with attrs[acnt]^ do
begin
mod_op := AValue.ModOp or LDAP_MOD_BVALUES;
mod_type := PChar(AValue.fAttribute.Name);
modv_bvals := nil; // MUST be nil before call to SetLength!
SetLength(PPLdapBervalA(modv_bvals), 2);
PPLdapBervalA(modv_bvals)[0] := AValue.BerVal;
PPLdapBervalA(modv_bvals)[1] := nil; // trailing NULL
end;
Inc(acnt);
end
else
begin
with attrs[idx]^ do
begin
pix := Length(PPLdapBervalA(modv_bvals));
PPLdapBervalA(modv_bvals)[pix - 1] := AValue.BerVal;
Setlength(PPLdapBervalA(modv_bvals), pix + 1);
PPLdapBervalA(modv_bvals)[pix] := nil; // trailing NULL
end;
end;
end;
procedure DeleteAll(const AttributeName: string);
begin
if acnt = High(attrs) then // we need trailing NULL
SetLength(attrs, acnt + 10); // expand array if neccessary
GetMem(attrs[acnt], SizeOf(LDAPMod));
with attrs[acnt]^ do
begin
mod_op := LDAP_MOD_DELETE;
mod_type := PChar(AttributeName);
modv_bvals := nil;
end;
Inc(acnt);
end;
begin