ldap.el 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. ;;; ldap.el --- client interface to LDAP for Emacs
  2. ;; Copyright (C) 1998-2017 Free Software Foundation, Inc.
  3. ;; Author: Oscar Figueiredo <oscar@cpe.fr>
  4. ;; Maintainer: emacs-devel@gnu.org
  5. ;; Created: April 1998
  6. ;; Keywords: comm
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; This package provides basic functionality to perform searches on LDAP
  20. ;; servers. It requires a command line utility generally named
  21. ;; `ldapsearch' to actually perform the searches. That program can be
  22. ;; found in all LDAP developer kits such as:
  23. ;; - UM-LDAP 3.3 (http://www.umich.edu/~dirsvcs/ldap/)
  24. ;; - OpenLDAP (http://www.openldap.org/)
  25. ;;; Code:
  26. (require 'custom)
  27. (require 'password-cache)
  28. (autoload 'auth-source-search "auth-source")
  29. (defgroup ldap nil
  30. "Lightweight Directory Access Protocol."
  31. :version "21.1"
  32. :group 'comm)
  33. (defcustom ldap-default-host nil
  34. "Default LDAP server.
  35. A TCP port number can be appended to that name using a colon as
  36. a separator."
  37. :type '(choice (string :tag "Host name")
  38. (const :tag "Use library default" nil)))
  39. (defcustom ldap-default-port nil
  40. "Default TCP port for LDAP connections.
  41. Initialized from the LDAP library at build time. Default value is 389."
  42. :type '(choice (const :tag "Use library default" nil)
  43. (integer :tag "Port number")))
  44. (defcustom ldap-default-base nil
  45. "Default base for LDAP searches.
  46. This is a string using the syntax of RFC 1779.
  47. For instance, \"o=ACME, c=US\" limits the search to the
  48. Acme organization in the United States."
  49. :type '(choice (const :tag "Use library default" nil)
  50. (string :tag "Search base")))
  51. (defcustom ldap-host-parameters-alist nil
  52. "Alist of host-specific options for LDAP transactions.
  53. The format of each list element is (HOST PROP1 VAL1 PROP2 VAL2 ...).
  54. HOST is the hostname of an LDAP server (with an optional TCP port number
  55. appended to it using a colon as a separator).
  56. PROPn and VALn are property/value pairs describing parameters for the server.
  57. Valid properties include:
  58. `binddn' is the distinguished name of the user to bind as
  59. (in RFC 1779 syntax).
  60. `passwd' is the password to use for simple authentication.
  61. `auth' is the authentication method to use.
  62. Possible values are: `simple', `krbv41' and `krbv42'.
  63. `base' is the base for the search as described in RFC 1779.
  64. `scope' is one of the three symbols `subtree', `base' or `onelevel'.
  65. `deref' is one of the symbols `never', `always', `search' or `find'.
  66. `timelimit' is the timeout limit for the connection in seconds.
  67. `sizelimit' is the maximum number of matches to return."
  68. :type '(repeat :menu-tag "Host parameters"
  69. :tag "Host parameters"
  70. (list :menu-tag "Host parameters"
  71. :tag "Host parameters"
  72. :value nil
  73. (string :tag "Host name")
  74. (checklist :inline t
  75. :greedy t
  76. (list
  77. :tag "Search Base"
  78. :inline t
  79. (const :tag "Search Base" base)
  80. string)
  81. (list
  82. :tag "Binding DN"
  83. :inline t
  84. (const :tag "Binding DN" binddn)
  85. string)
  86. (list
  87. :tag "Password"
  88. :inline t
  89. (const :tag "Password" passwd)
  90. string)
  91. (list
  92. :tag "Authentication Method"
  93. :inline t
  94. (const :tag "Authentication Method" auth)
  95. (choice
  96. (const :menu-tag "None" :tag "None" nil)
  97. (const :menu-tag "Simple" :tag "Simple" simple)
  98. (const :menu-tag "Kerberos 4.1" :tag "Kerberos 4.1" krbv41)
  99. (const :menu-tag "Kerberos 4.2" :tag "Kerberos 4.2" krbv42)))
  100. (list
  101. :tag "Search Scope"
  102. :inline t
  103. (const :tag "Search Scope" scope)
  104. (choice
  105. (const :menu-tag "Default" :tag "Default" nil)
  106. (const :menu-tag "Subtree" :tag "Subtree" subtree)
  107. (const :menu-tag "Base" :tag "Base" base)
  108. (const :menu-tag "One Level" :tag "One Level" onelevel)))
  109. (list
  110. :tag "Dereferencing"
  111. :inline t
  112. (const :tag "Dereferencing" deref)
  113. (choice
  114. (const :menu-tag "Default" :tag "Default" nil)
  115. (const :menu-tag "Never" :tag "Never" never)
  116. (const :menu-tag "Always" :tag "Always" always)
  117. (const :menu-tag "When searching" :tag "When searching" search)
  118. (const :menu-tag "When locating base" :tag "When locating base" find)))
  119. (list
  120. :tag "Time Limit"
  121. :inline t
  122. (const :tag "Time Limit" timelimit)
  123. (integer :tag "(in seconds)"))
  124. (list
  125. :tag "Size Limit"
  126. :inline t
  127. (const :tag "Size Limit" sizelimit)
  128. (integer :tag "(number of records)"))))))
  129. (defcustom ldap-ldapsearch-prog "ldapsearch"
  130. "The name of the ldapsearch command line program."
  131. :type '(string :tag "`ldapsearch' Program"))
  132. (defcustom ldap-ldapsearch-args '("-LL" "-tt")
  133. "A list of additional arguments to pass to `ldapsearch'."
  134. :type '(repeat :tag "`ldapsearch' Arguments"
  135. (string :tag "Argument")))
  136. (defcustom ldap-ldapsearch-password-prompt-regexp "Enter LDAP Password: "
  137. "A regular expression used to recognize the `ldapsearch'
  138. program's password prompt."
  139. :type 'regexp
  140. :version "25.1")
  141. (defcustom ldap-ignore-attribute-codings nil
  142. "If non-nil, do not encode/decode LDAP attribute values."
  143. :type 'boolean)
  144. (defcustom ldap-default-attribute-decoder nil
  145. "Decoder function to use for attributes whose syntax is unknown."
  146. :type 'symbol)
  147. (defcustom ldap-coding-system 'utf-8
  148. "Coding system of LDAP string values.
  149. LDAP v3 specifies the coding system of strings to be UTF-8."
  150. :type 'symbol)
  151. (defvar ldap-attribute-syntax-encoders
  152. [nil ; 1 ACI Item N
  153. nil ; 2 Access Point Y
  154. nil ; 3 Attribute Type Description Y
  155. nil ; 4 Audio N
  156. nil ; 5 Binary N
  157. nil ; 6 Bit String Y
  158. ldap-encode-boolean ; 7 Boolean Y
  159. nil ; 8 Certificate N
  160. nil ; 9 Certificate List N
  161. nil ; 10 Certificate Pair N
  162. ldap-encode-country-string ; 11 Country String Y
  163. ldap-encode-string ; 12 DN Y
  164. nil ; 13 Data Quality Syntax Y
  165. nil ; 14 Delivery Method Y
  166. ldap-encode-string ; 15 Directory String Y
  167. nil ; 16 DIT Content Rule Description Y
  168. nil ; 17 DIT Structure Rule Description Y
  169. nil ; 18 DL Submit Permission Y
  170. nil ; 19 DSA Quality Syntax Y
  171. nil ; 20 DSE Type Y
  172. nil ; 21 Enhanced Guide Y
  173. nil ; 22 Facsimile Telephone Number Y
  174. nil ; 23 Fax N
  175. nil ; 24 Generalized Time Y
  176. nil ; 25 Guide Y
  177. nil ; 26 IA5 String Y
  178. number-to-string ; 27 INTEGER Y
  179. nil ; 28 JPEG N
  180. nil ; 29 Master And Shadow Access Points Y
  181. nil ; 30 Matching Rule Description Y
  182. nil ; 31 Matching Rule Use Description Y
  183. nil ; 32 Mail Preference Y
  184. nil ; 33 MHS OR Address Y
  185. nil ; 34 Name And Optional UID Y
  186. nil ; 35 Name Form Description Y
  187. nil ; 36 Numeric String Y
  188. nil ; 37 Object Class Description Y
  189. nil ; 38 OID Y
  190. nil ; 39 Other Mailbox Y
  191. nil ; 40 Octet String Y
  192. ldap-encode-address ; 41 Postal Address Y
  193. nil ; 42 Protocol Information Y
  194. nil ; 43 Presentation Address Y
  195. ldap-encode-string ; 44 Printable String Y
  196. nil ; 45 Subtree Specification Y
  197. nil ; 46 Supplier Information Y
  198. nil ; 47 Supplier Or Consumer Y
  199. nil ; 48 Supplier And Consumer Y
  200. nil ; 49 Supported Algorithm N
  201. nil ; 50 Telephone Number Y
  202. nil ; 51 Teletex Terminal Identifier Y
  203. nil ; 52 Telex Number Y
  204. nil ; 53 UTC Time Y
  205. nil ; 54 LDAP Syntax Description Y
  206. nil ; 55 Modify Rights Y
  207. nil ; 56 LDAP Schema Definition Y
  208. nil ; 57 LDAP Schema Description Y
  209. nil ; 58 Substring Assertion Y
  210. ]
  211. "A vector of functions used to encode LDAP attribute values.
  212. The sequence of functions corresponds to the sequence of LDAP attribute syntax
  213. object identifiers of the form 1.3.6.1.4.1.1466.1115.121.1.* as defined in
  214. RFC2252 section 4.3.2")
  215. (defvar ldap-attribute-syntax-decoders
  216. [nil ; 1 ACI Item N
  217. nil ; 2 Access Point Y
  218. nil ; 3 Attribute Type Description Y
  219. nil ; 4 Audio N
  220. nil ; 5 Binary N
  221. nil ; 6 Bit String Y
  222. ldap-decode-boolean ; 7 Boolean Y
  223. nil ; 8 Certificate N
  224. nil ; 9 Certificate List N
  225. nil ; 10 Certificate Pair N
  226. ldap-decode-string ; 11 Country String Y
  227. ldap-decode-string ; 12 DN Y
  228. nil ; 13 Data Quality Syntax Y
  229. nil ; 14 Delivery Method Y
  230. ldap-decode-string ; 15 Directory String Y
  231. nil ; 16 DIT Content Rule Description Y
  232. nil ; 17 DIT Structure Rule Description Y
  233. nil ; 18 DL Submit Permission Y
  234. nil ; 19 DSA Quality Syntax Y
  235. nil ; 20 DSE Type Y
  236. nil ; 21 Enhanced Guide Y
  237. nil ; 22 Facsimile Telephone Number Y
  238. nil ; 23 Fax N
  239. nil ; 24 Generalized Time Y
  240. nil ; 25 Guide Y
  241. nil ; 26 IA5 String Y
  242. string-to-number ; 27 INTEGER Y
  243. nil ; 28 JPEG N
  244. nil ; 29 Master And Shadow Access Points Y
  245. nil ; 30 Matching Rule Description Y
  246. nil ; 31 Matching Rule Use Description Y
  247. nil ; 32 Mail Preference Y
  248. nil ; 33 MHS OR Address Y
  249. nil ; 34 Name And Optional UID Y
  250. nil ; 35 Name Form Description Y
  251. nil ; 36 Numeric String Y
  252. nil ; 37 Object Class Description Y
  253. nil ; 38 OID Y
  254. nil ; 39 Other Mailbox Y
  255. nil ; 40 Octet String Y
  256. ldap-decode-address ; 41 Postal Address Y
  257. nil ; 42 Protocol Information Y
  258. nil ; 43 Presentation Address Y
  259. ldap-decode-string ; 44 Printable String Y
  260. nil ; 45 Subtree Specification Y
  261. nil ; 46 Supplier Information Y
  262. nil ; 47 Supplier Or Consumer Y
  263. nil ; 48 Supplier And Consumer Y
  264. nil ; 49 Supported Algorithm N
  265. nil ; 50 Telephone Number Y
  266. nil ; 51 Teletex Terminal Identifier Y
  267. nil ; 52 Telex Number Y
  268. nil ; 53 UTC Time Y
  269. nil ; 54 LDAP Syntax Description Y
  270. nil ; 55 Modify Rights Y
  271. nil ; 56 LDAP Schema Definition Y
  272. nil ; 57 LDAP Schema Description Y
  273. nil ; 58 Substring Assertion Y
  274. ]
  275. "A vector of functions used to decode LDAP attribute values.
  276. The sequence of functions corresponds to the sequence of LDAP attribute syntax
  277. object identifiers of the form 1.3.6.1.4.1.1466.1115.121.1.* as defined in
  278. RFC2252 section 4.3.2")
  279. (defvar ldap-attribute-syntaxes-alist
  280. '((createtimestamp . 24)
  281. (modifytimestamp . 24)
  282. (creatorsname . 12)
  283. (modifiersname . 12)
  284. (subschemasubentry . 12)
  285. (attributetypes . 3)
  286. (objectclasses . 37)
  287. (matchingrules . 30)
  288. (matchingruleuse . 31)
  289. (namingcontexts . 12)
  290. (altserver . 26)
  291. (supportedextension . 38)
  292. (supportedcontrol . 38)
  293. (supportedsaslmechanisms . 15)
  294. (supportedldapversion . 27)
  295. (ldapsyntaxes . 16)
  296. (ditstructurerules . 17)
  297. (nameforms . 35)
  298. (ditcontentrules . 16)
  299. (objectclass . 38)
  300. (aliasedobjectname . 12)
  301. (cn . 15)
  302. (sn . 15)
  303. (serialnumber . 44)
  304. (c . 15)
  305. (l . 15)
  306. (st . 15)
  307. (street . 15)
  308. (o . 15)
  309. (ou . 15)
  310. (title . 15)
  311. (description . 15)
  312. (searchguide . 25)
  313. (businesscategory . 15)
  314. (postaladdress . 41)
  315. (postalcode . 15)
  316. (postofficebox . 15)
  317. (physicaldeliveryofficename . 15)
  318. (telephonenumber . 50)
  319. (telexnumber . 52)
  320. (telexterminalidentifier . 51)
  321. (facsimiletelephonenumber . 22)
  322. (x121address . 36)
  323. (internationalisdnnumber . 36)
  324. (registeredaddress . 41)
  325. (destinationindicator . 44)
  326. (preferreddeliverymethod . 14)
  327. (presentationaddress . 43)
  328. (supportedapplicationcontext . 38)
  329. (member . 12)
  330. (owner . 12)
  331. (roleoccupant . 12)
  332. (seealso . 12)
  333. (userpassword . 40)
  334. (usercertificate . 8)
  335. (cacertificate . 8)
  336. (authorityrevocationlist . 9)
  337. (certificaterevocationlist . 9)
  338. (crosscertificatepair . 10)
  339. (name . 15)
  340. (givenname . 15)
  341. (initials . 15)
  342. (generationqualifier . 15)
  343. (x500uniqueidentifier . 6)
  344. (dnqualifier . 44)
  345. (enhancedsearchguide . 21)
  346. (protocolinformation . 42)
  347. (distinguishedname . 12)
  348. (uniquemember . 34)
  349. (houseidentifier . 15)
  350. (supportedalgorithms . 49)
  351. (deltarevocationlist . 9)
  352. (dmdname . 15)
  353. (carlicense . 15)
  354. (departmentnumber . 15)
  355. (displayname . 15)
  356. (employeenumber . 15)
  357. (employeetype . 15)
  358. (jpegphoto . 28)
  359. (preferredlanguage . 15)
  360. (usersmimecertificate . 5)
  361. (userpkcs12 . 5))
  362. "A map of LDAP attribute names to their type object id minor number.
  363. This table is built from RFC2252 Section 5, RFC2256 Section 5 and
  364. RFC2798 Section 9.1.1")
  365. ;; Coding/decoding functions
  366. (defun ldap-encode-boolean (bool)
  367. (if bool
  368. "TRUE"
  369. "FALSE"))
  370. (defun ldap-decode-boolean (str)
  371. (cond
  372. ((string-equal str "TRUE")
  373. t)
  374. ((string-equal str "FALSE")
  375. nil)
  376. (t
  377. (error "Wrong LDAP boolean string: %s" str))))
  378. (defun ldap-encode-country-string (str)
  379. ;; We should do something useful here...
  380. (if (not (= 2 (length str)))
  381. (error "Invalid country string: %s" str)))
  382. (defun ldap-decode-string (str)
  383. (decode-coding-string str ldap-coding-system))
  384. (defun ldap-encode-string (str)
  385. (encode-coding-string str ldap-coding-system))
  386. (defun ldap-decode-address (str)
  387. (mapconcat 'ldap-decode-string
  388. (split-string str "\\$")
  389. "\n"))
  390. (defun ldap-encode-address (str)
  391. (mapconcat 'ldap-encode-string
  392. (split-string str "\n")
  393. "$"))
  394. ;; LDAP protocol functions
  395. (defun ldap-get-host-parameter (host parameter)
  396. "Get the value of PARAMETER for HOST in `ldap-host-parameters-alist'."
  397. (plist-get (cdr (assoc host ldap-host-parameters-alist))
  398. parameter))
  399. (defun ldap-decode-attribute (attr)
  400. "Decode the attribute/value pair ATTR according to LDAP rules.
  401. The attribute name is looked up in `ldap-attribute-syntaxes-alist'
  402. and the corresponding decoder is then retrieved from
  403. `ldap-attribute-syntax-decoders' and applied on the value(s)."
  404. (let* ((name (car attr))
  405. (values (cdr attr))
  406. (syntax-id (cdr (assq (intern (downcase name))
  407. ldap-attribute-syntaxes-alist)))
  408. decoder)
  409. (if syntax-id
  410. (setq decoder (aref ldap-attribute-syntax-decoders
  411. (1- syntax-id)))
  412. (setq decoder ldap-default-attribute-decoder))
  413. (if decoder
  414. (cons name (mapcar decoder values))
  415. attr)))
  416. (defun ldap-search (filter &optional host attributes attrsonly withdn)
  417. "Perform an LDAP search.
  418. FILTER is the search filter in RFC1558 syntax.
  419. HOST is the LDAP host on which to perform the search.
  420. ATTRIBUTES are the specific attributes to retrieve, nil means
  421. retrieve all.
  422. ATTRSONLY, if non-nil, retrieves the attributes only, without
  423. the associated values.
  424. If WITHDN is non-nil, each entry in the result will be prepended with
  425. its distinguished name WITHDN.
  426. Additional search parameters can be specified through
  427. `ldap-host-parameters-alist', which see."
  428. (interactive "sFilter:")
  429. (or host
  430. (setq host ldap-default-host)
  431. (error "No LDAP host specified"))
  432. (let* ((host-plist (cdr (assoc host ldap-host-parameters-alist)))
  433. (result (ldap-search-internal `(host ,host
  434. filter ,filter
  435. attributes ,attributes
  436. attrsonly ,attrsonly
  437. withdn ,withdn
  438. ,@host-plist))))
  439. (if ldap-ignore-attribute-codings
  440. result
  441. (mapcar (lambda (record)
  442. (mapcar #'ldap-decode-attribute record))
  443. result))))
  444. (defun ldap-password-read (host)
  445. "Read LDAP password for HOST.
  446. If the password is cached, it is read from the cache, otherwise the user
  447. is prompted for the password. If `password-cache' is non-nil the password
  448. is verified and cached. The `password-cache-expiry' variable
  449. controls for how long the password is cached.
  450. This function can be specified for the `passwd' property in
  451. `ldap-host-parameters-alist' when interactive password prompting
  452. is desired for HOST."
  453. ;; Add ldap: namespace to allow empty string for default host.
  454. (let* ((host-key (concat "ldap:" host))
  455. (password (password-read
  456. (format "Enter LDAP Password%s: "
  457. (if (equal host "")
  458. ""
  459. (format " for %s" host)))
  460. host-key)))
  461. (when (and password-cache
  462. (not (password-in-cache-p host-key))
  463. ;; Confirm the password is valid before adding it to
  464. ;; the password cache. ldap-search-internal will throw
  465. ;; an error if the password is invalid.
  466. (not (ldap-search-internal
  467. `(host ,host
  468. ;; Specify an arbitrary filter that should
  469. ;; produce no results, since only
  470. ;; authentication success is of interest.
  471. filter "emacs-test-password="
  472. attributes nil
  473. attrsonly nil
  474. withdn nil
  475. ;; Preempt passwd ldap-password-read
  476. ;; setting in ldap-host-parameters-alist.
  477. passwd ,password
  478. ,@(cdr
  479. (assoc
  480. host
  481. ldap-host-parameters-alist))))))
  482. (password-cache-add host-key password))
  483. password))
  484. (defun ldap-search-internal (search-plist)
  485. "Perform a search on a LDAP server.
  486. SEARCH-PLIST is a property list describing the search request.
  487. Valid keys in that list are:
  488. `auth-source', if non-nil, will use `auth-source-search' and
  489. will grab the :host, :secret, :base, and (:user or :binddn)
  490. tokens into the `host', `passwd', `base', and `binddn' parameters
  491. respectively if they are not provided in SEARCH-PLIST. So for
  492. instance *each* of these netrc lines has the same effect if you
  493. ask for the host \"ldapserver:2400\":
  494. machine ldapserver:2400 login myDN secret myPassword base myBase
  495. machine ldapserver:2400 binddn myDN secret myPassword port ldap
  496. login myDN secret myPassword base myBase
  497. but if you have more than one in your netrc file, only the first
  498. matching one will be used. Note the \"port ldap\" part is NOT
  499. required.
  500. `host' is a string naming one or more (blank-separated) LDAP servers
  501. to try to connect to. Each host name may optionally be of the form HOST:PORT.
  502. `filter' is a filter string for the search as described in RFC 1558.
  503. `attributes' is a list of strings indicating which attributes to retrieve
  504. for each matching entry. If nil, return all available attributes.
  505. `attrsonly', if non-nil, indicates that only attributes are retrieved,
  506. not their associated values.
  507. `auth' is one of the symbols `simple', `krbv41' or `krbv42'.
  508. `base' is the base for the search as described in RFC 1779.
  509. `scope' is one of the three symbols `sub', `base' or `one'.
  510. `binddn' is the distinguished name of the user to bind as (in
  511. RFC 1779 syntax).
  512. `passwd' is the password to use for simple authentication.
  513. `deref' is one of the symbols `never', `always', `search' or `find'.
  514. `timelimit' is the timeout limit for the connection in seconds.
  515. `sizelimit' is the maximum number of matches to return.
  516. `withdn' if non-nil each entry in the result will be prepended with
  517. its distinguished name DN.
  518. The function returns a list of matching entries. Each entry is itself
  519. an alist of attribute/value pairs."
  520. (let* ((buf (get-buffer-create " *ldap-search*"))
  521. (bufval (get-buffer-create " *ldap-value*"))
  522. (host (or (plist-get search-plist 'host)
  523. ldap-default-host))
  524. ;; find entries with port "ldap" that match the requested host if any
  525. (asfound (when (plist-get search-plist 'auth-source)
  526. (nth 0 (auth-source-search :host (or host t)
  527. :create t))))
  528. ;; if no host was requested, get it from the auth-source entry
  529. (host (or host (plist-get asfound :host)))
  530. ;; get the password from the auth-source
  531. (passwd (or (plist-get search-plist 'passwd)
  532. (plist-get asfound :secret)))
  533. ;; convert the password from a function call if needed
  534. (passwd (if (functionp passwd)
  535. (if (eq passwd 'ldap-password-read)
  536. (funcall passwd host)
  537. (funcall passwd))
  538. passwd))
  539. ;; get the binddn from the search-list or from the
  540. ;; auth-source user or binddn tokens
  541. (binddn (or (plist-get search-plist 'binddn)
  542. (plist-get asfound :user)
  543. (plist-get asfound :binddn)))
  544. (base (or (plist-get search-plist 'base)
  545. (plist-get asfound :base)
  546. ldap-default-base))
  547. (filter (plist-get search-plist 'filter))
  548. (attributes (plist-get search-plist 'attributes))
  549. (attrsonly (plist-get search-plist 'attrsonly))
  550. (scope (plist-get search-plist 'scope))
  551. (auth (plist-get search-plist 'auth))
  552. (deref (plist-get search-plist 'deref))
  553. (timelimit (plist-get search-plist 'timelimit))
  554. (sizelimit (plist-get search-plist 'sizelimit))
  555. (withdn (plist-get search-plist 'withdn))
  556. (numres 0)
  557. arglist dn name value record result proc)
  558. (if (or (null filter)
  559. (equal "" filter))
  560. (error "No search filter"))
  561. (setq filter (cons filter attributes))
  562. (with-current-buffer buf
  563. (erase-buffer)
  564. (if (and host
  565. (not (equal "" host)))
  566. (setq arglist (nconc arglist
  567. (list (format
  568. ;; Use -H if host is a new-style LDAP URI.
  569. (if (string-match "^[a-zA-Z]+://" host)
  570. "-H%s"
  571. "-h%s")
  572. host)))))
  573. (if (and attrsonly
  574. (not (equal "" attrsonly)))
  575. (setq arglist (nconc arglist (list "-A"))))
  576. (if (and base
  577. (not (equal "" base)))
  578. (setq arglist (nconc arglist (list (format "-b%s" base)))))
  579. (if (and scope
  580. (not (equal "" scope)))
  581. (setq arglist (nconc arglist (list (format "-s%s" scope)))))
  582. (if (and binddn
  583. (not (equal "" binddn)))
  584. (setq arglist (nconc arglist (list (format "-D%s" binddn)))))
  585. (if (and auth
  586. (equal 'simple auth))
  587. (setq arglist (nconc arglist (list "-x"))))
  588. ;; Allow passwd to be set to "", representing a blank password.
  589. (if passwd
  590. (setq arglist (nconc arglist (list "-W"))))
  591. (if (and deref
  592. (not (equal "" deref)))
  593. (setq arglist (nconc arglist (list (format "-a%s" deref)))))
  594. (if (and timelimit
  595. (not (equal "" timelimit)))
  596. (setq arglist (nconc arglist (list (format "-l%s" timelimit)))))
  597. (if (and sizelimit
  598. (not (equal "" sizelimit)))
  599. (setq arglist (nconc arglist (list (format "-z%s" sizelimit)))))
  600. (if passwd
  601. (let* ((process-connection-type nil)
  602. (proc-args (append arglist ldap-ldapsearch-args
  603. filter))
  604. (proc (apply #'start-process "ldapsearch" buf
  605. ldap-ldapsearch-prog
  606. proc-args)))
  607. (while (null (progn
  608. (goto-char (point-min))
  609. (re-search-forward
  610. ldap-ldapsearch-password-prompt-regexp
  611. (point-max) t)))
  612. (accept-process-output proc 1))
  613. (process-send-string proc passwd)
  614. (process-send-string proc "\n")
  615. (while (not (memq (process-status proc) '(exit signal)))
  616. (sit-for 0.1))
  617. (let ((status (process-exit-status proc)))
  618. (when (not (eq status 0))
  619. ;; Handle invalid credentials exit status specially
  620. ;; for ldap-password-read.
  621. (if (eq status 49)
  622. (error (concat "Incorrect LDAP password or"
  623. " bind distinguished name (binddn)"))
  624. (error "Failed ldapsearch invocation: %s \"%s\""
  625. ldap-ldapsearch-prog
  626. (mapconcat 'identity proc-args "\" \""))))))
  627. (apply #'call-process ldap-ldapsearch-prog
  628. ;; Ignore stderr, which can corrupt results
  629. nil (list buf nil) nil
  630. (append arglist ldap-ldapsearch-args filter)))
  631. (insert "\n")
  632. (goto-char (point-min))
  633. (while (re-search-forward (concat "[\t\n\f]+ \\|"
  634. ldap-ldapsearch-password-prompt-regexp)
  635. nil t)
  636. (replace-match "" nil nil))
  637. (goto-char (point-min))
  638. (if (looking-at "usage")
  639. (error "Incorrect ldapsearch invocation")
  640. (message "Parsing results... ")
  641. ;; Skip error message when retrieving attribute list
  642. (if (looking-at "Size limit exceeded")
  643. (forward-line 1))
  644. (if (looking-at "version:") (forward-line 1)) ;bug#12724.
  645. (while (progn
  646. (skip-chars-forward " \t\n")
  647. (not (eobp)))
  648. (setq dn (buffer-substring (point) (point-at-eol)))
  649. (forward-line 1)
  650. (while (looking-at "^\\([A-Za-z][-A-Za-z0-9]*\
  651. \\|[0-9]+\\(?:\\.[0-9]+\\)*\\)\\(;[-A-Za-z0-9]+\\)*[=:\t ]+\
  652. \\(<[\t ]*file://\\)\\(.*\\)$")
  653. (setq name (match-string 1)
  654. value (match-string 4))
  655. ;; Need to handle file:///D:/... as generated by OpenLDAP
  656. ;; on DOS/Windows as local files.
  657. (if (and (memq system-type '(windows-nt ms-dos))
  658. (eq (string-match "/\\(.:.*\\)$" value) 0))
  659. (setq value (match-string 1 value)))
  660. ;; Do not try to open non-existent files
  661. (if (equal value "")
  662. (setq value " ")
  663. (with-current-buffer bufval
  664. (erase-buffer)
  665. (set-buffer-multibyte nil)
  666. (insert-file-contents-literally value)
  667. (delete-file value)
  668. (setq value (buffer-string))))
  669. (setq record (cons (list name value)
  670. record))
  671. (forward-line 1))
  672. (cond (withdn
  673. (push (cons dn (nreverse record)) result))
  674. (record
  675. (push (nreverse record) result)))
  676. (setq record nil)
  677. (skip-chars-forward " \t\n")
  678. (message "Parsing results... %d" numres)
  679. (1+ numres))
  680. (message "Parsing results... done")
  681. (nreverse result)))))
  682. (provide 'ldap)
  683. ;;; ldap.el ends here