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