source4 smdb: Add a post fork hook to the service API
[samba.git] / source4 / ldap_server / ldap_server.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    LDAP server
5
6    Copyright (C) Andrew Tridgell 2005
7    Copyright (C) Volker Lendecke 2004
8    Copyright (C) Stefan Metzmacher 2004
9
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.
14
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.
19
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/>.
22 */
23
24 #include "includes.h"
25 #include "system/network.h"
26 #include "lib/events/events.h"
27 #include "auth/auth.h"
28 #include "auth/credentials/credentials.h"
29 #include "librpc/gen_ndr/ndr_samr.h"
30 #include "../lib/util/dlinklist.h"
31 #include "../lib/util/asn1.h"
32 #include "ldap_server/ldap_server.h"
33 #include "smbd/service_task.h"
34 #include "smbd/service_stream.h"
35 #include "smbd/service.h"
36 #include "smbd/process_model.h"
37 #include "lib/tls/tls.h"
38 #include "lib/messaging/irpc.h"
39 #include <ldb.h>
40 #include <ldb_errors.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"
46 #include "../lib/tsocket/tsocket.h"
47 #include "../lib/util/tevent_ntstatus.h"
48 #include "../libcli/util/tstream.h"
49 #include "libds/common/roles.h"
50
51 static void ldapsrv_terminate_connection_done(struct tevent_req *subreq);
52
53 /*
54   close the socket and shutdown a server_context
55 */
56 static void ldapsrv_terminate_connection(struct ldapsrv_connection *conn,
57                                          const char *reason)
58 {
59         struct tevent_req *subreq;
60
61         if (conn->limits.reason) {
62                 return;
63         }
64
65         DLIST_REMOVE(conn->service->connections, conn);
66
67         conn->limits.endtime = timeval_current_ofs(0, 500);
68
69         tevent_queue_stop(conn->sockets.send_queue);
70         TALLOC_FREE(conn->sockets.read_req);
71         if (conn->active_call) {
72                 tevent_req_cancel(conn->active_call);
73                 conn->active_call = NULL;
74         }
75
76         conn->limits.reason = talloc_strdup(conn, reason);
77         if (conn->limits.reason == NULL) {
78                 TALLOC_FREE(conn->sockets.tls);
79                 TALLOC_FREE(conn->sockets.sasl);
80                 TALLOC_FREE(conn->sockets.raw);
81                 stream_terminate_connection(conn->connection, reason);
82                 return;
83         }
84
85         subreq = tstream_disconnect_send(conn,
86                                          conn->connection->event.ctx,
87                                          conn->sockets.active);
88         if (subreq == NULL) {
89                 TALLOC_FREE(conn->sockets.tls);
90                 TALLOC_FREE(conn->sockets.sasl);
91                 TALLOC_FREE(conn->sockets.raw);
92                 stream_terminate_connection(conn->connection, reason);
93                 return;
94         }
95         tevent_req_set_endtime(subreq,
96                                conn->connection->event.ctx,
97                                conn->limits.endtime);
98         tevent_req_set_callback(subreq, ldapsrv_terminate_connection_done, conn);
99 }
100
101 static void ldapsrv_terminate_connection_done(struct tevent_req *subreq)
102 {
103         struct ldapsrv_connection *conn =
104                 tevent_req_callback_data(subreq,
105                 struct ldapsrv_connection);
106         int sys_errno;
107         bool ok;
108
109         tstream_disconnect_recv(subreq, &sys_errno);
110         TALLOC_FREE(subreq);
111
112         if (conn->sockets.active == conn->sockets.raw) {
113                 TALLOC_FREE(conn->sockets.tls);
114                 TALLOC_FREE(conn->sockets.sasl);
115                 TALLOC_FREE(conn->sockets.raw);
116                 stream_terminate_connection(conn->connection,
117                                             conn->limits.reason);
118                 return;
119         }
120
121         TALLOC_FREE(conn->sockets.tls);
122         TALLOC_FREE(conn->sockets.sasl);
123         conn->sockets.active = conn->sockets.raw;
124
125         subreq = tstream_disconnect_send(conn,
126                                          conn->connection->event.ctx,
127                                          conn->sockets.active);
128         if (subreq == NULL) {
129                 TALLOC_FREE(conn->sockets.raw);
130                 stream_terminate_connection(conn->connection,
131                                             conn->limits.reason);
132                 return;
133         }
134         ok = tevent_req_set_endtime(subreq,
135                                     conn->connection->event.ctx,
136                                     conn->limits.endtime);
137         if (!ok) {
138                 TALLOC_FREE(conn->sockets.raw);
139                 stream_terminate_connection(conn->connection,
140                                             conn->limits.reason);
141                 return;
142         }
143         tevent_req_set_callback(subreq, ldapsrv_terminate_connection_done, conn);
144 }
145
146 /*
147   called when a LDAP socket becomes readable
148 */
149 void ldapsrv_recv(struct stream_connection *c, uint16_t flags)
150 {
151         smb_panic(__location__);
152 }
153
154 /*
155   called when a LDAP socket becomes writable
156 */
157 static void ldapsrv_send(struct stream_connection *c, uint16_t flags)
158 {
159         smb_panic(__location__);
160 }
161
162 static int ldapsrv_load_limits(struct ldapsrv_connection *conn)
163 {
164         TALLOC_CTX *tmp_ctx;
165         const char *attrs[] = { "configurationNamingContext", NULL };
166         const char *attrs2[] = { "lDAPAdminLimits", NULL };
167         struct ldb_message_element *el;
168         struct ldb_result *res = NULL;
169         struct ldb_dn *basedn;
170         struct ldb_dn *conf_dn;
171         struct ldb_dn *policy_dn;
172         unsigned int i;
173         int ret;
174
175         /* set defaults limits in case of failure */
176         conn->limits.initial_timeout = 120;
177         conn->limits.conn_idle_time = 900;
178         conn->limits.max_page_size = 1000;
179         conn->limits.max_notifications = 5;
180         conn->limits.search_timeout = 120;
181
182
183         tmp_ctx = talloc_new(conn);
184         if (tmp_ctx == NULL) {
185                 return -1;
186         }
187
188         basedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);
189         if (basedn == NULL) {
190                 goto failed;
191         }
192
193         ret = ldb_search(conn->ldb, tmp_ctx, &res, basedn, LDB_SCOPE_BASE, attrs, NULL);
194         if (ret != LDB_SUCCESS) {
195                 goto failed;
196         }
197
198         if (res->count != 1) {
199                 goto failed;
200         }
201
202         conf_dn = ldb_msg_find_attr_as_dn(conn->ldb, tmp_ctx, res->msgs[0], "configurationNamingContext");
203         if (conf_dn == NULL) {
204                 goto failed;
205         }
206
207         policy_dn = ldb_dn_copy(tmp_ctx, conf_dn);
208         ldb_dn_add_child_fmt(policy_dn, "CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services");
209         if (policy_dn == NULL) {
210                 goto failed;
211         }
212
213         ret = ldb_search(conn->ldb, tmp_ctx, &res, policy_dn, LDB_SCOPE_BASE, attrs2, NULL);
214         if (ret != LDB_SUCCESS) {
215                 goto failed;
216         }
217
218         if (res->count != 1) {
219                 goto failed;
220         }
221
222         el = ldb_msg_find_element(res->msgs[0], "lDAPAdminLimits");
223         if (el == NULL) {
224                 goto failed;
225         }
226
227         for (i = 0; i < el->num_values; i++) {
228                 char policy_name[256];
229                 int policy_value, s;
230
231                 s = sscanf((const char *)el->values[i].data, "%255[^=]=%d", policy_name, &policy_value);
232                 if (s != 2 || policy_value == 0)
233                         continue;
234                 if (strcasecmp("InitRecvTimeout", policy_name) == 0) {
235                         conn->limits.initial_timeout = policy_value;
236                         continue;
237                 }
238                 if (strcasecmp("MaxConnIdleTime", policy_name) == 0) {
239                         conn->limits.conn_idle_time = policy_value;
240                         continue;
241                 }
242                 if (strcasecmp("MaxPageSize", policy_name) == 0) {
243                         conn->limits.max_page_size = policy_value;
244                         continue;
245                 }
246                 if (strcasecmp("MaxNotificationPerConn", policy_name) == 0) {
247                         conn->limits.max_notifications = policy_value;
248                         continue;
249                 }
250                 if (strcasecmp("MaxQueryDuration", policy_name) == 0) {
251                         conn->limits.search_timeout = policy_value;
252                         continue;
253                 }
254         }
255
256         return 0;
257
258 failed:
259         DEBUG(0, ("Failed to load ldap server query policies\n"));
260         talloc_free(tmp_ctx);
261         return -1;
262 }
263
264 static int ldapsrv_call_destructor(struct ldapsrv_call *call)
265 {
266         if (call->conn == NULL) {
267                 return 0;
268         }
269
270         DLIST_REMOVE(call->conn->pending_calls, call);
271
272         call->conn = NULL;
273         return 0;
274 }
275
276 static struct tevent_req *ldapsrv_process_call_send(TALLOC_CTX *mem_ctx,
277                                                     struct tevent_context *ev,
278                                                     struct tevent_queue *call_queue,
279                                                     struct ldapsrv_call *call);
280 static NTSTATUS ldapsrv_process_call_recv(struct tevent_req *req);
281
282 static bool ldapsrv_call_read_next(struct ldapsrv_connection *conn);
283 static void ldapsrv_accept_tls_done(struct tevent_req *subreq);
284
285 /*
286   initialise a server_context from a open socket and register a event handler
287   for reading from that socket
288 */
289 static void ldapsrv_accept(struct stream_connection *c,
290                            struct auth_session_info *session_info,
291                            bool is_privileged)
292 {
293         struct ldapsrv_service *ldapsrv_service = 
294                 talloc_get_type(c->private_data, struct ldapsrv_service);
295         struct ldapsrv_connection *conn;
296         struct cli_credentials *server_credentials;
297         struct socket_address *socket_address;
298         NTSTATUS status;
299         int port;
300         int ret;
301         struct tevent_req *subreq;
302         struct timeval endtime;
303         char *errstring = NULL;
304
305         conn = talloc_zero(c, struct ldapsrv_connection);
306         if (!conn) {
307                 stream_terminate_connection(c, "ldapsrv_accept: out of memory");
308                 return;
309         }
310         conn->is_privileged = is_privileged;
311
312         conn->sockets.send_queue = tevent_queue_create(conn, "ldapsev send queue");
313         if (conn->sockets.send_queue == NULL) {
314                 stream_terminate_connection(c,
315                                             "ldapsrv_accept: tevent_queue_create failed");
316                 return;
317         }
318
319         TALLOC_FREE(c->event.fde);
320
321         ret = tstream_bsd_existing_socket(conn,
322                                           socket_get_fd(c->socket),
323                                           &conn->sockets.raw);
324         if (ret == -1) {
325                 stream_terminate_connection(c,
326                                             "ldapsrv_accept: out of memory");
327                 return;
328         }
329         socket_set_flags(c->socket, SOCKET_FLAG_NOCLOSE);
330
331         conn->connection  = c;
332         conn->service     = ldapsrv_service;
333         conn->lp_ctx      = ldapsrv_service->task->lp_ctx;
334
335         c->private_data   = conn;
336
337         socket_address = socket_get_my_addr(c->socket, conn);
338         if (!socket_address) {
339                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: failed to obtain local socket address!");
340                 return;
341         }
342         port = socket_address->port;
343         talloc_free(socket_address);
344         if (port == 3268 || port == 3269) /* Global catalog */ {
345                 conn->global_catalog = true;
346         }
347
348         server_credentials = cli_credentials_init(conn);
349         if (!server_credentials) {
350                 stream_terminate_connection(c, "Failed to init server credentials\n");
351                 return;
352         }
353
354         cli_credentials_set_conf(server_credentials, conn->lp_ctx);
355         status = cli_credentials_set_machine_account(server_credentials, conn->lp_ctx);
356         if (!NT_STATUS_IS_OK(status)) {
357                 stream_terminate_connection(c, talloc_asprintf(conn, "Failed to obtain server credentials, perhaps a standalone server?: %s\n", nt_errstr(status)));
358                 return;
359         }
360         conn->server_credentials = server_credentials;
361
362         conn->session_info = session_info;
363
364         conn->sockets.active = conn->sockets.raw;
365
366         if (conn->is_privileged) {
367                 conn->require_strong_auth = LDAP_SERVER_REQUIRE_STRONG_AUTH_NO;
368         } else {
369                 conn->require_strong_auth = lpcfg_ldap_server_require_strong_auth(conn->lp_ctx);
370         }
371
372         ret = ldapsrv_backend_Init(conn, &errstring);
373         if (ret != LDB_SUCCESS) {
374                 char *reason = talloc_asprintf(conn,
375                                                "LDB backend for LDAP Init "
376                                                "failed: %s: %s",
377                                                errstring, ldb_strerror(ret));
378                 ldapsrv_terminate_connection(conn, reason);
379                 return;
380         }
381
382         /* load limits from the conf partition */
383         ldapsrv_load_limits(conn); /* should we fail on error ? */
384
385         /* register the server */       
386         irpc_add_name(c->msg_ctx, "ldap_server");
387
388         DLIST_ADD_END(ldapsrv_service->connections, conn);
389
390         if (port != 636 && port != 3269) {
391                 ldapsrv_call_read_next(conn);
392                 return;
393         }
394
395         endtime = timeval_current_ofs(conn->limits.conn_idle_time, 0);
396
397         subreq = tstream_tls_accept_send(conn,
398                                          conn->connection->event.ctx,
399                                          conn->sockets.raw,
400                                          conn->service->tls_params);
401         if (subreq == NULL) {
402                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: "
403                                 "no memory for tstream_tls_accept_send");
404                 return;
405         }
406         tevent_req_set_endtime(subreq,
407                                conn->connection->event.ctx,
408                                endtime);
409         tevent_req_set_callback(subreq, ldapsrv_accept_tls_done, conn);
410 }
411
412 static void ldapsrv_accept_tls_done(struct tevent_req *subreq)
413 {
414         struct ldapsrv_connection *conn =
415                 tevent_req_callback_data(subreq,
416                 struct ldapsrv_connection);
417         int ret;
418         int sys_errno;
419
420         ret = tstream_tls_accept_recv(subreq, &sys_errno,
421                                       conn, &conn->sockets.tls);
422         TALLOC_FREE(subreq);
423         if (ret == -1) {
424                 const char *reason;
425
426                 reason = talloc_asprintf(conn, "ldapsrv_accept_tls_loop: "
427                                          "tstream_tls_accept_recv() - %d:%s",
428                                          sys_errno, strerror(sys_errno));
429                 if (!reason) {
430                         reason = "ldapsrv_accept_tls_loop: "
431                                  "tstream_tls_accept_recv() - failed";
432                 }
433
434                 ldapsrv_terminate_connection(conn, reason);
435                 return;
436         }
437
438         conn->sockets.active = conn->sockets.tls;
439         ldapsrv_call_read_next(conn);
440 }
441
442 static void ldapsrv_call_read_done(struct tevent_req *subreq);
443
444 static bool ldapsrv_call_read_next(struct ldapsrv_connection *conn)
445 {
446         struct tevent_req *subreq;
447
448         if (conn->pending_calls != NULL) {
449                 conn->limits.endtime = timeval_zero();
450
451                 ldapsrv_notification_retry_setup(conn->service, false);
452         } else if (timeval_is_zero(&conn->limits.endtime)) {
453                 conn->limits.endtime =
454                         timeval_current_ofs(conn->limits.initial_timeout, 0);
455         } else {
456                 conn->limits.endtime =
457                         timeval_current_ofs(conn->limits.conn_idle_time, 0);
458         }
459
460         if (conn->sockets.read_req != NULL) {
461                 return true;
462         }
463
464         /*
465          * The minimum size of a LDAP pdu is 7 bytes
466          *
467          * dumpasn1 -hh ldap-unbind-min.dat
468          *
469          *     <30 05 02 01 09 42 00>
470          *    0    5: SEQUENCE {
471          *     <02 01 09>
472          *    2    1:   INTEGER 9
473          *     <42 00>
474          *    5    0:   [APPLICATION 2]
475          *          :     Error: Object has zero length.
476          *          :   }
477          *
478          * dumpasn1 -hh ldap-unbind-windows.dat
479          *
480          *     <30 84 00 00 00 05 02 01 09 42 00>
481          *    0    5: SEQUENCE {
482          *     <02 01 09>
483          *    6    1:   INTEGER 9
484          *     <42 00>
485          *    9    0:   [APPLICATION 2]
486          *          :     Error: Object has zero length.
487          *          :   }
488          *
489          * This means using an initial read size
490          * of 7 is ok.
491          */
492         subreq = tstream_read_pdu_blob_send(conn,
493                                             conn->connection->event.ctx,
494                                             conn->sockets.active,
495                                             7, /* initial_read_size */
496                                             ldap_full_packet,
497                                             conn);
498         if (subreq == NULL) {
499                 ldapsrv_terminate_connection(conn, "ldapsrv_call_read_next: "
500                                 "no memory for tstream_read_pdu_blob_send");
501                 return false;
502         }
503         if (!timeval_is_zero(&conn->limits.endtime)) {
504                 bool ok;
505                 ok = tevent_req_set_endtime(subreq,
506                                             conn->connection->event.ctx,
507                                             conn->limits.endtime);
508                 if (!ok) {
509                         ldapsrv_terminate_connection(
510                                 conn,
511                                 "ldapsrv_call_read_next: "
512                                 "no memory for tevent_req_set_endtime");
513                         return false;
514                 }
515         }
516         tevent_req_set_callback(subreq, ldapsrv_call_read_done, conn);
517         conn->sockets.read_req = subreq;
518         return true;
519 }
520
521 static void ldapsrv_call_process_done(struct tevent_req *subreq);
522
523 static void ldapsrv_call_read_done(struct tevent_req *subreq)
524 {
525         struct ldapsrv_connection *conn =
526                 tevent_req_callback_data(subreq,
527                 struct ldapsrv_connection);
528         NTSTATUS status;
529         struct ldapsrv_call *call;
530         struct asn1_data *asn1;
531         DATA_BLOB blob;
532
533         conn->sockets.read_req = NULL;
534
535         call = talloc_zero(conn, struct ldapsrv_call);
536         if (!call) {
537                 ldapsrv_terminate_connection(conn, "no memory");
538                 return;
539         }
540         talloc_set_destructor(call, ldapsrv_call_destructor);
541
542         call->conn = conn;
543
544         status = tstream_read_pdu_blob_recv(subreq,
545                                             call,
546                                             &blob);
547         TALLOC_FREE(subreq);
548         if (!NT_STATUS_IS_OK(status)) {
549                 const char *reason;
550
551                 reason = talloc_asprintf(call, "ldapsrv_call_loop: "
552                                          "tstream_read_pdu_blob_recv() - %s",
553                                          nt_errstr(status));
554                 if (!reason) {
555                         reason = nt_errstr(status);
556                 }
557
558                 ldapsrv_terminate_connection(conn, reason);
559                 return;
560         }
561
562         asn1 = asn1_init(call);
563         if (asn1 == NULL) {
564                 ldapsrv_terminate_connection(conn, "no memory");
565                 return;
566         }
567
568         call->request = talloc(call, struct ldap_message);
569         if (call->request == NULL) {
570                 ldapsrv_terminate_connection(conn, "no memory");
571                 return;
572         }
573
574         if (!asn1_load(asn1, blob)) {
575                 ldapsrv_terminate_connection(conn, "asn1_load failed");
576                 return;
577         }
578
579         status = ldap_decode(asn1, samba_ldap_control_handlers(),
580                              call->request);
581         if (!NT_STATUS_IS_OK(status)) {
582                 ldapsrv_terminate_connection(conn, nt_errstr(status));
583                 return;
584         }
585
586         data_blob_free(&blob);
587
588
589         /* queue the call in the global queue */
590         subreq = ldapsrv_process_call_send(call,
591                                            conn->connection->event.ctx,
592                                            conn->service->call_queue,
593                                            call);
594         if (subreq == NULL) {
595                 ldapsrv_terminate_connection(conn, "ldapsrv_process_call_send failed");
596                 return;
597         }
598         tevent_req_set_callback(subreq, ldapsrv_call_process_done, call);
599         conn->active_call = subreq;
600 }
601
602 static void ldapsrv_call_wait_done(struct tevent_req *subreq);
603 static void ldapsrv_call_writev_start(struct ldapsrv_call *call);
604 static void ldapsrv_call_writev_done(struct tevent_req *subreq);
605
606 static void ldapsrv_call_process_done(struct tevent_req *subreq)
607 {
608         struct ldapsrv_call *call =
609                 tevent_req_callback_data(subreq,
610                 struct ldapsrv_call);
611         struct ldapsrv_connection *conn = call->conn;
612         NTSTATUS status;
613
614         conn->active_call = NULL;
615
616         status = ldapsrv_process_call_recv(subreq);
617         TALLOC_FREE(subreq);
618         if (!NT_STATUS_IS_OK(status)) {
619                 ldapsrv_terminate_connection(conn, nt_errstr(status));
620                 return;
621         }
622
623         if (call->wait_send != NULL) {
624                 subreq = call->wait_send(call,
625                                          conn->connection->event.ctx,
626                                          call->wait_private);
627                 if (subreq == NULL) {
628                         ldapsrv_terminate_connection(conn,
629                                         "ldapsrv_call_process_done: "
630                                         "call->wait_send - no memory");
631                         return;
632                 }
633                 tevent_req_set_callback(subreq,
634                                         ldapsrv_call_wait_done,
635                                         call);
636                 conn->active_call = subreq;
637                 return;
638         }
639
640         ldapsrv_call_writev_start(call);
641 }
642
643 static void ldapsrv_call_wait_done(struct tevent_req *subreq)
644 {
645         struct ldapsrv_call *call =
646                 tevent_req_callback_data(subreq,
647                 struct ldapsrv_call);
648         struct ldapsrv_connection *conn = call->conn;
649         NTSTATUS status;
650
651         conn->active_call = NULL;
652
653         status = call->wait_recv(subreq);
654         TALLOC_FREE(subreq);
655         if (!NT_STATUS_IS_OK(status)) {
656                 const char *reason;
657
658                 reason = talloc_asprintf(call, "ldapsrv_call_wait_done: "
659                                          "call->wait_recv() - %s",
660                                          nt_errstr(status));
661                 if (reason == NULL) {
662                         reason = nt_errstr(status);
663                 }
664
665                 ldapsrv_terminate_connection(conn, reason);
666                 return;
667         }
668
669         ldapsrv_call_writev_start(call);
670 }
671
672 static void ldapsrv_call_writev_start(struct ldapsrv_call *call)
673 {
674         struct ldapsrv_connection *conn = call->conn;
675         DATA_BLOB blob = data_blob_null;
676         struct tevent_req *subreq = NULL;
677
678         /* build all the replies into a single blob */
679         while (call->replies) {
680                 DATA_BLOB b;
681                 bool ret;
682
683                 if (!ldap_encode(call->replies->msg, samba_ldap_control_handlers(), &b, call)) {
684                         DEBUG(0,("Failed to encode ldap reply of type %d\n",
685                                  call->replies->msg->type));
686                         ldapsrv_terminate_connection(conn, "ldap_encode failed");
687                         return;
688                 }
689
690                 ret = data_blob_append(call, &blob, b.data, b.length);
691                 data_blob_free(&b);
692
693                 talloc_set_name_const(blob.data, "Outgoing, encoded LDAP packet");
694
695                 if (!ret) {
696                         ldapsrv_terminate_connection(conn, "data_blob_append failed");
697                         return;
698                 }
699
700                 DLIST_REMOVE(call->replies, call->replies);
701         }
702
703         if (blob.length == 0) {
704                 if (!call->notification.busy) {
705                         TALLOC_FREE(call);
706                 }
707
708                 ldapsrv_call_read_next(conn);
709                 return;
710         }
711
712         call->out_iov.iov_base = blob.data;
713         call->out_iov.iov_len = blob.length;
714
715         subreq = tstream_writev_queue_send(call,
716                                            conn->connection->event.ctx,
717                                            conn->sockets.active,
718                                            conn->sockets.send_queue,
719                                            &call->out_iov, 1);
720         if (subreq == NULL) {
721                 ldapsrv_terminate_connection(conn, "stream_writev_queue_send failed");
722                 return;
723         }
724         tevent_req_set_callback(subreq, ldapsrv_call_writev_done, call);
725 }
726
727 static void ldapsrv_call_postprocess_done(struct tevent_req *subreq);
728
729 static void ldapsrv_call_writev_done(struct tevent_req *subreq)
730 {
731         struct ldapsrv_call *call =
732                 tevent_req_callback_data(subreq,
733                 struct ldapsrv_call);
734         struct ldapsrv_connection *conn = call->conn;
735         int sys_errno;
736         int rc;
737
738         rc = tstream_writev_queue_recv(subreq, &sys_errno);
739         TALLOC_FREE(subreq);
740         if (rc == -1) {
741                 const char *reason;
742
743                 reason = talloc_asprintf(call, "ldapsrv_call_writev_done: "
744                                          "tstream_writev_queue_recv() - %d:%s",
745                                          sys_errno, strerror(sys_errno));
746                 if (reason == NULL) {
747                         reason = "ldapsrv_call_writev_done: "
748                                  "tstream_writev_queue_recv() failed";
749                 }
750
751                 ldapsrv_terminate_connection(conn, reason);
752                 return;
753         }
754
755         if (call->postprocess_send) {
756                 subreq = call->postprocess_send(call,
757                                                 conn->connection->event.ctx,
758                                                 call->postprocess_private);
759                 if (subreq == NULL) {
760                         ldapsrv_terminate_connection(conn, "ldapsrv_call_writev_done: "
761                                         "call->postprocess_send - no memory");
762                         return;
763                 }
764                 tevent_req_set_callback(subreq,
765                                         ldapsrv_call_postprocess_done,
766                                         call);
767                 return;
768         }
769
770         if (!call->notification.busy) {
771                 TALLOC_FREE(call);
772         }
773
774         ldapsrv_call_read_next(conn);
775 }
776
777 static void ldapsrv_call_postprocess_done(struct tevent_req *subreq)
778 {
779         struct ldapsrv_call *call =
780                 tevent_req_callback_data(subreq,
781                 struct ldapsrv_call);
782         struct ldapsrv_connection *conn = call->conn;
783         NTSTATUS status;
784
785         status = call->postprocess_recv(subreq);
786         TALLOC_FREE(subreq);
787         if (!NT_STATUS_IS_OK(status)) {
788                 const char *reason;
789
790                 reason = talloc_asprintf(call, "ldapsrv_call_postprocess_done: "
791                                          "call->postprocess_recv() - %s",
792                                          nt_errstr(status));
793                 if (reason == NULL) {
794                         reason = nt_errstr(status);
795                 }
796
797                 ldapsrv_terminate_connection(conn, reason);
798                 return;
799         }
800
801         TALLOC_FREE(call);
802
803         ldapsrv_call_read_next(conn);
804 }
805
806 static void ldapsrv_notification_retry_done(struct tevent_req *subreq);
807
808 void ldapsrv_notification_retry_setup(struct ldapsrv_service *service, bool force)
809 {
810         struct ldapsrv_connection *conn = NULL;
811         struct timeval retry;
812         size_t num_pending = 0;
813         size_t num_active = 0;
814
815         if (force) {
816                 TALLOC_FREE(service->notification.retry);
817                 service->notification.generation += 1;
818         }
819
820         if (service->notification.retry != NULL) {
821                 return;
822         }
823
824         for (conn = service->connections; conn != NULL; conn = conn->next) {
825                 if (conn->pending_calls == NULL) {
826                         continue;
827                 }
828
829                 num_pending += 1;
830
831                 if (conn->pending_calls->notification.generation !=
832                     service->notification.generation)
833                 {
834                         num_active += 1;
835                 }
836         }
837
838         if (num_pending == 0) {
839                 return;
840         }
841
842         if (num_active != 0) {
843                 retry = timeval_current_ofs(0, 100);
844         } else {
845                 retry = timeval_current_ofs(5, 0);
846         }
847
848         service->notification.retry = tevent_wakeup_send(service,
849                                                          service->task->event_ctx,
850                                                          retry);
851         if (service->notification.retry == NULL) {
852                 /* retry later */
853                 return;
854         }
855
856         tevent_req_set_callback(service->notification.retry,
857                                 ldapsrv_notification_retry_done,
858                                 service);
859 }
860
861 static void ldapsrv_notification_retry_done(struct tevent_req *subreq)
862 {
863         struct ldapsrv_service *service =
864                 tevent_req_callback_data(subreq,
865                 struct ldapsrv_service);
866         struct ldapsrv_connection *conn = NULL;
867         struct ldapsrv_connection *conn_next = NULL;
868         bool ok;
869
870         service->notification.retry = NULL;
871
872         ok = tevent_wakeup_recv(subreq);
873         TALLOC_FREE(subreq);
874         if (!ok) {
875                 /* ignore */
876         }
877
878         for (conn = service->connections; conn != NULL; conn = conn_next) {
879                 struct ldapsrv_call *call = conn->pending_calls;
880
881                 conn_next = conn->next;
882
883                 if (conn->pending_calls == NULL) {
884                         continue;
885                 }
886
887                 if (conn->active_call != NULL) {
888                         continue;
889                 }
890
891                 DLIST_DEMOTE(conn->pending_calls, call);
892                 call->notification.generation =
893                                 service->notification.generation;
894
895                 /* queue the call in the global queue */
896                 subreq = ldapsrv_process_call_send(call,
897                                                    conn->connection->event.ctx,
898                                                    conn->service->call_queue,
899                                                    call);
900                 if (subreq == NULL) {
901                         ldapsrv_terminate_connection(conn,
902                                         "ldapsrv_process_call_send failed");
903                         continue;
904                 }
905                 tevent_req_set_callback(subreq, ldapsrv_call_process_done, call);
906                 conn->active_call = subreq;
907         }
908
909         ldapsrv_notification_retry_setup(service, false);
910 }
911
912 struct ldapsrv_process_call_state {
913         struct ldapsrv_call *call;
914 };
915
916 static void ldapsrv_process_call_trigger(struct tevent_req *req,
917                                          void *private_data);
918
919 static struct tevent_req *ldapsrv_process_call_send(TALLOC_CTX *mem_ctx,
920                                                     struct tevent_context *ev,
921                                                     struct tevent_queue *call_queue,
922                                                     struct ldapsrv_call *call)
923 {
924         struct tevent_req *req;
925         struct ldapsrv_process_call_state *state;
926         bool ok;
927
928         req = tevent_req_create(mem_ctx, &state,
929                                 struct ldapsrv_process_call_state);
930         if (req == NULL) {
931                 return req;
932         }
933
934         state->call = call;
935
936         ok = tevent_queue_add(call_queue, ev, req,
937                               ldapsrv_process_call_trigger, NULL);
938         if (!ok) {
939                 tevent_req_oom(req);
940                 return tevent_req_post(req, ev);
941         }
942
943         return req;
944 }
945
946 static void ldapsrv_process_call_trigger(struct tevent_req *req,
947                                          void *private_data)
948 {
949         struct ldapsrv_process_call_state *state =
950                 tevent_req_data(req,
951                 struct ldapsrv_process_call_state);
952         NTSTATUS status;
953
954         /* make the call */
955         status = ldapsrv_do_call(state->call);
956         if (!NT_STATUS_IS_OK(status)) {
957                 tevent_req_nterror(req, status);
958                 return;
959         }
960
961         tevent_req_done(req);
962 }
963
964 static NTSTATUS ldapsrv_process_call_recv(struct tevent_req *req)
965 {
966         NTSTATUS status;
967
968         if (tevent_req_is_nterror(req, &status)) {
969                 tevent_req_received(req);
970                 return status;
971         }
972
973         tevent_req_received(req);
974         return NT_STATUS_OK;
975 }
976
977 static void ldapsrv_accept_nonpriv(struct stream_connection *c)
978 {
979         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
980                 c->private_data, struct ldapsrv_service);
981         struct auth_session_info *session_info;
982         NTSTATUS status;
983
984         status = auth_anonymous_session_info(
985                 c, ldapsrv_service->task->lp_ctx, &session_info);
986         if (!NT_STATUS_IS_OK(status)) {
987                 stream_terminate_connection(c, "failed to setup anonymous "
988                                             "session info");
989                 return;
990         }
991         ldapsrv_accept(c, session_info, false);
992 }
993
994 static const struct stream_server_ops ldap_stream_nonpriv_ops = {
995         .name                   = "ldap",
996         .accept_connection      = ldapsrv_accept_nonpriv,
997         .recv_handler           = ldapsrv_recv,
998         .send_handler           = ldapsrv_send,
999 };
1000
1001 /* The feature removed behind an #ifdef until we can do it properly
1002  * with an EXTERNAL bind. */
1003
1004 #define WITH_LDAPI_PRIV_SOCKET
1005
1006 #ifdef WITH_LDAPI_PRIV_SOCKET
1007 static void ldapsrv_accept_priv(struct stream_connection *c)
1008 {
1009         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
1010                 c->private_data, struct ldapsrv_service);
1011         struct auth_session_info *session_info;
1012
1013         session_info = system_session(ldapsrv_service->task->lp_ctx);
1014         if (!session_info) {
1015                 stream_terminate_connection(c, "failed to setup system "
1016                                             "session info");
1017                 return;
1018         }
1019         ldapsrv_accept(c, session_info, true);
1020 }
1021
1022 static const struct stream_server_ops ldap_stream_priv_ops = {
1023         .name                   = "ldap",
1024         .accept_connection      = ldapsrv_accept_priv,
1025         .recv_handler           = ldapsrv_recv,
1026         .send_handler           = ldapsrv_send,
1027 };
1028
1029 #endif
1030
1031
1032 /*
1033   add a socket address to the list of events, one event per port
1034 */
1035 static NTSTATUS add_socket(struct task_server *task,
1036                            struct loadparm_context *lp_ctx,
1037                            const struct model_ops *model_ops,
1038                            const char *address, struct ldapsrv_service *ldap_service)
1039 {
1040         uint16_t port = 389;
1041         NTSTATUS status;
1042         struct ldb_context *ldb;
1043
1044         status = stream_setup_socket(task, task->event_ctx, lp_ctx,
1045                                      model_ops, &ldap_stream_nonpriv_ops,
1046                                      "ip", address, &port,
1047                                      lpcfg_socket_options(lp_ctx),
1048                                      ldap_service, task->process_context);
1049         if (!NT_STATUS_IS_OK(status)) {
1050                 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
1051                          address, port, nt_errstr(status)));
1052                 return status;
1053         }
1054
1055         if (tstream_tls_params_enabled(ldap_service->tls_params)) {
1056                 /* add ldaps server */
1057                 port = 636;
1058                 status = stream_setup_socket(task, task->event_ctx, lp_ctx,
1059                                              model_ops,
1060                                              &ldap_stream_nonpriv_ops,
1061                                              "ip", address, &port,
1062                                              lpcfg_socket_options(lp_ctx),
1063                                              ldap_service,
1064                                              task->process_context);
1065                 if (!NT_STATUS_IS_OK(status)) {
1066                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
1067                                  address, port, nt_errstr(status)));
1068                         return status;
1069                 }
1070         }
1071
1072         /* Load LDAP database, but only to read our settings */
1073         ldb = samdb_connect(ldap_service,
1074                             ldap_service->task->event_ctx,
1075                             lp_ctx,
1076                             system_session(lp_ctx),
1077                             NULL,
1078                             0);
1079         if (!ldb) {
1080                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1081         }
1082
1083         if (samdb_is_gc(ldb)) {
1084                 port = 3268;
1085                 status = stream_setup_socket(task, task->event_ctx, lp_ctx,
1086                                              model_ops,
1087                                              &ldap_stream_nonpriv_ops,
1088                                              "ip", address, &port,
1089                                              lpcfg_socket_options(lp_ctx),
1090                                              ldap_service,
1091                                              task->process_context);
1092                 if (!NT_STATUS_IS_OK(status)) {
1093                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
1094                                  address, port, nt_errstr(status)));
1095                         return status;
1096                 }
1097                 if (tstream_tls_params_enabled(ldap_service->tls_params)) {
1098                         /* add ldaps server for the global catalog */
1099                         port = 3269;
1100                         status = stream_setup_socket(task, task->event_ctx, lp_ctx,
1101                                                      model_ops,
1102                                                      &ldap_stream_nonpriv_ops,
1103                                                      "ip", address, &port,
1104                                                      lpcfg_socket_options(lp_ctx),
1105                                                      ldap_service,
1106                                                      task->process_context);
1107                         if (!NT_STATUS_IS_OK(status)) {
1108                                 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
1109                                          address, port, nt_errstr(status)));
1110                                 return status;
1111                         }
1112                 }
1113         }
1114
1115         /* And once we are bound, free the temporary ldb, it will
1116          * connect again on each incoming LDAP connection */
1117         talloc_unlink(ldap_service, ldb);
1118
1119         return NT_STATUS_OK;
1120 }
1121
1122 /*
1123   open the ldap server sockets
1124 */
1125 static NTSTATUS ldapsrv_task_init(struct task_server *task)
1126 {       
1127         char *ldapi_path;
1128 #ifdef WITH_LDAPI_PRIV_SOCKET
1129         char *priv_dir;
1130 #endif
1131         const char *dns_host_name;
1132         struct ldapsrv_service *ldap_service;
1133         NTSTATUS status;
1134
1135         switch (lpcfg_server_role(task->lp_ctx)) {
1136         case ROLE_STANDALONE:
1137                 task_server_terminate(task, "ldap_server: no LDAP server required in standalone configuration", 
1138                                       false);
1139                 return NT_STATUS_INVALID_DOMAIN_ROLE;
1140         case ROLE_DOMAIN_MEMBER:
1141                 task_server_terminate(task, "ldap_server: no LDAP server required in member server configuration", 
1142                                       false);
1143                 return NT_STATUS_INVALID_DOMAIN_ROLE;
1144         case ROLE_ACTIVE_DIRECTORY_DC:
1145                 /* Yes, we want an LDAP server */
1146                 break;
1147         }
1148
1149         task_server_set_title(task, "task[ldapsrv]");
1150
1151         ldap_service = talloc_zero(task, struct ldapsrv_service);
1152         if (ldap_service == NULL) {
1153                 status = NT_STATUS_NO_MEMORY;
1154                 goto failed;
1155         }
1156
1157         ldap_service->task = task;
1158
1159         dns_host_name = talloc_asprintf(ldap_service, "%s.%s",
1160                                         lpcfg_netbios_name(task->lp_ctx),
1161                                         lpcfg_dnsdomain(task->lp_ctx));
1162         if (dns_host_name == NULL) {
1163                 status = NT_STATUS_NO_MEMORY;
1164                 goto failed;
1165         }
1166
1167         status = tstream_tls_params_server(ldap_service,
1168                                            dns_host_name,
1169                                            lpcfg_tls_enabled(task->lp_ctx),
1170                                            lpcfg_tls_keyfile(ldap_service, task->lp_ctx),
1171                                            lpcfg_tls_certfile(ldap_service, task->lp_ctx),
1172                                            lpcfg_tls_cafile(ldap_service, task->lp_ctx),
1173                                            lpcfg_tls_crlfile(ldap_service, task->lp_ctx),
1174                                            lpcfg_tls_dhpfile(ldap_service, task->lp_ctx),
1175                                            lpcfg_tls_priority(task->lp_ctx),
1176                                            &ldap_service->tls_params);
1177         if (!NT_STATUS_IS_OK(status)) {
1178                 DEBUG(0,("ldapsrv failed tstream_tls_params_server - %s\n",
1179                          nt_errstr(status)));
1180                 goto failed;
1181         }
1182
1183         ldap_service->call_queue = tevent_queue_create(ldap_service, "ldapsrv_call_queue");
1184         if (ldap_service->call_queue == NULL) {
1185                 status = NT_STATUS_NO_MEMORY;
1186                 goto failed;
1187         }
1188
1189         if (lpcfg_interfaces(task->lp_ctx) && lpcfg_bind_interfaces_only(task->lp_ctx)) {
1190                 struct interface *ifaces;
1191                 int num_interfaces;
1192                 int i;
1193
1194                 load_interface_list(task, task->lp_ctx, &ifaces);
1195                 num_interfaces = iface_list_count(ifaces);
1196
1197                 /* We have been given an interfaces line, and been 
1198                    told to only bind to those interfaces. Create a
1199                    socket per interface and bind to only these.
1200                 */
1201                 for(i = 0; i < num_interfaces; i++) {
1202                         const char *address = iface_list_n_ip(ifaces, i);
1203                         status = add_socket(task, task->lp_ctx, task->model_ops,
1204                                             address, ldap_service);
1205                         if (!NT_STATUS_IS_OK(status)) goto failed;
1206                 }
1207         } else {
1208                 char **wcard;
1209                 size_t i;
1210                 size_t num_binds = 0;
1211                 wcard = iface_list_wildcard(task);
1212                 if (wcard == NULL) {
1213                         DEBUG(0,("No wildcard addresses available\n"));
1214                         status = NT_STATUS_UNSUCCESSFUL;
1215                         goto failed;
1216                 }
1217                 for (i=0; wcard[i]; i++) {
1218                         status = add_socket(task, task->lp_ctx, task->model_ops,
1219                                             wcard[i], ldap_service);
1220                         if (NT_STATUS_IS_OK(status)) {
1221                                 num_binds++;
1222                         }
1223                 }
1224                 talloc_free(wcard);
1225                 if (num_binds == 0) {
1226                         status = NT_STATUS_UNSUCCESSFUL;
1227                         goto failed;
1228                 }
1229         }
1230
1231         ldapi_path = lpcfg_private_path(ldap_service, task->lp_ctx, "ldapi");
1232         if (!ldapi_path) {
1233                 status = NT_STATUS_UNSUCCESSFUL;
1234                 goto failed;
1235         }
1236
1237         status = stream_setup_socket(task, task->event_ctx, task->lp_ctx,
1238                                      task->model_ops, &ldap_stream_nonpriv_ops,
1239                                      "unix", ldapi_path, NULL, 
1240                                      lpcfg_socket_options(task->lp_ctx),
1241                                      ldap_service, task->process_context);
1242         talloc_free(ldapi_path);
1243         if (!NT_STATUS_IS_OK(status)) {
1244                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
1245                          ldapi_path, nt_errstr(status)));
1246         }
1247
1248 #ifdef WITH_LDAPI_PRIV_SOCKET
1249         priv_dir = lpcfg_private_path(ldap_service, task->lp_ctx, "ldap_priv");
1250         if (priv_dir == NULL) {
1251                 status = NT_STATUS_UNSUCCESSFUL;
1252                 goto failed;
1253         }
1254         /*
1255          * Make sure the directory for the privileged ldapi socket exists, and
1256          * is of the correct permissions
1257          */
1258         if (!directory_create_or_exist(priv_dir, 0750)) {
1259                 task_server_terminate(task, "Cannot create ldap "
1260                                       "privileged ldapi directory", true);
1261                 return NT_STATUS_UNSUCCESSFUL;
1262         }
1263         ldapi_path = talloc_asprintf(ldap_service, "%s/ldapi", priv_dir);
1264         talloc_free(priv_dir);
1265         if (ldapi_path == NULL) {
1266                 status = NT_STATUS_NO_MEMORY;
1267                 goto failed;
1268         }
1269
1270         status = stream_setup_socket(task, task->event_ctx, task->lp_ctx,
1271                                      task->model_ops, &ldap_stream_priv_ops,
1272                                      "unix", ldapi_path, NULL,
1273                                      lpcfg_socket_options(task->lp_ctx),
1274                                      ldap_service,
1275                                      task->process_context);
1276         talloc_free(ldapi_path);
1277         if (!NT_STATUS_IS_OK(status)) {
1278                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
1279                          ldapi_path, nt_errstr(status)));
1280         }
1281
1282 #endif
1283
1284         /* register the server */
1285         irpc_add_name(task->msg_ctx, "ldap_server");
1286         return NT_STATUS_OK;
1287
1288 failed:
1289         task_server_terminate(task, "Failed to startup ldap server task", true);
1290         return status;
1291 }
1292
1293
1294 NTSTATUS server_service_ldap_init(TALLOC_CTX *ctx)
1295 {
1296         static const struct service_details details = {
1297                 .inhibit_fork_on_accept = false,
1298                 .inhibit_pre_fork = false,
1299                 .task_init = ldapsrv_task_init,
1300                 .post_fork = NULL
1301         };
1302         return register_server_service(ctx, "ldap", &details);
1303 }