/
eldap.erl
2023 lines (1773 loc) · 67.5 KB
/
eldap.erl
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
-module(eldap).
-moduledoc """
LDAP Client
This module provides a client api to the Lightweight Directory Access Protocol
(LDAP).
References:
- RFC 4510 - RFC 4519
- RFC 2830
The above publications can be found at [IETF](http://www.ietf.org).
Terminology abbreviations:
- Dn. An LDAPDN is defined to be the representation of a Distinguished Name
(DN) after encoding according to the specification in [RFC4514].
""".
-doc """
The LDAP socket and the transport protocol, TCP or TLS (SSL), used by the ldap connection
""".
-type connection_info() :: #{socket := ssl:sslsocket() | gen_tcp:socket(), socket_type := tcp | ssl}.
-doc """
A requested set of serach options for seaching the directory
""".
-type search_option() ::
{base, string()} |
{filter, filter()} |
{scope, scope()} |
{attributes, [string()]} |
{deref, dereference()} |
{types_only, boolean()} |
{timeout, integer()}.
-doc "An opaque handle unique for the connection".
-type handle() :: term().
-doc "The attributes of an entry".
-type attribute() :: {Type :: string(), Value :: [string()]}.
-doc """
Entry modification operations.
See `mod_add/2`, `mod_delete/2`, `mod_replace/2`
""".
-type modify_op() :: term().
-doc """
Scope of a search.
See `baseObject/0`, `singleLevel/0`, `wholeSubtree/0`
""".
-opaque scope() :: baseObject | singleLevel | wholeSubtree.
-doc """
How to handle aliases during a search.
See `neverDerefAliases/0`, `derefInSearching/0`, `derefFindingBaseObj/0`, `derefAlways/0`
""".
-opaque dereference() :: neverDerefAliases | derefInSearching | derefFindingBaseObj | derefAlways.
-doc """
An opaque type representing a filter operation.
See the filter creation functions for more info, including,
`present/1`, `substrings/2`, `equalityMatch/2`,
`greaterOrEqual/2`, `lessOrEqual/2`,
`approxMatch/2`, `extensibleMatch/2`,
`'and'/1`, `'or'/1`, `'not'/1`
""".
-type filter() :: term().
-doc """
The LDAP Server Address.
The contents of `Address` is server dependent.
""".
-type referrals() :: [Address :: string()].
-export_type([scope/0, dereference/0]).
-moduledoc(#{since => "OTP R15B01"}).
%%% --------------------------------------------------------------------
%%% Created: 12 Oct 2000 by Tobbe <tnt@home.se>
%%% Function: Erlang client LDAP implementation according RFC 2251,2253
%%% and 2255. The interface is based on RFC 1823, and
%%% draft-ietf-asid-ldap-c-api-00.txt
%%%
%%% Copyright (c) 2010 Torbjorn Tornkvist
%%% Copyright Ericsson AB 2011-2013. All Rights Reserved.
%%% See MIT-LICENSE at the top dir for licensing information.
%%% --------------------------------------------------------------------
-vc('$Id$ ').
-export([open/1, open/2,
simple_bind/3, simple_bind/4,
controlling_process/2,
start_tls/2, start_tls/3, start_tls/4,
modify_password/3, modify_password/4, modify_password/5,
getopts/2,
baseObject/0,singleLevel/0,wholeSubtree/0,close/1,
equalityMatch/2,greaterOrEqual/2,lessOrEqual/2,
extensibleMatch/2,
search/2, search/3,
approxMatch/2,substrings/2,present/1,
'and'/1,'or'/1,'not'/1,mod_add/2, mod_delete/2,
mod_replace/2,
modify/3, modify/4,
add/3, add/4,
delete/2, delete/3,
modify_dn/5,parse_dn/1,
parse_ldap_url/1,
paged_result_control/1,
paged_result_control/2,
paged_result_cookie/1,
info/1]).
-export([neverDerefAliases/0, derefInSearching/0,
derefFindingBaseObj/0, derefAlways/0]).
%% for upgrades
-export([loop/2]).
-import(lists,[concat/1]).
-include("ELDAPv3.hrl").
-include("eldap.hrl").
-define(LDAP_VERSION, 3).
-define(LDAP_PORT, 389).
-define(LDAPS_PORT, 636).
-record(eldap, {version = ?LDAP_VERSION,
host, % Host running LDAP server
port = ?LDAP_PORT, % The LDAP server port
fd, % Socket filedescriptor.
prev_fd, % Socket that was upgraded by start_tls
binddn = "", % Name of the entry to bind as
passwd, % Password for (above) entry
id = 0, % LDAP Request ID
log, % User provided log function
timeout = infinity, % Request timeout
anon_auth = false, % Allow anonymous authentication
ldaps = false, % LDAP/LDAPS
using_tls = false, % true if LDAPS or START_TLS executed
tls_opts = [], % ssl:ssloption()
tcp_opts = [] % inet6 support
}).
%%% For debug purposes
%%-define(PRINT(S, A), io:fwrite("~w(~w): " ++ S, [?MODULE,?LINE|A])).
-define(PRINT(S, A), true).
-define(elog(S, A), error_logger:info_msg("~w(~w): "++S,[?MODULE,?LINE|A])).
%%% ====================================================================
%%% Exported interface
%%% ====================================================================
%%% --------------------------------------------------------------------
%%% open(Hosts [,Opts] )
%%% --------------------
%%% Setup a connection to on of the Hosts in the argument
%%% list. Stop at the first successful connection attempt.
%%% Valid Opts are: Where:
%%%
%%% {port, Port} - Port is the port number
%%% {log, F} - F(LogLevel, FormatString, ListOfArgs)
%%% {timeout, milliSec} - Server request timeout
%%%
%%% --------------------------------------------------------------------
-doc """
Setup a connection to an LDAP server, the `HOST`'s are tried in order.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec open(Hosts) -> {ok, Handle} | {error, Reason} when
Hosts :: [Host],
Host :: inet:socket_address() | inet:hostname(),
Handle :: handle(),
Reason :: term().
open(Hosts) ->
open(Hosts, []).
-doc """
Setup a connection to an LDAP server, the `HOST`'s are tried in order.
The log function takes three arguments,
`fun(Level, FormatString, [FormatArg]) end`.
Timeout set the maximum time in milliseconds that each server request may take.
All TCP socket options are accepted except `active`, `binary`, `deliver`,
`list`, `mode` and `packet`
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec open(Hosts, Options) -> {ok, Handle} | {error, Reason} when
Hosts :: [Host],
Host :: inet:socket_address() | inet:hostname(),
Options ::
[{port, integer()} |
{log, function()} |
{timeout, integer()} |
{ssl, boolean()} |
{sslopts, list()} |
{tcpopts, list()}],
Handle :: handle(),
Reason :: term().
open(Hosts, Opts) when is_list(Hosts), is_list(Opts) ->
Self = self(),
Pid = spawn_link(fun() -> init(Hosts, Opts, Self) end),
recv(Pid).
%%% --------------------------------------------------------------------
%%% Upgrade an existing connection to TLS
%%% --------------------------------------------------------------------
-doc """
Same as start_tls(Handle, Options, infinity)
""".
-doc(#{since => <<"OTP R16B03">>}).
-spec start_tls(Handle, TlsOptions) -> ok |{ok, Refs} | {error, Reason} when
Handle :: handle(),
TlsOptions :: ssl:tls_client_option(),
Refs :: {referral, referrals()},
Reason :: term().
start_tls(Handle, TlsOptions) ->
start_tls(Handle, TlsOptions, infinity).
-doc """
Upgrade the connection associated with `Handle` to a TLS connection if possible.
The upgrade is done in two phases: first the server is asked for permission to
upgrade. Second, if the request is acknowledged, the upgrade to TLS is
performed.
Error responses from phase one will not affect the current encryption state of
the connection. Those responses are:
- **`tls_already_started`** - The connection is already encrypted. The
connection is not affected.
- **`{response,ResponseFromServer}`** - The upgrade was refused by the LDAP
server. The `ResponseFromServer` is an atom delivered byt the LDAP server
explained in section 2.3 of rfc 2830. The connection is not affected, so it is
still un-encrypted.
Errors in the second phase will however end the connection:
- **`Error`** - Any error responded from ssl:connect/3
The `Timeout` parameter is for the actual TLS upgrade (phase 2) while the
timeout in [eldap:open/2](`open/2`) is used for the initial negotiation about
upgrade (phase 1).
""".
-doc(#{since => <<"OTP R16B03">>}).
-spec start_tls(Handle, TlsOptions, Timeout) -> ok | {ok, Refs} | {error, Reason} when
Handle :: handle(),
TlsOptions :: ssl:tls_client_option(),
Timeout :: infinity | pos_integer(),
Refs :: {referral, referrals()},
Reason :: term().
start_tls(Handle, TlsOptions, Timeout) ->
start_tls(Handle, TlsOptions, Timeout, asn1_NOVALUE).
-doc false.
start_tls(Handle, TlsOptions, Timeout, Controls) ->
send(Handle, {start_tls,TlsOptions,Timeout,Controls}),
recv(Handle).
%%% --------------------------------------------------------------------
%%% Modify the password of a user.
%%%
%%% Dn - Name of the entry to modify. If empty, the session user.
%%% NewPasswd - New password. If empty, the server returns a new password.
%%% OldPasswd - Original password for server verification, may be empty.
%%%
%%% Returns: ok | {ok, Refs} | {ok, GenPasswd} | {error, term()}
%%% --------------------------------------------------------------------
-doc """
Modify the password of a user. See `modify_password/4`.
""".
-doc(#{since => <<"OTP 18.0">>}).
-spec modify_password(Handle, Dn, NewPasswd) ->
ok | {ok, Refs} | {error, term()} | {ok, GenPasswd} when
Handle :: handle(),
Dn :: string(),
NewPasswd :: string(),
Refs :: {referral, referrals()},
GenPasswd :: string().
modify_password(Handle, Dn, NewPasswd) ->
modify_password(Handle, Dn, NewPasswd, []).
-doc """
Modify the password of a user.
- `Dn`. The user to modify. Should be "" if the modify request is for the user
of the LDAP session.
- `NewPasswd`. The new password to set. Should be "" if the server is to
generate the password. In this case, the result will be `{ok, GenPasswd}`.
- `OldPasswd`. Sometimes required by server policy for a user to change their
password. If not required, use `modify_password/3`.
""".
-doc(#{since => <<"OTP 18.0">>}).
-spec modify_password(Handle, Dn, NewPasswd, OldPasswd) ->
ok | {ok, Refs} | {error, term()} | {ok, GenPasswd} when
Handle :: handle(),
Dn :: string(),
NewPasswd :: string(),
OldPasswd :: string(),
Refs :: {referral, referrals()},
GenPasswd :: string().
modify_password(Handle, Dn, NewPasswd, OldPasswd)
when is_pid(Handle), is_list(Dn), is_list(NewPasswd), is_list(OldPasswd) ->
modify_password(Handle, Dn, NewPasswd, OldPasswd, asn1_NOVALUE).
-doc false.
modify_password(Handle, Dn, NewPasswd, OldPasswd, Controls)
when is_pid(Handle), is_list(Dn), is_list(NewPasswd), is_list(OldPasswd) ->
send(Handle, {passwd_modify,optional(Dn),optional(NewPasswd),optional(OldPasswd),Controls}),
recv(Handle).
%%% --------------------------------------------------------------------
%%% Ask for option values on the socket.
%%% Warning: This is an undocumented function for testing purposes only.
%%% Use at own risk...
%%% --------------------------------------------------------------------
-doc false.
getopts(Handle, OptNames) when is_pid(Handle), is_list(OptNames) ->
send(Handle, {getopts, OptNames}),
recv(Handle).
%%% --------------------------------------------------------------------
%%% Shutdown connection (and process) asynchronous.
%%% --------------------------------------------------------------------
-doc """
Shutdown the connection after sending an unbindRequest to the server.
If the connection is TLS the connection will be closed with `ssl:close/1`, otherwise
with `gen_tcp:close/1`.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec close(Handle) -> ok when
Handle :: handle().
close(Handle) when is_pid(Handle) ->
send(Handle, close),
ok.
%%% --------------------------------------------------------------------
%%% Set who we should link ourselves to
%%% --------------------------------------------------------------------
-doc false.
controlling_process(Handle, Pid) when is_pid(Handle), is_pid(Pid) ->
link(Pid),
send(Handle, {cnt_proc, Pid}),
recv(Handle).
%%% --------------------------------------------------------------------
%%% Return LDAP socket information
%%% --------------------------------------------------------------------
-doc """
Currently available information reveals the socket and the transport protocol,
TCP or TLS (SSL), used by the LDAP connection.
""".
-doc(#{since => <<"OTP 25.3.1">>}).
-spec info(Handle) -> connection_info() when
Handle :: handle().
info(Handle) when is_pid(Handle) ->
send(Handle, info),
recv(Handle).
%%% --------------------------------------------------------------------
%%% Authenticate ourselves to the Directory
%%% using simple authentication.
%%%
%%% Dn - The name of the entry to bind as
%%% Passwd - The password to be used
%%%
%%% Returns: - ok | {ok, Refs} | {error, Reason}
%%% --------------------------------------------------------------------
-doc """
Authenticate the connection using simple authentication.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec simple_bind(Handle, Dn, Password) -> ok | {ok, Refs} | {error, Reason} when
Handle :: handle(),
Dn :: string(),
Password :: string(),
Refs :: {referral, referrals()},
Reason :: term().
simple_bind(Handle, Dn, Passwd) when is_pid(Handle) ->
simple_bind(Handle, Dn, Passwd, asn1_NOVALUE).
-doc false.
simple_bind(Handle, Dn, Passwd, Controls) when is_pid(Handle) ->
send(Handle, {simple_bind, Dn, Passwd, Controls}),
recv(Handle).
%%% --------------------------------------------------------------------
%%% Add an entry. The entry field MUST NOT exist for the AddRequest
%%% to succeed. The parent of the entry MUST exist.
%%% Example:
%%%
%%% add(Handle,
%%% "cn=Bill Valentine, ou=people, o=Bluetail AB, dc=bluetail, dc=com",
%%% [{"objectclass", ["person"]},
%%% {"cn", ["Bill Valentine"]},
%%% {"sn", ["Valentine"]},
%%% {"telephoneNumber", ["545 555 00"]}]
%%% )
%%% --------------------------------------------------------------------
-doc """
Add an entry. The entry must not exist.
```erlang
add(Handle,
"cn=Bill Valentine, ou=people, o=Example Org, dc=example, dc=com",
[{"objectclass", ["person"]},
{"cn", ["Bill Valentine"]},
{"sn", ["Valentine"]},
{"telephoneNumber", ["545 555 00"]}]
)
```
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec add(Handle, Dn, Attributes) -> ok | {ok, Refs} | {error, Reason} when
Handle :: handle(),
Dn :: string(),
Attributes :: [attribute()],
Refs :: {referral, referrals()},
Reason :: term().
add(Handle, Entry, Attributes) when is_pid(Handle),is_list(Entry),is_list(Attributes) ->
add(Handle, Entry, Attributes, asn1_NOVALUE).
-doc false.
add(Handle, Entry, Attributes, Controls) when is_pid(Handle),is_list(Entry),is_list(Attributes) ->
send(Handle, {add, Entry, add_attrs(Attributes), Controls}),
recv(Handle).
%%% Do sanity check !
add_attrs(Attrs) ->
F = fun({Type,Vals}) when is_list(Type),is_list(Vals) ->
%% Confused ? Me too... :-/
{'AddRequest_attributes',Type, Vals}
end,
case catch lists:map(F, Attrs) of
{'EXIT', _} -> throw({error, attribute_values});
Else -> Else
end.
%%% --------------------------------------------------------------------
%%% Delete an entry. The entry consists of the DN of
%%% the entry to be deleted.
%%% Example:
%%%
%%% delete(Handle,
%%% "cn=Bill Valentine, ou=people, o=Bluetail AB, dc=bluetail, dc=com"
%%% )
%%% --------------------------------------------------------------------
-doc """
Delete an entry.
```text
delete(Handle, "cn=Bill Valentine, ou=people, o=Example Org, dc=example, dc=com")
```
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec delete(Handle, Dn) -> ok | {ok, Refs} |{error, Reason} when
Handle :: handle(),
Dn :: string(),
Refs :: {referral, referrals()},
Reason :: term().
delete(Handle, Entry) when is_pid(Handle), is_list(Entry) ->
delete(Handle, Entry, asn1_NOVALUE).
-doc false.
delete(Handle, Entry, Controls) when is_pid(Handle), is_list(Entry) ->
send(Handle, {delete, Entry, Controls}),
recv(Handle).
%%% --------------------------------------------------------------------
%%% Modify an entry. Given an entry a number of modification
%%% operations can be performed as one atomic operation.
%%% Example:
%%%
%%% modify(Handle,
%%% "cn=Torbjorn Tornkvist, ou=people, o=Bluetail AB, dc=bluetail, dc=com",
%%% [mod_replace("telephoneNumber", ["555 555 00"]),
%%% mod_add("description", ["LDAP hacker"])]
%%% )
%%% --------------------------------------------------------------------
-doc """
Modify an entry.
```erlang
modify(Handle, "cn=Bill Valentine, ou=people, o=Example Org, dc=example, dc=com",
[eldap:mod_replace("telephoneNumber", ["555 555 00"]),
eldap:mod_add("description", ["LDAP Hacker"]) ])
```
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec modify(Handle, Dn, ModifyOps) -> ok | {ok, Refs} | {error, Reason} when
Handle :: handle(),
Dn :: string(),
ModifyOps :: [term()],
Refs :: {referral, referrals()},
Reason :: term().
modify(Handle, Object, Mods) when is_pid(Handle), is_list(Object), is_list(Mods) ->
modify(Handle, Object, Mods, asn1_NOVALUE).
-doc false.
modify(Handle, Object, Mods, Controls) when is_pid(Handle), is_list(Object), is_list(Mods) ->
send(Handle, {modify, Object, Mods, Controls}),
recv(Handle).
%%%
%%% Modification operations.
%%% Example:
%%% mod_replace("telephoneNumber", ["555 555 00"])
%%%
-doc """
Create an add modification operation.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec mod_add(Type, Values) -> modify_op() when
Type :: string(),
Values :: [string()].
mod_add(Type, Values) when is_list(Type), is_list(Values) -> m(add, Type, Values).
-doc """
Create a delete modification operation.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec mod_delete(Type, Values) -> modify_op() when
Type :: string(),
Values :: [string()].
mod_delete(Type, Values) when is_list(Type), is_list(Values) -> m(delete, Type, Values).
-doc """
Create a replace modification operation.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec mod_replace(Type, Values) -> modify_op() when
Type :: string(),
Values :: [string()].
mod_replace(Type, Values) when is_list(Type), is_list(Values) -> m(replace, Type, Values).
m(Operation, Type, Values) ->
#'ModifyRequest_changes_SEQOF'{
operation = Operation,
modification = #'PartialAttribute'{
type = Type,
vals = Values}}.
%%% --------------------------------------------------------------------
%%% Modify an entry. Given an entry a number of modification
%%% operations can be performed as one atomic operation.
%%% Example:
%%%
%%% modify_dn(Handle,
%%% "cn=Bill Valentine, ou=people, o=Bluetail AB, dc=bluetail, dc=com",
%%% "cn=Ben Emerson",
%%% true,
%%% ""
%%% )
%%% --------------------------------------------------------------------
-doc """
Modify the DN of an entry.
`DeleteOldRDN` indicates whether the current RDN
should be removed from the attribute list after the operation. `NewSupDN` is the
new parent that the RDN shall be moved to. If the old parent should remain as
parent, `NewSupDN` shall be "".
```text
modify_dn(Handle, "cn=Bill Valentine, ou=people, o=Example Org, dc=example, dc=com ",
"cn=Bill Jr Valentine", true, "")
```
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec modify_dn(Handle, Dn, NewRDN, DeleteOldRDN, NewSupDN) -> ok | {ok, Refs} | {error, Reason} when
Handle :: handle(),
Dn :: string(),
NewRDN :: string(),
DeleteOldRDN :: boolean(),
NewSupDN :: string(),
Refs :: {referral, referrals()},
Reason :: term().
modify_dn(Handle, Entry, NewRDN, DelOldRDN, NewSup)
when is_pid(Handle),is_list(Entry),is_list(NewRDN),is_atom(DelOldRDN),is_list(NewSup) ->
modify_dn(Handle, Entry, NewRDN, DelOldRDN, NewSup, asn1_NOVALUE).
modify_dn(Handle, Entry, NewRDN, DelOldRDN, NewSup, Controls)
when is_pid(Handle),is_list(Entry),is_list(NewRDN),is_atom(DelOldRDN),is_list(NewSup) ->
send(Handle, {modify_dn, Entry, NewRDN,
bool_p(DelOldRDN), optional(NewSup), Controls}),
recv(Handle).
%%% Sanity checks !
bool_p(Bool) when is_boolean(Bool) -> Bool.
optional([]) -> asn1_NOVALUE;
optional(Value) -> Value.
%%% --------------------------------------------------------------------
%%% Synchronous search of the Directory returning a
%%% requested set of attributes.
%%%
%%% Example:
%%%
%%% Filter = eldap:substrings("cn", [{any,"o"}]),
%%% eldap:search(S, [{base, "dc=bluetail, dc=com"},
%%% {filter, Filter},
%%% {attributes,["cn"]}])),
%%%
%%% Returned result: {ok, #eldap_search_result{}}
%%%
%%% Example:
%%%
%%% {ok,{eldap_search_result,
%%% [{eldap_entry,
%%% "cn=Magnus Froberg, dc=bluetail, dc=com",
%%% [{"cn",["Magnus Froberg"]}]},
%%% {eldap_entry,
%%% "cn=Torbjorn Tornkvist, dc=bluetail, dc=com",
%%% [{"cn",["Torbjorn Tornkvist"]}]}],
%%% []}}
%%%
%%% --------------------------------------------------------------------
-doc """
Search the directory with the supplied the SearchOptions.
The base and filter
options must be supplied. Default values: scope is `wholeSubtree/0`, deref is
`derefAlways/0`, types_only is `false` and timeout is `0` (meaning infinity).
```erlang
Filter = eldap:substrings("cn", [{any,"V"}]),
search(Handle, [{base, "dc=example, dc=com"}, {filter, Filter}, {attributes, ["cn"]}]),
```
The `timeout` option in the `SearchOptions` is for the ldap server, while the
timeout in [eldap:open/2](`open/2`) is used for each individual request in the
search operation.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec search(Handle, SearchOptions) ->
{ok, #eldap_search_result{entries :: term(), referrals :: term(), controls :: term()}} |
{ok, Refs} |
{error, Reason} when
Handle :: handle(),
SearchOptions ::
#eldap_search{base :: term(),
filter :: term(),
size_limit :: term(),
scope :: term(),
deref :: term(),
attributes :: term(),
types_only :: term(),
timeout :: term()} |
[search_option()],
Refs :: {referral, referrals()},
Reason :: term().
search(Handle, X) when is_pid(Handle), is_record(X,eldap_search) ; is_list(X) ->
search(Handle, X, asn1_NOVALUE).
-doc false.
search(Handle, A, Controls) when is_pid(Handle), is_record(A, eldap_search) ->
call_search(Handle, A, Controls);
search(Handle, L, Controls) when is_pid(Handle), is_list(L) ->
case catch parse_search_args(L) of
{error, Emsg} -> {error, Emsg};
A when is_record(A, eldap_search) -> call_search(Handle, A, Controls)
end.
call_search(Handle, A, Controls) ->
send(Handle, {search, A, Controls}),
recv(Handle).
parse_search_args(Args) ->
parse_search_args(Args,
#eldap_search{scope = wholeSubtree,
deref = derefAlways}).
parse_search_args([{base, Base}|T],A) ->
parse_search_args(T,A#eldap_search{base = Base});
parse_search_args([{filter, Filter}|T],A) ->
parse_search_args(T,A#eldap_search{filter = Filter});
parse_search_args([{size_limit, SizeLimit}|T],A) when is_integer(SizeLimit) ->
parse_search_args(T,A#eldap_search{size_limit = SizeLimit});
parse_search_args([{scope, Scope}|T],A) ->
parse_search_args(T,A#eldap_search{scope = Scope});
parse_search_args([{deref, Deref}|T],A) ->
parse_search_args(T,A#eldap_search{deref = Deref});
parse_search_args([{attributes, Attrs}|T],A) ->
parse_search_args(T,A#eldap_search{attributes = Attrs});
parse_search_args([{types_only, TypesOnly}|T],A) ->
parse_search_args(T,A#eldap_search{types_only = TypesOnly});
parse_search_args([{timeout, Timeout}|T],A) when is_integer(Timeout) ->
parse_search_args(T,A#eldap_search{timeout = Timeout});
parse_search_args([H|_],_) ->
throw({error,{unknown_arg, H}});
parse_search_args([],A) ->
A.
%%%
%%% The Scope parameter
%%%
-doc """
Search baseobject only.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec baseObject() -> scope().
baseObject() -> baseObject.
-doc """
Search the specified level only, i.e. do not recurse.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec singleLevel() -> scope().
singleLevel() -> singleLevel.
-doc """
Search the entire subtree.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec wholeSubtree() -> scope().
wholeSubtree() -> wholeSubtree.
%%
%% The derefAliases parameter
%%
-doc """
Never dereference aliases, treat aliases as entries.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec neverDerefAliases() -> dereference().
neverDerefAliases() -> neverDerefAliases.
-doc """
Dereference aliases only when searching.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec derefInSearching() -> dereference().
derefInSearching() -> derefInSearching.
-doc """
Dereference aliases only in finding the base.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec derefFindingBaseObj() -> dereference().
derefFindingBaseObj() -> derefFindingBaseObj.
-doc """
Always dereference aliases.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec derefAlways() -> dereference().
derefAlways() -> derefAlways.
%%%
%%% Boolean filter operations
%%%
-doc """
Creates a filter where all `Filter` must be true.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec 'and'(ListOfFilters) -> filter() when ListOfFilters :: [filter()].
'and'(ListOfFilters) when is_list(ListOfFilters) -> {'and',ListOfFilters}.
-doc """
Create a filter where at least one of the `Filter` must be true.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec 'or'(ListOfFilters) -> filter() when ListOfFilters :: [filter()].
'or'(ListOfFilters) when is_list(ListOfFilters) -> {'or', ListOfFilters}.
-doc """
Negate a filter.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec 'not'(Filter) -> filter() when Filter :: {filter()}.
'not'(Filter) when is_tuple(Filter) -> {'not',Filter}.
%%%
%%% The following Filter parameters consist of an attribute
%%% and an attribute value. Example: F("uid","tobbe")
%%%
-doc """
Create a equality filter.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec equalityMatch(Type, Value) -> filter() when
Type :: string(),
Value :: string().
equalityMatch(Desc, Value) -> {equalityMatch, av_assert(Desc, Value)}.
-doc """
Create a greater or equal filter.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec greaterOrEqual(Type, Value) -> filter() when
Type :: string(),
Value :: string().
greaterOrEqual(Desc, Value) -> {greaterOrEqual, av_assert(Desc, Value)}.
-doc """
Create a less or equal filter.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec lessOrEqual(Type, Value) -> filter() when
Type :: string(),
Value :: string().
lessOrEqual(Desc, Value) -> {lessOrEqual, av_assert(Desc, Value)}.
-doc """
Create a approximation match filter.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec approxMatch(Type, Value) -> filter() when
Type :: string(),
Value :: string().
approxMatch(Desc, Value) -> {approxMatch, av_assert(Desc, Value)}.
av_assert(Desc, Value) ->
#'AttributeValueAssertion'{attributeDesc = Desc,
assertionValue = Value}.
%%%
%%% Filter to check for the presence of an attribute
%%%
-doc """
Create a filter which filters on attribute type presence.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec present(Type) -> filter() when Type :: string().
present(Attribute) when is_list(Attribute) ->
{present, Attribute}.
%%%
%%% A substring filter seem to be based on a pattern:
%%%
%%% InitValue*AnyValue*FinalValue
%%%
%%% where all three parts seem to be optional (at least when
%%% talking with an OpenLDAP server). Thus, the arguments
%%% to substrings/2 looks like this:
%%%
%%% Type ::= string( <attribute> )
%%% SubStr ::= listof( {initial,Value} | {any,Value}, {final,Value})
%%%
%%% Example: substrings("sn",[{initial,"To"},{any,"kv"},{final,"st"}])
%%% will match entries containing: 'sn: Tornkvist'
%%%
-doc """
Create a filter which filters on substrings.
""".
-doc(#{since => <<"OTP R15B01">>}).
-spec substrings(Type, SubStrings) -> filter() when
Type :: string(),
SubStrings :: [{initial, string()} | {any, string()} |{final, string()}].
substrings(Type, SubStr) when is_list(Type), is_list(SubStr) ->
Ss = v_substr(SubStr),
{substrings,#'SubstringFilter'{type = Type,
substrings = Ss}}.
%%%
%%% Filter for extensibleMatch
%%%
-doc """
Creates an extensible match filter. For example,
```erlang
eldap:extensibleMatch("Bar", [{type,"sn"}, {matchingRule,"caseExactMatch"}]))
```
creates a filter which performs a `caseExactMatch` on the attribute `sn` and
matches with the value `"Bar"`. The default value of `dnAttributes` is `false`.
""".
-doc(#{since => <<"OTP 17.4">>}).
-spec extensibleMatch(MatchValue, OptionalAttrs) -> filter() when
MatchValue :: string(),
OptionalAttrs :: [{matchingRule, string()} | {type, string()} | {dnAttributes, boolean()}].
extensibleMatch(MatchValue, OptArgs) ->
MatchingRuleAssertion =
mra(OptArgs, #'MatchingRuleAssertion'{matchValue = MatchValue}),
{extensibleMatch, MatchingRuleAssertion}.
mra([{matchingRule,Val}|T], Ack) when is_list(Val) ->
mra(T, Ack#'MatchingRuleAssertion'{matchingRule=Val});
mra([{type,Val}|T], Ack) when is_list(Val) ->
mra(T, Ack#'MatchingRuleAssertion'{type=Val});
mra([{dnAttributes,true}|T], Ack) ->
mra(T, Ack#'MatchingRuleAssertion'{dnAttributes=true});
mra([{dnAttributes,false}|T], Ack) ->
mra(T, Ack#'MatchingRuleAssertion'{dnAttributes=false});
mra([H|_], _) ->
throw({error,{extensibleMatch_arg,H}});
mra([], Ack) ->
Ack.
%%% --------------------------------------------------------------------
%%% Worker process. We keep track of a controlling process to
%%% be able to terminate together with it.
%%% --------------------------------------------------------------------
init(Hosts, Opts, Cpid) ->
Data = parse_args(Opts, Cpid, #eldap{}),
case try_connect(Hosts, Data) of
{ok,Data2} ->
send(Cpid, {ok,self()}),
?MODULE:loop(Cpid, Data2);
Else ->
send(Cpid, Else),
unlink(Cpid),
exit(Else)
end.
parse_args([{port, Port}|T], Cpid, Data) when is_integer(Port) ->
parse_args(T, Cpid, Data#eldap{port = Port});
parse_args([{timeout, Timeout}|T], Cpid, Data) when is_integer(Timeout),Timeout>0 ->
parse_args(T, Cpid, Data#eldap{timeout = Timeout});
parse_args([{anon_auth, true}|T], Cpid, Data) ->
parse_args(T, Cpid, Data#eldap{anon_auth = true});
parse_args([{anon_auth, _}|T], Cpid, Data) ->
parse_args(T, Cpid, Data);
parse_args([{ssl, true}|T], Cpid, Data) ->
parse_args(T, Cpid, Data#eldap{ldaps = true, using_tls=true});
parse_args([{ssl, _}|T], Cpid, Data) ->
parse_args(T, Cpid, Data);
parse_args([{sslopts, Opts}|T], Cpid, Data) when is_list(Opts) ->
parse_args(T, Cpid, Data#eldap{ldaps = true, using_tls=true, tls_opts = Opts ++ Data#eldap.tls_opts});
parse_args([{sslopts, _}|T], Cpid, Data) ->
parse_args(T, Cpid, Data);
parse_args([{tcpopts, Opts}|T], Cpid, Data) when is_list(Opts) ->
parse_args(T, Cpid, Data#eldap{tcp_opts = tcp_opts(Opts,Cpid,Data#eldap.tcp_opts)});
parse_args([{log, F}|T], Cpid, Data) when is_function(F) ->
parse_args(T, Cpid, Data#eldap{log = F});
parse_args([{log, _}|T], Cpid, Data) ->
parse_args(T, Cpid, Data);
parse_args([H|_], Cpid, _) ->
send(Cpid, {error,{wrong_option,H}}),
unlink(Cpid),
exit(wrong_option);
parse_args([], _, Data) ->
Data.
tcp_opts([Opt|Opts], Cpid, Acc) ->
Key = if is_atom(Opt) -> Opt;
is_tuple(Opt) -> element(1,Opt)
end,
case lists:member(Key,[active,binary,deliver,list,mode,packet]) of
false ->
tcp_opts(Opts, Cpid, [Opt|Acc]);
true ->
tcp_opts_error(Opt, Cpid)
end;
tcp_opts([], _Cpid, Acc) -> Acc.
tcp_opts_error(Opt, Cpid) ->
send(Cpid, {error, {{forbidden_tcp_option,Opt},
"This option affects the eldap functionality and can't be set by user"}}),
unlink(Cpid),
exit(forbidden_tcp_option).
%%% Try to connect to the hosts in the listed order,
%%% and stop with the first one to which a successful
%%% connection is made.
try_connect([Host|Hosts], Data) ->
TcpOpts = [{packet, asn1}, {active,false}],
try do_connect(Host, Data, TcpOpts) of
{ok,Fd} -> {ok,Data#eldap{host = Host, fd = Fd}};
Err ->
log2(Data, "Connect: ~p failed ~p~n",[Host, Err]),
try_connect(Hosts, Data)
catch _:Err ->
log2(Data, "Connect: ~p failed ~p~n",[Host, Err]),
try_connect(Hosts, Data)
end;
try_connect([],_) ->
{error,"connect failed"}.
do_connect(Host, Data, Opts) when Data#eldap.ldaps == false ->
gen_tcp:connect(Host, Data#eldap.port, Opts ++ Data#eldap.tcp_opts,
Data#eldap.timeout);
do_connect(Host, Data, Opts) when Data#eldap.ldaps == true ->
ssl:connect(Host, Data#eldap.port,
Opts ++ Data#eldap.tls_opts ++ Data#eldap.tcp_opts,
Data#eldap.timeout).
-doc false.
loop(Cpid, Data) ->
receive
{From, {search, A, Controls}} ->
{Res,NewData} = do_search(Data, A, Controls),
send(From,Res),
?MODULE:loop(Cpid, NewData);
{From, {modify, Obj, Mod, Controls}} ->
{Res,NewData} = do_modify(Data, Obj, Mod, Controls),
send(From,Res),
?MODULE:loop(Cpid, NewData);