s3: Optimize g_lock_lock for a heavily contended case
[Samba.git] / source4 / ldap_server / ldap_server.c
blob344015892e9bbb53132c68861d62ffada623110e
1 /*
2 Unix SMB/CIFS implementation.
4 LDAP server
6 Copyright (C) Andrew Tridgell 2005
7 Copyright (C) Volker Lendecke 2004
8 Copyright (C) Stefan Metzmacher 2004
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "includes.h"
25 #include "lib/events/events.h"
26 #include "auth/auth.h"
27 #include "auth/credentials/credentials.h"
28 #include "librpc/gen_ndr/ndr_samr.h"
29 #include "../lib/util/dlinklist.h"
30 #include "../lib/util/asn1.h"
31 #include "ldap_server/ldap_server.h"
32 #include "smbd/service_task.h"
33 #include "smbd/service_stream.h"
34 #include "smbd/service.h"
35 #include "smbd/process_model.h"
36 #include "lib/tls/tls.h"
37 #include "lib/messaging/irpc.h"
38 #include "lib/ldb/include/ldb.h"
39 #include "lib/ldb/include/ldb_errors.h"
40 #include "libcli/ldap/ldap.h"
41 #include "libcli/ldap/ldap_proto.h"
42 #include "system/network.h"
43 #include "lib/socket/netif.h"
44 #include "dsdb/samdb/samdb.h"
45 #include "param/param.h"
47 close the socket and shutdown a server_context
49 void ldapsrv_terminate_connection(struct ldapsrv_connection *conn,
50 const char *reason)
52 packet_recv_disable(conn->packet);
53 TALLOC_FREE(conn->packet);
54 TALLOC_FREE(conn->sockets.tls);
55 stream_terminate_connection(conn->connection, reason);
59 handle packet errors
61 static void ldapsrv_error_handler(void *private_data, NTSTATUS status)
63 struct ldapsrv_connection *conn = talloc_get_type(private_data,
64 struct ldapsrv_connection);
65 ldapsrv_terminate_connection(conn, nt_errstr(status));
69 process a decoded ldap message
71 static void ldapsrv_process_message(struct ldapsrv_connection *conn,
72 struct ldap_message *msg)
74 struct ldapsrv_call *call;
75 NTSTATUS status;
76 DATA_BLOB blob;
78 call = talloc(conn, struct ldapsrv_call);
79 if (!call) {
80 ldapsrv_terminate_connection(conn, "no memory");
81 return;
84 call->request = talloc_steal(call, msg);
85 call->conn = conn;
86 call->replies = NULL;
87 call->send_callback = NULL;
88 call->send_private = NULL;
90 /* make the call */
91 status = ldapsrv_do_call(call);
92 if (!NT_STATUS_IS_OK(status)) {
93 talloc_free(call);
94 return;
97 blob = data_blob(NULL, 0);
99 if (call->replies == NULL) {
100 talloc_free(call);
101 return;
104 /* build all the replies into a single blob */
105 while (call->replies) {
106 DATA_BLOB b;
107 bool ret;
109 msg = call->replies->msg;
110 if (!ldap_encode(msg, samba_ldap_control_handlers(), &b, call)) {
111 DEBUG(0,("Failed to encode ldap reply of type %d\n", msg->type));
112 talloc_free(call);
113 return;
116 ret = data_blob_append(call, &blob, b.data, b.length);
117 data_blob_free(&b);
119 talloc_set_name_const(blob.data, "Outgoing, encoded LDAP packet");
121 if (!ret) {
122 talloc_free(call);
123 return;
126 DLIST_REMOVE(call->replies, call->replies);
129 packet_send_callback(conn->packet, blob,
130 call->send_callback, call->send_private);
131 talloc_free(call);
132 return;
136 decode/process data
138 static NTSTATUS ldapsrv_decode(void *private_data, DATA_BLOB blob)
140 NTSTATUS status;
141 struct ldapsrv_connection *conn = talloc_get_type(private_data,
142 struct ldapsrv_connection);
143 struct asn1_data *asn1 = asn1_init(conn);
144 struct ldap_message *msg = talloc(conn, struct ldap_message);
146 if (asn1 == NULL || msg == NULL) {
147 return NT_STATUS_NO_MEMORY;
150 if (!asn1_load(asn1, blob)) {
151 talloc_free(msg);
152 talloc_free(asn1);
153 return NT_STATUS_NO_MEMORY;
156 status = ldap_decode(asn1, samba_ldap_control_handlers(), msg);
157 if (!NT_STATUS_IS_OK(status)) {
158 asn1_free(asn1);
159 return status;
162 data_blob_free(&blob);
163 talloc_steal(conn, msg);
164 asn1_free(asn1);
166 ldapsrv_process_message(conn, msg);
167 return NT_STATUS_OK;
171 Idle timeout handler
173 static void ldapsrv_conn_idle_timeout(struct tevent_context *ev,
174 struct tevent_timer *te,
175 struct timeval t,
176 void *private_data)
178 struct ldapsrv_connection *conn = talloc_get_type(private_data, struct ldapsrv_connection);
180 ldapsrv_terminate_connection(conn, "Timeout. No requests after bind");
184 called when a LDAP socket becomes readable
186 void ldapsrv_recv(struct stream_connection *c, uint16_t flags)
188 struct ldapsrv_connection *conn =
189 talloc_get_type(c->private_data, struct ldapsrv_connection);
191 if (conn->limits.ite) { /* clean initial timeout if any */
192 talloc_free(conn->limits.ite);
193 conn->limits.ite = NULL;
196 if (conn->limits.te) { /* clean idle timeout if any */
197 talloc_free(conn->limits.te);
198 conn->limits.te = NULL;
201 packet_recv(conn->packet);
203 /* set idle timeout */
204 conn->limits.te = event_add_timed(c->event.ctx, conn,
205 timeval_current_ofs(conn->limits.conn_idle_time, 0),
206 ldapsrv_conn_idle_timeout, conn);
210 called when a LDAP socket becomes writable
212 static void ldapsrv_send(struct stream_connection *c, uint16_t flags)
214 struct ldapsrv_connection *conn =
215 talloc_get_type(c->private_data, struct ldapsrv_connection);
217 packet_queue_run(conn->packet);
220 static void ldapsrv_conn_init_timeout(struct tevent_context *ev,
221 struct tevent_timer *te,
222 struct timeval t,
223 void *private_data)
225 struct ldapsrv_connection *conn = talloc_get_type(private_data, struct ldapsrv_connection);
227 ldapsrv_terminate_connection(conn, "Timeout. No requests after initial connection");
230 static int ldapsrv_load_limits(struct ldapsrv_connection *conn)
232 TALLOC_CTX *tmp_ctx;
233 const char *attrs[] = { "configurationNamingContext", NULL };
234 const char *attrs2[] = { "lDAPAdminLimits", NULL };
235 struct ldb_message_element *el;
236 struct ldb_result *res = NULL;
237 struct ldb_dn *basedn;
238 struct ldb_dn *conf_dn;
239 struct ldb_dn *policy_dn;
240 int i,ret;
242 /* set defaults limits in case of failure */
243 conn->limits.initial_timeout = 120;
244 conn->limits.conn_idle_time = 900;
245 conn->limits.max_page_size = 1000;
246 conn->limits.search_timeout = 120;
249 tmp_ctx = talloc_new(conn);
250 if (tmp_ctx == NULL) {
251 return -1;
254 basedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);
255 if ( ! ldb_dn_validate(basedn)) {
256 goto failed;
259 ret = ldb_search(conn->ldb, tmp_ctx, &res, basedn, LDB_SCOPE_BASE, attrs, NULL);
260 if (ret != LDB_SUCCESS) {
261 goto failed;
264 if (res->count != 1) {
265 goto failed;
268 conf_dn = ldb_msg_find_attr_as_dn(conn->ldb, tmp_ctx, res->msgs[0], "configurationNamingContext");
269 if (conf_dn == NULL) {
270 goto failed;
273 policy_dn = ldb_dn_copy(tmp_ctx, conf_dn);
274 ldb_dn_add_child_fmt(policy_dn, "CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services");
275 if (policy_dn == NULL) {
276 goto failed;
279 ret = ldb_search(conn->ldb, tmp_ctx, &res, policy_dn, LDB_SCOPE_BASE, attrs2, NULL);
280 if (ret != LDB_SUCCESS) {
281 goto failed;
284 if (res->count != 1) {
285 goto failed;
288 el = ldb_msg_find_element(res->msgs[0], "lDAPAdminLimits");
289 if (el == NULL) {
290 goto failed;
293 for (i = 0; i < el->num_values; i++) {
294 char policy_name[256];
295 int policy_value, s;
297 s = sscanf((const char *)el->values[i].data, "%255[^=]=%d", policy_name, &policy_value);
298 if (ret != 2 || policy_value == 0)
299 continue;
301 if (strcasecmp("InitRecvTimeout", policy_name) == 0) {
302 conn->limits.initial_timeout = policy_value;
303 continue;
305 if (strcasecmp("MaxConnIdleTime", policy_name) == 0) {
306 conn->limits.conn_idle_time = policy_value;
307 continue;
309 if (strcasecmp("MaxPageSize", policy_name) == 0) {
310 conn->limits.max_page_size = policy_value;
311 continue;
313 if (strcasecmp("MaxQueryDuration", policy_name) == 0) {
314 conn->limits.search_timeout = policy_value;
315 continue;
319 return 0;
321 failed:
322 DEBUG(0, ("Failed to load ldap server query policies\n"));
323 talloc_free(tmp_ctx);
324 return -1;
328 initialise a server_context from a open socket and register a event handler
329 for reading from that socket
331 static void ldapsrv_accept(struct stream_connection *c,
332 struct auth_session_info *session_info)
334 struct ldapsrv_service *ldapsrv_service =
335 talloc_get_type(c->private_data, struct ldapsrv_service);
336 struct ldapsrv_connection *conn;
337 struct cli_credentials *server_credentials;
338 struct socket_address *socket_address;
339 NTSTATUS status;
340 int port;
342 conn = talloc_zero(c, struct ldapsrv_connection);
343 if (!conn) {
344 stream_terminate_connection(c, "ldapsrv_accept: out of memory");
345 return;
348 conn->packet = NULL;
349 conn->connection = c;
350 conn->service = ldapsrv_service;
351 conn->sockets.raw = c->socket;
352 conn->lp_ctx = ldapsrv_service->task->lp_ctx;
354 c->private_data = conn;
356 socket_address = socket_get_my_addr(c->socket, conn);
357 if (!socket_address) {
358 ldapsrv_terminate_connection(conn, "ldapsrv_accept: failed to obtain local socket address!");
359 return;
361 port = socket_address->port;
362 talloc_free(socket_address);
364 if (port == 636) {
365 struct socket_context *tls_socket = tls_init_server(ldapsrv_service->tls_params, c->socket,
366 c->event.fde, NULL);
367 if (!tls_socket) {
368 ldapsrv_terminate_connection(conn, "ldapsrv_accept: tls_init_server() failed");
369 return;
371 talloc_steal(c, tls_socket);
372 c->socket = tls_socket;
373 conn->sockets.tls = tls_socket;
375 } else if (port == 3268) /* Global catalog */ {
376 conn->global_catalog = true;
378 conn->packet = packet_init(conn);
379 if (conn->packet == NULL) {
380 ldapsrv_terminate_connection(conn, "out of memory");
381 return;
384 packet_set_private(conn->packet, conn);
385 packet_set_socket(conn->packet, c->socket);
386 packet_set_callback(conn->packet, ldapsrv_decode);
387 packet_set_full_request(conn->packet, ldap_full_packet);
388 packet_set_error_handler(conn->packet, ldapsrv_error_handler);
389 packet_set_event_context(conn->packet, c->event.ctx);
390 packet_set_fde(conn->packet, c->event.fde);
391 packet_set_serialise(conn->packet);
393 if (conn->sockets.tls) {
394 packet_set_unreliable_select(conn->packet);
397 /* Ensure we don't get packets until the database is ready below */
398 packet_recv_disable(conn->packet);
400 server_credentials = cli_credentials_init(conn);
401 if (!server_credentials) {
402 stream_terminate_connection(c, "Failed to init server credentials\n");
403 return;
406 cli_credentials_set_conf(server_credentials, conn->lp_ctx);
407 status = cli_credentials_set_machine_account(server_credentials, conn->lp_ctx);
408 if (!NT_STATUS_IS_OK(status)) {
409 stream_terminate_connection(c, talloc_asprintf(conn, "Failed to obtain server credentials, perhaps a standalone server?: %s\n", nt_errstr(status)));
410 return;
412 conn->server_credentials = server_credentials;
414 conn->session_info = talloc_move(conn, &session_info);
416 if (!NT_STATUS_IS_OK(ldapsrv_backend_Init(conn))) {
417 ldapsrv_terminate_connection(conn, "backend Init failed");
418 return;
421 /* load limits from the conf partition */
422 ldapsrv_load_limits(conn); /* should we fail on error ? */
424 /* register the server */
425 irpc_add_name(c->msg_ctx, "ldap_server");
427 /* set connections limits */
428 conn->limits.ite = event_add_timed(c->event.ctx, conn,
429 timeval_current_ofs(conn->limits.initial_timeout, 0),
430 ldapsrv_conn_init_timeout, conn);
432 packet_recv_enable(conn->packet);
436 static void ldapsrv_accept_nonpriv(struct stream_connection *c)
438 struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
439 c->private_data, struct ldapsrv_service);
440 struct auth_session_info *session_info;
441 NTSTATUS status;
443 status = auth_anonymous_session_info(
444 c, c->event.ctx, ldapsrv_service->task->lp_ctx, &session_info);
445 if (!NT_STATUS_IS_OK(status)) {
446 stream_terminate_connection(c, "failed to setup anonymous "
447 "session info");
448 return;
450 ldapsrv_accept(c, session_info);
453 static const struct stream_server_ops ldap_stream_nonpriv_ops = {
454 .name = "ldap",
455 .accept_connection = ldapsrv_accept_nonpriv,
456 .recv_handler = ldapsrv_recv,
457 .send_handler = ldapsrv_send,
460 /* The feature removed behind an #ifdef until we can do it properly
461 * with an EXTERNAL bind. */
463 #define WITH_LDAPI_PRIV_SOCKET
465 #ifdef WITH_LDAPI_PRIV_SOCKET
466 static void ldapsrv_accept_priv(struct stream_connection *c)
468 struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
469 c->private_data, struct ldapsrv_service);
470 struct auth_session_info *session_info;
471 NTSTATUS status;
473 status = auth_system_session_info(
474 c, ldapsrv_service->task->lp_ctx, &session_info);
475 if (!NT_STATUS_IS_OK(status)) {
476 stream_terminate_connection(c, "failed to setup system "
477 "session info");
478 return;
480 ldapsrv_accept(c, session_info);
483 static const struct stream_server_ops ldap_stream_priv_ops = {
484 .name = "ldap",
485 .accept_connection = ldapsrv_accept_priv,
486 .recv_handler = ldapsrv_recv,
487 .send_handler = ldapsrv_send,
490 #endif
492 add a socket address to the list of events, one event per port
494 static NTSTATUS add_socket(struct tevent_context *event_context,
495 struct loadparm_context *lp_ctx,
496 const struct model_ops *model_ops,
497 const char *address, struct ldapsrv_service *ldap_service)
499 uint16_t port = 389;
500 NTSTATUS status;
501 struct ldb_context *ldb;
503 status = stream_setup_socket(event_context, lp_ctx,
504 model_ops, &ldap_stream_nonpriv_ops,
505 "ipv4", address, &port,
506 lp_socket_options(lp_ctx),
507 ldap_service);
508 if (!NT_STATUS_IS_OK(status)) {
509 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
510 address, port, nt_errstr(status)));
513 if (tls_support(ldap_service->tls_params)) {
514 /* add ldaps server */
515 port = 636;
516 status = stream_setup_socket(event_context, lp_ctx,
517 model_ops,
518 &ldap_stream_nonpriv_ops,
519 "ipv4", address, &port,
520 lp_socket_options(lp_ctx),
521 ldap_service);
522 if (!NT_STATUS_IS_OK(status)) {
523 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
524 address, port, nt_errstr(status)));
528 /* Load LDAP database, but only to read our settings */
529 ldb = samdb_connect(ldap_service, ldap_service->task->event_ctx,
530 lp_ctx, system_session(ldap_service, lp_ctx));
531 if (!ldb) {
532 return NT_STATUS_INTERNAL_DB_CORRUPTION;
535 if (samdb_is_gc(ldb)) {
536 port = 3268;
537 status = stream_setup_socket(event_context, lp_ctx,
538 model_ops,
539 &ldap_stream_nonpriv_ops,
540 "ipv4", address, &port,
541 lp_socket_options(lp_ctx),
542 ldap_service);
543 if (!NT_STATUS_IS_OK(status)) {
544 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
545 address, port, nt_errstr(status)));
549 /* And once we are bound, free the tempoary ldb, it will
550 * connect again on each incoming LDAP connection */
551 talloc_free(ldb);
553 return status;
557 open the ldap server sockets
559 static void ldapsrv_task_init(struct task_server *task)
561 char *ldapi_path;
562 #ifdef WITH_LDAPI_PRIV_SOCKET
563 char *priv_dir;
564 #endif
565 struct ldapsrv_service *ldap_service;
566 NTSTATUS status;
567 const struct model_ops *model_ops;
569 switch (lp_server_role(task->lp_ctx)) {
570 case ROLE_STANDALONE:
571 task_server_terminate(task, "ldap_server: no LDAP server required in standalone configuration",
572 false);
573 return;
574 case ROLE_DOMAIN_MEMBER:
575 task_server_terminate(task, "ldap_server: no LDAP server required in member server configuration",
576 false);
577 return;
578 case ROLE_DOMAIN_CONTROLLER:
579 /* Yes, we want an LDAP server */
580 break;
583 task_server_set_title(task, "task[ldapsrv]");
585 /* run the ldap server as a single process */
586 model_ops = process_model_startup(task->event_ctx, "single");
587 if (!model_ops) goto failed;
589 ldap_service = talloc_zero(task, struct ldapsrv_service);
590 if (ldap_service == NULL) goto failed;
592 ldap_service->task = task;
594 ldap_service->tls_params = tls_initialise(ldap_service, task->lp_ctx);
595 if (ldap_service->tls_params == NULL) goto failed;
597 if (lp_interfaces(task->lp_ctx) && lp_bind_interfaces_only(task->lp_ctx)) {
598 struct interface *ifaces;
599 int num_interfaces;
600 int i;
602 load_interfaces(task, lp_interfaces(task->lp_ctx), &ifaces);
603 num_interfaces = iface_count(ifaces);
605 /* We have been given an interfaces line, and been
606 told to only bind to those interfaces. Create a
607 socket per interface and bind to only these.
609 for(i = 0; i < num_interfaces; i++) {
610 const char *address = iface_n_ip(ifaces, i);
611 status = add_socket(task->event_ctx, task->lp_ctx, model_ops, address, ldap_service);
612 if (!NT_STATUS_IS_OK(status)) goto failed;
614 } else {
615 status = add_socket(task->event_ctx, task->lp_ctx, model_ops,
616 lp_socket_address(task->lp_ctx), ldap_service);
617 if (!NT_STATUS_IS_OK(status)) goto failed;
620 ldapi_path = private_path(ldap_service, task->lp_ctx, "ldapi");
621 if (!ldapi_path) {
622 goto failed;
625 status = stream_setup_socket(task->event_ctx, task->lp_ctx,
626 model_ops, &ldap_stream_nonpriv_ops,
627 "unix", ldapi_path, NULL,
628 lp_socket_options(task->lp_ctx),
629 ldap_service);
630 talloc_free(ldapi_path);
631 if (!NT_STATUS_IS_OK(status)) {
632 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
633 ldapi_path, nt_errstr(status)));
636 #ifdef WITH_LDAPI_PRIV_SOCKET
637 priv_dir = private_path(ldap_service, task->lp_ctx, "ldap_priv");
638 if (priv_dir == NULL) {
639 goto failed;
642 * Make sure the directory for the privileged ldapi socket exists, and
643 * is of the correct permissions
645 if (!directory_create_or_exist(priv_dir, geteuid(), 0750)) {
646 task_server_terminate(task, "Cannot create ldap "
647 "privileged ldapi directory", true);
648 return;
650 ldapi_path = talloc_asprintf(ldap_service, "%s/ldapi", priv_dir);
651 talloc_free(priv_dir);
652 if (ldapi_path == NULL) {
653 goto failed;
656 status = stream_setup_socket(task->event_ctx, task->lp_ctx,
657 model_ops, &ldap_stream_priv_ops,
658 "unix", ldapi_path, NULL,
659 lp_socket_options(task->lp_ctx),
660 ldap_service);
661 talloc_free(ldapi_path);
662 if (!NT_STATUS_IS_OK(status)) {
663 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
664 ldapi_path, nt_errstr(status)));
667 #endif
668 return;
670 failed:
671 task_server_terminate(task, "Failed to startup ldap server task", true);
675 NTSTATUS server_service_ldap_init(void)
677 return register_server_service("ldap", ldapsrv_task_init);