-
Notifications
You must be signed in to change notification settings - Fork 5
/
trivial-ldap.lisp
1853 lines (1645 loc) · 70.3 KB
/
trivial-ldap.lisp
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
;;;; TRIVIAL-LDAP -- a one file, all lisp client implementation of
;;;; parts of RFC 2261.
;;;; Please see the trivial-ldap.html file for documentation and limitations.
;;;; TRIVIAL-LDAP is
;;;; Copyright 2005-2009 Kevin Montuori
;;;; and is distributed under The Clarified Artistic License, a copy
;;;; of which should have accompanied this file.
;;;; Kevin Montuori <[email protected]>
#+xcvb (module ())
(in-package :trivial-ldap)
(defparameter *init-sec-fn* nil)
(defparameter *wrap-fn* nil)
(defparameter *unwrap-fn* nil)
(defvar *binary-attributes*
(list :objectsid :objectguid))
(defun attribute-binary-p (attribute-name)
(let ((name-sym (intern (string-upcase (if (symbolp attribute-name)
(symbol-name attribute-name)
attribute-name))
:keyword)))
(declare (special *binary-attributes*))
(member name-sym *binary-attributes*)))
(defun (setf attribute-binary-p) (value attribute-name)
(let ((name-sym (intern (string-upcase (if (symbolp attribute-name)
(symbol-name attribute-name)
attribute-name))
:keyword)))
(declare (special *binary-attributes*))
(if value
(pushnew name-sym *binary-attributes*)
(setf *binary-attributes* (remove name-sym *binary-attributes*)))))
;;;;
;;;; error conditions
;;;;
(define-condition ldap-error (error)
((note :initarg :mesg
:reader mesg
:initform "LDAP transaction resulted in an error."))
(:report (lambda (c stream)
(format stream "~A~%" (mesg c)))))
(define-condition ldap-filter-error (ldap-error)
((filter :initarg :filter
:reader filter
:initform "Not Supplied"))
(:report (lambda (c stream)
(format stream "Filter Error: ~A~%Supplied Filter: ~A~%"
(mesg c) (filter c)))))
(define-condition ldap-connection-error (ldap-error)
((host :initarg :host
:reader host)
(port :initarg :port
:reader port))
(:report (lambda (c stream)
(format stream "LDAP Connection Error: ~A~%Host:Port: ~A:~A~%"
(mesg c) (host c) (port c)))))
(define-condition ldap-response-error (ldap-error)
((dn :initarg :dn
:reader dn
:initform "DN not available.")
(code :initarg :code
:reader code
:initform "Result code not available")
(msg :initarg :msg
:reader msg
:initform "N/A"))
(:report (lambda (c stream)
(format stream "~A~%DN: ~A~%Code: ~A~%Message: ~A~%"
(mesg c) (dn c) (code c) (msg c)))))
(define-condition ldap-bind-error (ldap-error)
((code-sym :initarg :code-sym
:reader code-sym
:initform (error "Must specify code-sym")))
(:report (lambda (c stream)
(format stream "LDAP Bind Error: ~A~%"
(code-sym c)))))
(define-condition ldap-referral-error (ldap-error)
()
(:report (lambda (c stream)
(declare (ignore c))
(format stream "LDAP Error: Referral."))))
(define-condition ldap-size-limit-exceeded-error (ldap-error)
()
(:report (lambda (c stream)
(declare (ignore c))
(format stream "LDAP Error: Size Limit Exceeded."))))
;;;;
;;;; utility functions
;;;;
;; to appease sbcl (see http://tinyurl.com/auqmr):
(defmacro define-constant (name value &optional doc)
`(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value)
,@(when doc (list doc))))
(defparameter *hex-print* "~A~%~{~<~%~1,76:;~2,'0,,X~> ~}~%"
"Format directive to print a list of line wrapped hex numbers.")
(defun base10->base256 (int)
"Return representation of an integer as a list of base 256 'digits'."
(assert (and (integerp int) (>= int 0)))
(or
(do ((i 0 (+ i 8))
(j int (ash j -8))
(result nil (cons (logand #xFF j) result)))
((> i (1- (integer-length int))) result))
(list 0)))
(defun base256->base10 (list)
"Given a list of base 256 'digits' return an integer."
(assert (consp list))
(let ((len (length list)))
(do ((i 0 (1+ i))
(j (- len 1) (1- j))
(int 0 (dpb (pop list) (byte 8 (* 8 j)) int)))
((= i len) int))))
(defun base256-vec->base10 (vec &key (start 0) (end (length vec)))
(let ((res 0))
(loop for i from start below end
for j downfrom (- end start 1)
do (setf res (dpb (aref vec i) (byte 8 (* 8 j)) res)))
res))
#||
(let ((test-vec #(13 42 255 7 9)))
(values (base256-vec->base10 test-vec)
(base256->base10 (coerce test-vec 'list))))
(let ((test-vec #(13 42 255 7 9)))
(values (base256-vec->base10 test-vec :start 1 :end 3)
(base256->base10 (subseq (coerce test-vec 'list) 1 3))))
||#
;;; fixme: int->octet-list and octet-list->int seem to be duplicates of base256->int and base10->base256
(defun int->octet-list (int)
"Return 2s comp. representation of INT."
(assert (integerp int))
(do ((i 0 (+ i 8))
(j int (ash j -8))
(result nil (cons (logand #xFF j) result)))
((> i (integer-length int)) result)))
(defun octet-list->int (octet-list)
"Convert sequence of twos-complement octets into an integer."
(assert (consp octet-list))
(let ((int 0))
(dolist (value octet-list int) (setq int (+ (ash int 8) value)))))
(defun octet-vec->int (vec &key (start 0) (end (length vec)))
(let ((int 0))
;; fixme: use dpb
(loop for i from start below end
do (setf int (+ (ash int 8) (aref vec i))))
int))
#||
(let ((test-vec #(13 42 255 7 9)))
(values (base256-vec->base10 test-vec)
(base256->base10 (coerce test-vec 'list))
(octet-vec->int test-vec)
(octet-list->int (coerce test-vec 'list))))
(let ((test-vec #(-13 42 255 7 9)))
(values (base256-vec->base10 test-vec :start 1 :end 3)
(base256->base10 (subseq (coerce test-vec 'list) 1 3))
(octet-vec->int test-vec :start 1 :end 3)
(octet-list->int (subseq (coerce test-vec 'list) 1 3))))
||#
(defun unescape-string (string)
(if (not (some (lambda (c) (char= c #\\)) string))
string
(flet ((hex-digit-char-p (c)
(or (char<= #\0 c #\9)
(char<= #\a c #\f)
(char<= #\A c #\F))))
(let ((string-length (length string)))
(with-output-to-string (s)
(loop for i below string-length
do (let ((c (char string i)))
(if (char= c #\\)
(cond ((and (< i (- string-length 1))
(member (char string (1+ i)) '(#\( #\) #\* #\\) :test #'char=))
;; LDAP v2 style escapes
(write-char (char string (1+ i)) s)
(incf i 1))
((and (< i (- string-length 2))
(hex-digit-char-p (char string (+ i 1)))
(hex-digit-char-p (char string (+ i 2))))
;; LDAP v3 style escapes
(write-char (code-char (parse-integer (subseq string (1+ i) (+ 3 i)) :radix 16)) s)
(incf i 2))
(t
(error "invalid escape at position ~d in ~a" i string)))
(write-char (char string i) s))))
s)))))
(defun escape-string (string)
(flet ((must-escape (c)
(member c '(#\( #\) #\* #\\ #\null) :test #'char=)))
(if (not (some #'must-escape string))
string
(with-output-to-string (s)
(loop for c across string
do (if (must-escape c)
(format s "\\~2,'0X" (char-code c))
(write-char c s)))
s))))
(defun string->char-code-list (string)
"Convert a string into a list of bytes."
(let ((string (etypecase string
(string string)
(symbol (symbol-name string)))))
#-(or allegro ccl sbcl lispworks)
(map 'list #'char-code string)
#+ccl
(coerce
(ccl::encode-string-to-octets string :external-format :utf-8) 'list)
#+sbcl
(coerce (sb-ext:string-to-octets string :external-format :utf-8) 'list)
#+allegro
(coerce (excl:string-to-octets string :external-format :utf-8 :null-terminate nil) 'list)
#+lispworks
(coerce (external-format:encode-lisp-string string :utf-8) 'list)))
(defun char-code-list->string (char-code-list)
"Convert a list of bytes into a string."
(assert (or (null char-code-list) (consp char-code-list)))
#-(or allegro ccl sbcl lispworks)
(map 'string #'code-char char-code-list)
#+ccl
(ccl::decode-string-from-octets (make-array (list (length char-code-list))
:element-type '(unsigned-byte 8)
:initial-contents char-code-list)
:external-format :utf-8)
#+sbcl
(sb-ext:octets-to-string (make-array (list (length char-code-list))
:element-type '(unsigned-byte 8)
:initial-contents char-code-list)
:external-format :utf-8)
#+allegro
(excl:octets-to-string (make-array (list (length char-code-list))
:element-type '(unsigned-byte 8)
:initial-contents char-code-list)
:external-format :utf8)
#+lispworks
(external-format:decode-external-string (make-array (list (length char-code-list))
:element-type '(unsigned-byte 8)
:initial-contents char-code-list)
:utf-8))
(defun char-code-vec->string (char-code-vec &key (start 0) (end (length char-code-vec)))
"Convert a vector of bytes into a string."
(assert (typep char-code-vec '(array (unsigned-byte 8))))
#-(or allegro ccl sbcl lispworks)
(map 'string #'code-char char-code-list)
#+ccl
(ccl::decode-string-from-octets char-code-vec :start start :end end
:external-format :utf-8)
#+sbcl
(sb-ext:octets-to-string char-code-vec :start start :end end
:external-format :utf-8)
#+allegro
(excl:octets-to-string char-code-vec :start start :end end
:external-format :utf8)
#+lispworks
(external-format:decode-external-string char-code-vec :utf-8 :start start :end end))
(defun split-substring (string &optional list)
"Split a substring filter value into a list, retaining the * separators."
(let ((pos (position #\* string)))
(if pos
(let* ((capture (subseq string 0 pos))
(vals (if (string= capture "") (list "*") (list "*" capture))))
(split-substring (subseq string (1+ pos))(append vals list)))
(nreverse (if (string= string "") list (push string list))))))
;;;;
;;;; BER encoding constants and constructors.
;;;;
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-constant +max-int+ (- (expt 2 31) 1)
"As defined by the LDAP RFC.")
(define-constant +ber-class-id+
'((universal . #b00000000) (application . #b01000000)
(context . #b10000000) (private . #b11000000)))
(define-constant +ber-p/c-bit+
'((primitive . #b00000000) (constructed . #b00100000)))
(define-constant +ber-multibyte-tag-number+ #b00011111
"Flag indicating tag number requires > 1 byte")
(define-constant +ber-long-length-marker+ #b10000000
"Flag indicating more tag number bytes follow")
(defun ber-class-id (class)
"Return the bits to construct a BER tag of type class."
(or (cdr (assoc class +ber-class-id+))
(error "Attempted to retrieve a non-existent BER class.")))
(defun ber-p/c-bit (p/c)
"Return the bit to construct a BER tag of class primitive or constructed."
(or (cdr (assoc p/c +ber-p/c-bit+))
(error "Attempted to retrieve a non-existent p/c bit.")))
(defun ber-tag-type (class p/c)
"Construct the bits that kicks off a BER tag byte."
(+ (ber-class-id class) (ber-p/c-bit p/c)))
(defun ber-tag (class p/c number-or-command)
"Construct the list of bytes that constitute a BER tag number 0-127.
CLASS should be the symbol universal, applicaiton, context, or private.
P/C should be the symbol primitive or constructed.
NUMBER should be either an integer or LDAP application name as symbol."
(let ((byte (ber-tag-type class p/c))
(number (etypecase number-or-command
(integer number-or-command)
(symbol (ldap-command number-or-command)))))
(cond
((< number 31) (list (+ byte number)))
((< number 128) (list (+ byte +ber-multibyte-tag-number+) number))
(t (error "Length of tag exceeds maximum bounds (0-127).")))))
(defun ber-length (it)
"Given a sequence or integer, return a BER length."
(let ((length (etypecase it
(sequence (length it))
(integer it))))
(cond
((< length 128) (list length))
((< length +max-int+)
(let ((output (base10->base256 length)))
(append (list (+ (length output) +ber-long-length-marker+))
output)))
(t (error "Length exceeds maximum bounds")))))
(defun ber-msg (tag data)
"Given a BER tag and a sequence of data, return a message"
(let ((len (ber-length data)))
(append tag len data))))
;;;;
;;;; LDAP constants and accessors
;;;;
(define-constant +ldap-version+ #x03 "LDAP version 3.")
(define-constant +ldap-port-no-ssl+ 389 "Default LDAP Port.")
(define-constant +ldap-port-ssl+ 636 "Default LDAPS Port.")
(define-constant +ldap-disconnection-response+ "1.3.6.1.4.1.1466.20036"
"OID of the unsolicited disconnection reponse.")
(define-constant +ldap-control-extension-paging+ "1.2.840.113556.1.4.319"
"OID of the paging control.")
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-constant +ldap-application-names+
'((BindRequest . 0)
(BindResponse . 1)
(UnbindRequest . 2)
(SearchRequest . 3)
(SearchResultEntry . 4)
(SearchResultReference . 19)
(SearchResultDone . 5)
(ModifyRequest . 6)
(ModifyResponse . 7)
(AddRequest . 8)
(AddResponse . 9)
(DelRequest . 10)
(DelResponse . 11)
(ModifyDNRequest . 12)
(ModifyDNResponse . 13)
(CompareRequest . 14)
(CompareResponse . 15)
(AbandonRequest . 16)
(ExtendedRequest . 23)
(ExtendedResponse . 24)))
(defun ldap-command (command)
"Given a symbol naming an ldap command, return the command number."
(cdr (assoc command +ldap-application-names+)))
(defun ldap-command-sym (number)
"Given an application number, return the command name as symbol."
(car (rassoc number +ldap-application-names+)))
(define-constant +ldap-result-codes+
'((0 . (success "Success"))
(1 . (operationsError "Operations Error"))
(2 . (protocolError "Protocol Error"))
(3 . (timeLimitExceeded "Time Limit Exceeded"))
(4 . (sizeLimitExceeded "Size Limit Exceeded"))
(5 . (compareFalse "Compare False"))
(6 . (compareTrue "Compare True"))
(7 . (authMethodNotSupported "Auth Method Not Supported"))
(8 . (strongAuthRequired "Strong Auth Required"))
(10 . (referral "Referral"))
(11 . (adminLimitExceeded "Admin Limit Exceeded"))
(12 . (unavailableCriticalExtension "Unavailable Critical Extension"))
(13 . (confidentialityRequired "Confidentiality Required"))
(14 . (saslBindInProgress "SASL Bind In Progress"))
(16 . (noSuchAttribute "No Such Attribute"))
(17 . (undefinedAttributeType "Undefined Attribute Type"))
(18 . (inappropriateMatching "Inappropriate Matching"))
(19 . (constraintViolation "Constraint Violation"))
(20 . (attributeOrValueExists "Attribute Or Value Exists"))
(21 . (invalidAttributeSyntax "Invalid Attribute Syntax"))
(32 . (noSuchObject "No Such Object"))
(33 . (aliasProblem "Alias Problem"))
(34 . (invalidDNSyntax "Invalid DN Syntax"))
(36 . (aliasDereferencingProblem "Alias Dereferencing Problem"))
(48 . (inappropriateAuthentication "Inappropriate Authentication"))
(49 . (invalidCredentials "Invalid Credentials"))
(50 . (insufficientAccessRights "Insufficient Access Rights"))
(51 . (busy "Busy"))
(52 . (unavailable "Unavailable"))
(53 . (unwillingToPerform "Unwilling To Perform"))
(54 . (loopDetect "Loop Detect"))
(64 . (namingViolation "Naming Violation"))
(65 . (objectClassViolation "Object Class Violation"))
(66 . (notAllowedOnLeaf "Not Allowed On Leaf"))
(67 . (notAllowedOnRDN "Not Allowed On RDN"))
(68 . (entryAlreadyExists "Entry Already Exists"))
(69 . (objectClassModsProhibited "Object Class Mods Prohibited"))
(71 . (affectsMultipleDSAs "Affects Multiple DSAs"))
(80 . (other "Other"))))
;; export the result code symbols.
(dolist (i +ldap-result-codes+) (export (second i) :ldap)))
(defun ldap-result-code-string (code)
(second (cdr (assoc code +ldap-result-codes+))))
(defun ldap-result-code-symbol (code)
(first (cdr (assoc code +ldap-result-codes+))))
(define-constant +ldap-scope+
'((base . 0)
(one . 1)
(sub . 2)))
(define-constant +ldap-deref+
'((never . 0)
(search . 1)
(find . 2)
(always . 3)))
(define-constant +ldap-modify-type+
'((add . 0)
(delete . 1)
(replace . 2)))
(define-constant +ldap-filter-comparison-char+
'((& . 0)
(\| . 1)
(! . 2)
(= . 3)
(>= . 5)
(<= . 6)
(=* . 7)
(~= . 8)
(substring . 4)))
(define-constant +ldap-substring+
'((initial . 0)
(any . 1)
(final . 2)))
(defun ldap-scope (&optional (scope 'sub))
"Given a scope symbol return the enumeration int."
(cdr (assoc scope +ldap-scope+)))
(defun ldap-deref (&optional (deref 'never))
"Given a deref symbol return the enumeration int."
(cdr (assoc deref +ldap-deref+)))
(defun ldap-modify-type (type)
"Given a modify type, return the enumeration int."
(cdr (assoc type +ldap-modify-type+)))
(defun ldap-filter-comparison-char (comparison-char-as-symbol)
"Given a comparison character, return its integer enum value."
(cdr (assoc comparison-char-as-symbol +ldap-filter-comparison-char+)))
(defun ldap-substring (type)
"Given a substring type, return its integer choice value."
(cdr (assoc type +ldap-substring+)))
;;;;
;;;; BER sequence creators.
;;;;
;;; writers.
(define-constant +ber-bind-tag+
(ber-tag 'application 'constructed 'bindrequest))
(define-constant +ber-add-tag+
(ber-tag 'application 'constructed 'addrequest))
(define-constant +ber-del-tag+
(ber-tag 'application 'primitive 'delrequest))
(define-constant +ber-moddn-tag+
(ber-tag 'application 'constructed 'modifydnrequest))
(define-constant +ber-comp-tag+
(ber-tag 'application 'constructed 'comparerequest))
(define-constant +ber-search-tag+
(ber-tag 'application 'constructed 'searchrequest))
(define-constant +ber-abandon-tag+
(ber-tag 'application 'primitive 'abandonrequest))
(define-constant +ber-unbind-tag+
(ber-tag 'application 'primitive 'unbindrequest))
(define-constant +ber-modify-tag+
(ber-tag 'application 'constructed 'modifyrequest))
(define-constant +ber-controls-tag+
(car (ber-tag 'context 'constructed 0)))
;;;; readers.
(define-constant +ber-tag-controls+
(car (ber-tag 'context 'constructed 0)))
(define-constant +ber-tag-referral+
(car (ber-tag 'context 'constructed 'searchrequest)))
(define-constant +ber-tag-extendedresponse+
(car (ber-tag 'application 'constructed 'extendedresponse)))
(define-constant +ber-tag-ext-name+
(car (ber-tag 'context 'primitive 10)))
(define-constant +ber-tag-ext-val+
(car (ber-tag 'context 'primitive 11)))
(define-constant +ber-tag-bool+
(car (ber-tag 'universal 'primitive #x01)))
(define-constant +ber-tag-int+
(car (ber-tag 'universal 'primitive #x02)))
(define-constant +ber-tag-enum+
(car (ber-tag 'universal 'primitive #x0A)))
(define-constant +ber-tag-str+
(car (ber-tag 'universal 'primitive #x04)))
(define-constant +ber-tag-seq+
(car (ber-tag 'universal 'constructed #x10)))
(define-constant +ber-tag-set+
(car (ber-tag 'universal 'constructed #x11)))
(define-constant +ber-tag-sasl-res-creds+
#x87)
(defun seq-null ()
"BER encode a NULL"
(append (ber-tag 'universal 'primitive #x05) (ber-length 0)))
(defun seq-boolean (t/f)
"BER encode a boolean value."
(let ((value (cond ((eql t/f t) #xFF)
((eql t/f nil) #x00)
(t (error "Unknown boolean value.")))))
(nconc (ber-tag 'universal 'primitive #x01) (ber-length 1) (list value))))
(defun seq-integer (int)
"BER encode an integer value."
(assert (integerp int))
(let ((bytes (int->octet-list int)))
(nconc (ber-tag 'universal 'primitive #x02) (ber-length bytes) bytes)))
(defun seq-enumerated (int)
"BER encode an enumeration value."
(assert (integerp int))
(let ((bytes (int->octet-list int)))
(nconc (ber-tag 'universal 'primitive #x0A) (ber-length bytes) bytes)))
(defun seq-octet-string (string)
"BER encode an octet string value."
(let ((bytes (seq-primitive-string string)))
(nconc (ber-tag 'universal 'primitive #x04) (ber-length bytes) bytes)))
(defun seq-sequence (tlv-seq)
"BER encode a sequence of TLVs."
(assert (or (null tlv-seq) (consp tlv-seq)))
(nconc (ber-tag 'universal 'constructed #x10) (ber-length tlv-seq) tlv-seq))
(defun seq-set (tlv-set)
"BER encode a set of TLVs."
(assert (consp tlv-set))
(nconc (ber-tag 'universal 'constructed #x11) (ber-length tlv-set) tlv-set))
(defun seq-primitive-choice (int &optional data)
"BER encode a context-specific choice."
(assert (integerp int))
(let ((tag (ber-tag 'context 'primitive int)))
(etypecase data
(null (append tag (list #x00)))
(string (if (string= data "")
(append tag (list #x00))
(let ((bytes (string->char-code-list data)))
(append tag (ber-length bytes)
bytes))))
(integer (seq-integer data))
(boolean (seq-boolean data))
(symbol (let ((str (symbol-name data)))
(let ((bytes (string->char-code-list str)))
(append tag (ber-length bytes)
bytes)))))))
(defun seq-constructed-choice (int &optional data)
"BER encode a context-specific, constructed choice."
(assert (integerp int))
(let ((tag (ber-tag 'context 'constructed int)))
(etypecase data
(string (let* ((val (seq-octet-string data))
(len (ber-length val)))
(append tag len val)))
(sequence (let ((len (ber-length data)))
(append tag len data))))))
(defun seq-primitive-string (string)
"BER encode a string/symbol for use in a primitive context."
(assert (or (stringp string) (symbolp string) (typep string 'list)
(typep string '(array (unsigned-byte 8)))))
(cond ((or (stringp string) (symbolp string))
(string->char-code-list string))
((listp string)
string)
((typep string '(array (unsigned-byte 8)))
(coerce string 'list))
(t (error "~A is not a string, symbol, list of octets or vector of octets" string))))
(defun seq-attribute-alist (atts)
"BER encode an entry object's attribute alist (for use in add)."
(seq-sequence (mapcan #'(lambda (i)
(seq-att-and-values (car i) (cdr i))) atts)))
(defun seq-attribute-list (att-list)
"BER encode a list of attributes (for use in search)."
(seq-sequence (mapcan #'seq-octet-string att-list)))
(defun seq-attribute-assertion (att val)
"BER encode an ldap attribute assertion (for use in compare)."
(seq-sequence (nconc (seq-octet-string att) (seq-octet-string val))))
(defun seq-attribute-value-assertion (att val)
"BER encode an ldap attribute value assertion (for use in filters)."
(nconc (seq-octet-string att) (seq-octet-string val)))
(defun seq-att-and-values (att vals)
"BER encode an attribute and set of values (for use in modify)."
(unless (listp vals) (setf vals (list vals)))
(seq-sequence (nconc (seq-octet-string att)
(seq-set (mapcan #'seq-octet-string vals)))))
(defun ldap-filter-lexer (string)
(declare (type string string))
(let ((start 0)
(end (length string))
(start-condition nil))
(declare (type fixnum start end))
(labels ((looking-at (str &key (test #'string=))
(declare (type string str))
(let ((len-str (length str)))
(and (<= len-str (- end start))
(funcall test str string :start2 start :end2 (+ start len-str)))))
(accept (match terminal &key (test #'string=))
(declare (type (or symbol string) match))
(let ((match-str (if (symbolp match)
(symbol-name match)
match)))
(when (looking-at match-str :test test)
(multiple-value-prog1
(values terminal match)
(incf start (length match-str))))))
(accept-while (matcher terminal)
(let ((matched
(loop for i from start below end
while (funcall matcher (char string i))
finally (return (prog1
(subseq string start i)
(setq start i))))))
(when (not (zerop (length matched)))
(values terminal matched)))))
(lambda ()
(block nil
(macrolet ((try-match (pattern &body body)
(let ((gterminal (gensym "TERMINAL"))
(gvalue (gensym "VALUE")))
`(multiple-value-bind (,gterminal ,gvalue) ,pattern
(when ,gterminal
,@body
(return (values ,gterminal ,gvalue)))))))
(when (= start end)
nil)
(when (eq start-condition 'value)
(setq start-condition nil)
(try-match (accept-while (lambda (c) (char/= c #\))) 'string)))
(try-match (accept "(" 'lpar))
(try-match (accept ")" 'rpar))
(try-match (accept "&" 'and))
(try-match (accept "|" 'or))
(try-match (accept "!" 'not))
(try-match (accept '>= 'filtertype) (setq start-condition 'value))
(try-match (accept '<= 'filtertype) (setq start-condition 'value))
(try-match (accept '~= 'filtertype) (setq start-condition 'value))
(try-match (accept '= 'filtertype) (setq start-condition 'value))
(try-match (accept-while #'alphanumericp 'attr))))))))
(yacc:define-parser *ldap-filter-parser*
(:start-symbol filter)
(:terminals (lpar rpar semicolon colon and or not
filtertype attr string))
(:print-derives-epsilon nil)
;; productions
(filter
(lpar filtercomp rpar (lambda (dummy1 val dummy2) (declare (ignore dummy1 dummy2)) val))
item)
(filtercomp
(and filterlist (lambda (op list) (declare (ignore op)) (cons (intern "&") list)))
(or filterlist (lambda (op list) (declare (ignore op)) (cons (intern "|") list)))
(not filter (lambda (op element) (declare (ignore op)) (list (intern "!") element)))
item)
(filterlist
(filter #'list)
(filter filterlist #'cons))
(item
(simple #'identity)
#+nil extensible)
(simple
(attr filtertype value
(lambda (attr type value)
(if (eq type '=)
(cond ((string= value "*")
(list (intern "=*") attr))
((position #\* value :test #'char=)
(list (intern "SUBSTRING") attr value))
(t
(list type attr value)))
(list type attr value)))))
(extensible
;; whatever
)
(value
string))
(defun listify-filter (filter)
(let ((parsed-filter (yacc:parse-with-lexer (ldap-filter-lexer filter) *ldap-filter-parser*)))
parsed-filter))
(defun seq-filter (filter)
(let* ((filter (etypecase filter
(cons filter)
#+nil
;; FIXME: can't see that symbol can appear
;; here... and if it does, we cannot take the
;; #'car of it
(symbol filter)
(string (listify-filter filter))))
(op (intern (symbol-name (car filter)) :trivial-ldap)))
(when (eq op 'or)
(setq op '\|))
(when (eq op 'and)
(setq op '&))
(when (eq op 'not)
(setq op '!))
(when (eq op 'wildcard)
(setq op 'substring))
(cond
((eq '! op) (seq-constructed-choice (ldap-filter-comparison-char op)
(seq-filter (second filter))))
((or (eq '& op) (eq '\| op))
(seq-constructed-choice (ldap-filter-comparison-char op)
(mapcan #'seq-filter (cdr filter))))
((eq '=* op) (seq-primitive-choice
(ldap-filter-comparison-char op) (second filter)))
((or (eq '= op)
(eq '<= op) (eq '>= op) (eq '~= op))
(seq-constructed-choice (ldap-filter-comparison-char op)
(seq-attribute-value-assertion
(second filter) (third filter))))
((eq 'substring op)
(seq-constructed-choice (ldap-filter-comparison-char 'substring)
(append (seq-octet-string (second filter))
(seq-substrings (third filter)))))
(t (error 'ldap-filter-error
:mesg "unable to determine operator." :filter filter)))))
(defun seq-substrings (value)
"Given a search value with *s in it, return a BER encoded list."
(let ((list (etypecase value
(symbol (split-substring (symbol-name value)))
(string (split-substring value))))
(initial ()) (any ()) (final ()))
(when (string/= "*" (car list)) ; initial
(setf initial (seq-primitive-choice (ldap-substring 'initial)
(car list))))
(setf list (cdr list)) ; last
(when (and (> (length list) 0) (string/= "*" (car (last list))))
(setf final (seq-primitive-choice (ldap-substring 'final)
(car (last list)))))
(setf list (butlast list))
(when (> (length list) 0) ; any
(dolist (i (remove "*" list :test #'string=))
(setf any (append any (seq-primitive-choice
(ldap-substring 'any) i)))))
(seq-sequence (nconc initial any final))))
(defun valid-ldap-response-p (tag-byte)
"Return T if this is the valid initial tag byte for an LDAP response."
(if (= tag-byte (car (ber-tag 'universal 'constructed #x10))) t nil))
;;;;
;;;; referrer class & methods.
;;;;
(defclass referrer ()
((url :initarg :url
:initform (error "No URL specified")
:type string
:accessor url)))
(defun new-referrer (url)
"Instantiate a new referrer object."
(make-instance 'referrer :url url))
;;;;
;;;; entry class & methods.
;;;;
(defclass entry ()
((dn :initarg :dn :type string :accessor dn)
(rdn :initarg :rdn :type string :accessor rdn)
(attrs :initarg :attrs :type cons :accessor attrs)))
(defmethod dn ((dn string)) dn)
(defun rdn-from-dn (dn)
"Given a DN, return its RDN and a cons of (att . val)"
(let* ((eql-pos (position #\= dn))
(rdn (subseq dn 0 (position #\, dn)))
(rdn-att (subseq rdn 0 eql-pos))
(rdn-val (subseq rdn (1+ eql-pos) (length rdn))))
(values rdn (list (intern (string-upcase rdn-att) :keyword) rdn-val))))
(defun new-entry (dn &key (attrs ()) (infer-rdn t))
"Instantiate a new entry object."
(multiple-value-bind (rdn rdn-list) (rdn-from-dn dn)
(when (and infer-rdn
(not (assoc (car rdn-list) attrs)))
(setf attrs (acons (car rdn-list) (cdr rdn-list) attrs)))
(make-instance 'entry :dn dn :rdn rdn :attrs attrs)))
(defmethod change-rdn ((entry entry) new-rdn)
"Change the DN and RDN of the specified object, don't touch LDAP."
(let* ((len-old (length (rdn entry)))
(dn (concatenate 'string new-rdn (subseq (dn entry) len-old))))
(multiple-value-bind (old-rdn old-rdn-parts) (rdn-from-dn (dn entry))
(declare (ignore old-rdn))
(del-attr entry (first old-rdn-parts) (second old-rdn-parts)))
(setf (dn entry) dn
(rdn entry) new-rdn)
(multiple-value-bind (new-rdn new-rdn-parts) (rdn-from-dn (dn entry))
(declare (ignore new-rdn))
(add-attr entry (first new-rdn-parts) (second new-rdn-parts)))))
(defmethod attr-value ((entry entry) attr)
"Given an entry object and attr name (symbol), return list of values."
(let ((val (cdr (assoc attr (attrs entry)))))
(cond
((null val) nil)
((consp val) val)
(t (list val)))))
(defmethod attr-value ((entry entry) (attrs list))
"Given an entry object and list of attr names (as symbols),
return list of lists of attributes."
(mapcar #'(lambda (attr) (attr-value entry attr)) attrs))
(defmethod attr-list ((entry entry))
"Given an entry object, return a list of its attributes."
(map 'list #'car (attrs entry)))
(defmethod add-attr ((entry entry) attr vals)
"Add an attribute to entry object, do not update LDAP."
(let ((old-val-list (attr-value entry attr))
(new-val-list (if (consp vals) vals (list vals))))
(replace-attr entry attr (append old-val-list new-val-list))))
(defmethod del-attr ((entry entry) attr &optional vals)
"Delete an attribute from entry object, do not update LDAP"
(let ((old-val (attr-value entry attr))
(new-val (if (consp vals) vals (list vals))))
(dolist (val new-val)
(setf old-val (remove-if #'(lambda (x) (string= val x)) old-val)))
(if (or (null (car old-val))
(null (car new-val)))
(setf (attrs entry)
(remove-if #'(lambda (x) (eq (car x) attr)) (attrs entry)))
(replace-attr entry attr old-val))))
(defmethod replace-attr ((entry entry) attr vals)
"Replace attribute values from entry object, do not update LDAP"
(let ((vals (remove-if #'null vals)))
(if (consp (assoc attr (attrs entry)))
(rplacd (assoc attr (attrs entry)) vals)
(setf (attrs entry) (acons attr vals (attrs entry))))))
(defmethod ldif ((entry entry))
"Return an ldif formatted representation of entry."
(let ((results (format nil "DN: ~A~%" (dn entry))))
(dolist (att (attr-list entry) results)
(dolist (val (attr-value entry att))
(setf results (format nil "~@[~A~]~A: ~A~%" results att val))))))
(define-condition probably-binary-field-error (error)
((key :initarg :key
:reader probably-binary-field-error-key
:documentation "The name of the key which has binary content"))
(:report (lambda (condition out)
(format out "Probably a binary field: ~a" (probably-binary-field-error-key condition))))
(:documentation "Condition that is signalled when a binary field is being parsed as a string"))
(defun list-entries-to-string (key list)
(handler-case
(mapcar #'char-code-vec->string list)
(error ()
(error 'probably-binary-field-error :key key))))
(defun attrs-from-list (x)
(restart-case
(let* ((key (char-code-vec->string (car x)))
(value (restart-case
(if (attribute-binary-p key)
(cadr x)
(list-entries-to-string key (cadr x)))
(handle-as-binary ()
:report "Handle this attribute as binary"
(cadr x))
(handle-as-binary-and-add-known ()
:report "Handle this attribute as binary and add it to the list of binary attributes"
(setf (attribute-binary-p key) t)
(cadr x)))))
(list (cons (intern (string-upcase key) :keyword) value)))
(skip-entry ()
:report "Ignore this attribute"
nil)))
(defun new-entry-from-list (list)
"Create an entry object from the list return by search."
(let ((dn (char-code-vec->string (car list)))
(attrs (mapcan #'attrs-from-list (cadr list))))
(new-entry dn :attrs attrs)))
;;;
;;;
;;;
(defclass response-vec ()
((vec :accessor response-vec/vec :initarg :vec)
(ptr :accessor response-vec/ptr :initform 0)))
(defun make-response-vec (size)
(make-instance 'response-vec :vec (make-array size :element-type '(unsigned-byte 8))))
(defun copy-response-vec (vec &key (start 0) end)
(with-slots (vec ptr) vec
(let ((end (or end (- (length vec) ptr))))
(assert (<= (+ ptr start) (length vec)))
(make-instance 'response-vec :vec
(make-array (- end start)
:element-type '(unsigned-byte 8)
:displaced-to vec :displaced-index-offset (+ ptr start))))))
(defmethod pop-byte ((response-vec response-vec))
(with-slots (vec ptr) response-vec
(assert (< ptr (length vec)))
(prog1 (aref vec ptr)