s4:ldap_server: rewrite to socket layer to use tstream
[metze/samba/wip.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 "lib/ldb/include/ldb.h"
40 #include "lib/ldb/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
50 static void ldapsrv_terminate_connection_done(struct tevent_req *subreq);
51
52 /*
53   close the socket and shutdown a server_context
54 */
55 static void ldapsrv_terminate_connection(struct ldapsrv_connection *conn,
56                                          const char *reason)
57 {
58         struct tevent_req *subreq;
59
60         if (conn->limits.reason) {
61                 return;
62         }
63
64         conn->limits.endtime = timeval_current_ofs(0, 500);
65
66         DEBUG(2,("ldapsrv_terminate_connection: %s - disconnecting\n",
67                  reason));
68
69         tevent_queue_stop(conn->sockets.send_queue);
70         if (conn->active_call) {
71                 tevent_req_cancel(conn->active_call);
72                 conn->active_call = NULL;
73         }
74
75         conn->limits.reason = talloc_strdup(conn, reason);
76         if (conn->limits.reason == NULL) {
77                 TALLOC_FREE(conn->sockets.tls);
78                 TALLOC_FREE(conn->sockets.sasl);
79                 TALLOC_FREE(conn->sockets.raw);
80                 stream_terminate_connection(conn->connection, reason);
81                 return;
82         }
83
84         subreq = tstream_disconnect_send(conn,
85                                          conn->connection->event.ctx,
86                                          conn->sockets.active);
87         if (subreq == NULL) {
88                 TALLOC_FREE(conn->sockets.tls);
89                 TALLOC_FREE(conn->sockets.sasl);
90                 TALLOC_FREE(conn->sockets.raw);
91                 stream_terminate_connection(conn->connection, reason);
92                 return;
93         }
94         tevent_req_set_endtime(subreq,
95                                conn->connection->event.ctx,
96                                conn->limits.endtime);
97         tevent_req_set_callback(subreq, ldapsrv_terminate_connection_done, conn);
98 }
99
100 static void ldapsrv_terminate_connection_done(struct tevent_req *subreq)
101 {
102         struct ldapsrv_connection *conn =
103                 tevent_req_callback_data(subreq,
104                 struct ldapsrv_connection);
105         int ret;
106         int sys_errno;
107
108         ret = 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.search_timeout = 120;
173
174
175         tmp_ctx = talloc_new(conn);
176         if (tmp_ctx == NULL) {
177                 return -1;
178         }
179
180         basedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);
181         if ( ! ldb_dn_validate(basedn)) {
182                 goto failed;
183         }
184
185         ret = ldb_search(conn->ldb, tmp_ctx, &res, basedn, LDB_SCOPE_BASE, attrs, NULL);
186         if (ret != LDB_SUCCESS) {
187                 goto failed;
188         }
189
190         if (res->count != 1) {
191                 goto failed;
192         }
193
194         conf_dn = ldb_msg_find_attr_as_dn(conn->ldb, tmp_ctx, res->msgs[0], "configurationNamingContext");
195         if (conf_dn == NULL) {
196                 goto failed;
197         }
198
199         policy_dn = ldb_dn_copy(tmp_ctx, conf_dn);
200         ldb_dn_add_child_fmt(policy_dn, "CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services");
201         if (policy_dn == NULL) {
202                 goto failed;
203         }
204
205         ret = ldb_search(conn->ldb, tmp_ctx, &res, policy_dn, LDB_SCOPE_BASE, attrs2, NULL);
206         if (ret != LDB_SUCCESS) {
207                 goto failed;
208         }
209
210         if (res->count != 1) {
211                 goto failed;
212         }
213
214         el = ldb_msg_find_element(res->msgs[0], "lDAPAdminLimits");
215         if (el == NULL) {
216                 goto failed;
217         }
218
219         for (i = 0; i < el->num_values; i++) {
220                 char policy_name[256];
221                 int policy_value, s;
222
223                 s = sscanf((const char *)el->values[i].data, "%255[^=]=%d", policy_name, &policy_value);
224                 if (ret != 2 || policy_value == 0)
225                         continue;
226
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("MaxQueryDuration", policy_name) == 0) {
240                         conn->limits.search_timeout = policy_value;
241                         continue;
242                 }
243         }
244
245         return 0;
246
247 failed:
248         DEBUG(0, ("Failed to load ldap server query policies\n"));
249         talloc_free(tmp_ctx);
250         return -1;
251 }
252
253 static struct tevent_req *ldapsrv_process_call_send(TALLOC_CTX *mem_ctx,
254                                                     struct tevent_context *ev,
255                                                     struct tevent_queue *call_queue,
256                                                     struct ldapsrv_call *call);
257 static NTSTATUS ldapsrv_process_call_recv(struct tevent_req *req);
258
259 static bool ldapsrv_call_read_next(struct ldapsrv_connection *conn);
260 static void ldapsrv_accept_tls_done(struct tevent_req *subreq);
261
262 /*
263   initialise a server_context from a open socket and register a event handler
264   for reading from that socket
265 */
266 static void ldapsrv_accept(struct stream_connection *c,
267                            struct auth_session_info *session_info)
268 {
269         struct ldapsrv_service *ldapsrv_service = 
270                 talloc_get_type(c->private_data, struct ldapsrv_service);
271         struct ldapsrv_connection *conn;
272         struct cli_credentials *server_credentials;
273         struct socket_address *socket_address;
274         NTSTATUS status;
275         int port;
276         int ret;
277         struct tevent_req *subreq;
278         struct timeval endtime;
279
280         conn = talloc_zero(c, struct ldapsrv_connection);
281         if (!conn) {
282                 stream_terminate_connection(c, "ldapsrv_accept: out of memory");
283                 return;
284         }
285
286         conn->sockets.send_queue = tevent_queue_create(conn, "ldapsev send queue");
287         if (conn->sockets.send_queue == NULL) {
288                 stream_terminate_connection(c,
289                                             "ldapsrv_accept: tevent_queue_create failed");
290                 return;
291         }
292
293         TALLOC_FREE(c->event.fde);
294
295         /*
296          * Clone the fd that the connection isn't closed if we create a client
297          * connection.
298          */
299         ret = tstream_bsd_existing_socket(conn,
300                                           socket_get_fd(c->socket),
301                                           &conn->sockets.raw);
302         if (ret == -1) {
303                 stream_terminate_connection(c,
304                                             "ldapsrv_accept: out of memory");
305                 return;
306         }
307         socket_set_flags(c->socket, SOCKET_FLAG_NOCLOSE);
308
309         conn->connection  = c;
310         conn->service     = ldapsrv_service;
311         conn->lp_ctx      = ldapsrv_service->task->lp_ctx;
312
313         c->private_data   = conn;
314
315         socket_address = socket_get_my_addr(c->socket, conn);
316         if (!socket_address) {
317                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: failed to obtain local socket address!");
318                 return;
319         }
320         port = socket_address->port;
321         talloc_free(socket_address);
322         if (port == 3268) /* Global catalog */ {
323                 conn->global_catalog = true;
324         }
325
326         server_credentials = cli_credentials_init(conn);
327         if (!server_credentials) {
328                 stream_terminate_connection(c, "Failed to init server credentials\n");
329                 return;
330         }
331
332         cli_credentials_set_conf(server_credentials, conn->lp_ctx);
333         status = cli_credentials_set_machine_account(server_credentials, conn->lp_ctx);
334         if (!NT_STATUS_IS_OK(status)) {
335                 stream_terminate_connection(c, talloc_asprintf(conn, "Failed to obtain server credentials, perhaps a standalone server?: %s\n", nt_errstr(status)));
336                 return;
337         }
338         conn->server_credentials = server_credentials;
339
340         conn->session_info = talloc_move(conn, &session_info);
341
342         if (!NT_STATUS_IS_OK(ldapsrv_backend_Init(conn))) {
343                 ldapsrv_terminate_connection(conn, "backend Init failed");
344                 return;
345         }
346
347         /* load limits from the conf partition */
348         ldapsrv_load_limits(conn); /* should we fail on error ? */
349
350         /* register the server */       
351         irpc_add_name(c->msg_ctx, "ldap_server");
352
353         conn->sockets.active = conn->sockets.raw;
354
355         if (port != 636) {
356                 ldapsrv_call_read_next(conn);
357                 return;
358         }
359
360         endtime = timeval_current_ofs(conn->limits.conn_idle_time, 0);
361
362         subreq = tstream_tls_accept_send(conn,
363                                          conn->connection->event.ctx,
364                                          conn->sockets.raw,
365                                          conn->service->tls_params);
366         if (subreq == NULL) {
367                 ldapsrv_terminate_connection(conn, "ldapsrv_accept: "
368                                 "no memory for tstream_tls_accept_send");
369                 return;
370         }
371         tevent_req_set_endtime(subreq,
372                                conn->connection->event.ctx,
373                                endtime);
374         tevent_req_set_callback(subreq, ldapsrv_accept_tls_done, conn);
375 }
376
377 static void ldapsrv_accept_tls_done(struct tevent_req *subreq)
378 {
379         struct ldapsrv_connection *conn =
380                 tevent_req_callback_data(subreq,
381                 struct ldapsrv_connection);
382         int ret;
383         int sys_errno;
384
385         ret = tstream_tls_accept_recv(subreq, &sys_errno,
386                                       conn, &conn->sockets.tls);
387         TALLOC_FREE(subreq);
388         if (ret == -1) {
389                 const char *reason;
390
391                 reason = talloc_asprintf(conn, "ldapsrv_accept_tls_loop: "
392                                          "tstream_tls_accept_recv() - %d:%s",
393                                          sys_errno, strerror(sys_errno));
394                 if (!reason) {
395                         reason = "ldapsrv_accept_tls_loop: "
396                                  "tstream_tls_accept_recv() - failed";
397                 }
398
399                 ldapsrv_terminate_connection(conn, reason);
400                 return;
401         }
402
403         conn->sockets.active = conn->sockets.tls;
404         ldapsrv_call_read_next(conn);
405 }
406
407 static void ldapsrv_call_read_done(struct tevent_req *subreq);
408
409 static bool ldapsrv_call_read_next(struct ldapsrv_connection *conn)
410 {
411         struct tevent_req *subreq;
412
413         if (timeval_is_zero(&conn->limits.endtime)) {
414                 conn->limits.endtime =
415                         timeval_current_ofs(conn->limits.initial_timeout, 0);
416         } else {
417                 conn->limits.endtime =
418                         timeval_current_ofs(conn->limits.conn_idle_time, 0);
419         }
420
421         /*
422          * The minimun size of a LDAP pdu is 7 bytes
423          *
424          * dumpasn1 -hh ldap-unbind-min.dat
425          *
426          *     <30 05 02 01 09 42 00>
427          *    0    5: SEQUENCE {
428          *     <02 01 09>
429          *    2    1:   INTEGER 9
430          *     <42 00>
431          *    5    0:   [APPLICATION 2]
432          *          :     Error: Object has zero length.
433          *          :   }
434          *
435          * dumpasn1 -hh ldap-unbind-windows.dat
436          *
437          *     <30 84 00 00 00 05 02 01 09 42 00>
438          *    0    5: SEQUENCE {
439          *     <02 01 09>
440          *    6    1:   INTEGER 9
441          *     <42 00>
442          *    9    0:   [APPLICATION 2]
443          *          :     Error: Object has zero length.
444          *          :   }
445          *
446          * This means using an initial read size
447          * of 7 is ok.
448          */
449         subreq = tstream_read_pdu_blob_send(conn,
450                                             conn->connection->event.ctx,
451                                             conn->sockets.active,
452                                             7, /* initial_read_size */
453                                             ldap_full_packet,
454                                             conn);
455         if (subreq == NULL) {
456                 ldapsrv_terminate_connection(conn, "ldapsrv_call_read_next: "
457                                 "no memory for tstream_read_pdu_blob_send");
458                 return false;
459         }
460         tevent_req_set_endtime(subreq,
461                                conn->connection->event.ctx,
462                                conn->limits.endtime);
463         tevent_req_set_callback(subreq, ldapsrv_call_read_done, conn);
464         return true;
465 }
466
467 static void ldapsrv_call_process_done(struct tevent_req *subreq);
468
469 static void ldapsrv_call_read_done(struct tevent_req *subreq)
470 {
471         struct ldapsrv_connection *conn =
472                 tevent_req_callback_data(subreq,
473                 struct ldapsrv_connection);
474         NTSTATUS status;
475         struct ldapsrv_call *call;
476         struct asn1_data *asn1;
477         DATA_BLOB blob;
478
479         call = talloc_zero(conn, struct ldapsrv_call);
480         if (!call) {
481                 ldapsrv_terminate_connection(conn, "no memory");
482                 return;
483         }
484
485         call->conn = conn;
486
487         status = tstream_read_pdu_blob_recv(subreq,
488                                             call,
489                                             &blob);
490         TALLOC_FREE(subreq);
491         if (!NT_STATUS_IS_OK(status)) {
492                 const char *reason;
493
494                 reason = talloc_asprintf(call, "ldapsrv_call_loop: "
495                                          "tstream_read_pdu_blob_recv() - %s",
496                                          nt_errstr(status));
497                 if (!reason) {
498                         reason = nt_errstr(status);
499                 }
500
501                 ldapsrv_terminate_connection(conn, reason);
502                 return;
503         }
504
505         asn1 = asn1_init(call);
506         if (asn1 == NULL) {
507                 ldapsrv_terminate_connection(conn, "no memory");
508                 return;
509         }
510
511         call->request = talloc(call, struct ldap_message);
512         if (call->request == NULL) {
513                 ldapsrv_terminate_connection(conn, "no memory");
514                 return;
515         }
516
517         if (!asn1_load(asn1, blob)) {
518                 ldapsrv_terminate_connection(conn, "asn1_load failed");
519                 return;
520         }
521
522         status = ldap_decode(asn1, samba_ldap_control_handlers(),
523                              call->request);
524         if (!NT_STATUS_IS_OK(status)) {
525                 ldapsrv_terminate_connection(conn, nt_errstr(status));
526                 return;
527         }
528
529         data_blob_free(&blob);
530
531
532         /* queue the call in the global queue */
533         subreq = ldapsrv_process_call_send(call,
534                                            conn->connection->event.ctx,
535                                            conn->service->call_queue,
536                                            call);
537         if (subreq == NULL) {
538                 ldapsrv_terminate_connection(conn, "ldapsrv_process_call_send failed");
539                 return;
540         }
541         tevent_req_set_callback(subreq, ldapsrv_call_process_done, call);
542         conn->active_call = subreq;
543 }
544
545 static void ldapsrv_call_writev_done(struct tevent_req *subreq);
546
547 static void ldapsrv_call_process_done(struct tevent_req *subreq)
548 {
549         struct ldapsrv_call *call =
550                 tevent_req_callback_data(subreq,
551                 struct ldapsrv_call);
552         struct ldapsrv_connection *conn = call->conn;
553         NTSTATUS status;
554         DATA_BLOB blob = data_blob_null;
555
556         conn->active_call = NULL;
557
558         status = ldapsrv_process_call_recv(subreq);
559         TALLOC_FREE(subreq);
560         if (!NT_STATUS_IS_OK(status)) {
561                 ldapsrv_terminate_connection(conn, nt_errstr(status));
562                 return;
563         }
564
565         /* build all the replies into a single blob */
566         while (call->replies) {
567                 DATA_BLOB b;
568                 bool ret;
569
570                 if (!ldap_encode(call->replies->msg, samba_ldap_control_handlers(), &b, call)) {
571                         DEBUG(0,("Failed to encode ldap reply of type %d\n",
572                                  call->replies->msg->type));
573                         ldapsrv_terminate_connection(conn, "ldap_encode failed");
574                         return;
575                 }
576
577                 ret = data_blob_append(call, &blob, b.data, b.length);
578                 data_blob_free(&b);
579
580                 talloc_set_name_const(blob.data, "Outgoing, encoded LDAP packet");
581
582                 if (!ret) {
583                         ldapsrv_terminate_connection(conn, "data_blob_append failed");
584                         return;
585                 }
586
587                 DLIST_REMOVE(call->replies, call->replies);
588         }
589
590         if (blob.length == 0) {
591                 TALLOC_FREE(call);
592
593                 ldapsrv_call_read_next(conn);
594                 return;
595         }
596
597         call->out_iov.iov_base = blob.data;
598         call->out_iov.iov_len = blob.length;
599
600         subreq = tstream_writev_queue_send(call,
601                                            conn->connection->event.ctx,
602                                            conn->sockets.active,
603                                            conn->sockets.send_queue,
604                                            &call->out_iov, 1);
605         if (subreq == NULL) {
606                 ldapsrv_terminate_connection(conn, "stream_writev_queue_send failed");
607                 return;
608         }
609         tevent_req_set_callback(subreq, ldapsrv_call_writev_done, call);
610 }
611
612 static void ldapsrv_call_postprocess_done(struct tevent_req *subreq);
613
614 static void ldapsrv_call_writev_done(struct tevent_req *subreq)
615 {
616         struct ldapsrv_call *call =
617                 tevent_req_callback_data(subreq,
618                 struct ldapsrv_call);
619         struct ldapsrv_connection *conn = call->conn;
620         int sys_errno;
621         int rc;
622
623         rc = tstream_writev_queue_recv(subreq, &sys_errno);
624         TALLOC_FREE(subreq);
625         if (rc == -1) {
626                 const char *reason;
627
628                 reason = talloc_asprintf(call, "ldapsrv_call_writev_done: "
629                                          "tstream_writev_queue_recv() - %d:%s",
630                                          sys_errno, strerror(sys_errno));
631                 if (reason == NULL) {
632                         reason = "ldapsrv_call_writev_done: "
633                                  "tstream_writev_queue_recv() failed";
634                 }
635
636                 ldapsrv_terminate_connection(conn, reason);
637                 return;
638         }
639
640         if (call->postprocess_send) {
641                 subreq = call->postprocess_send(call,
642                                                 conn->connection->event.ctx,
643                                                 call->postprocess_private);
644                 if (subreq == NULL) {
645                         ldapsrv_terminate_connection(conn, "ldapsrv_call_writev_done: "
646                                         "call->postprocess_send - no memory");
647                         return;
648                 }
649                 tevent_req_set_callback(subreq,
650                                         ldapsrv_call_postprocess_done,
651                                         call);
652                 return;
653         }
654
655         TALLOC_FREE(call);
656
657         ldapsrv_call_read_next(conn);
658 }
659
660 static void ldapsrv_call_postprocess_done(struct tevent_req *subreq)
661 {
662         struct ldapsrv_call *call =
663                 tevent_req_callback_data(subreq,
664                 struct ldapsrv_call);
665         struct ldapsrv_connection *conn = call->conn;
666         NTSTATUS status;
667
668         status = call->postprocess_recv(subreq);
669         TALLOC_FREE(subreq);
670         if (!NT_STATUS_IS_OK(status)) {
671                 const char *reason;
672
673                 reason = talloc_asprintf(call, "ldapsrv_call_postprocess_done: "
674                                          "call->postprocess_recv() - %s",
675                                          nt_errstr(status));
676                 if (reason == NULL) {
677                         reason = nt_errstr(status);
678                 }
679
680                 ldapsrv_terminate_connection(conn, reason);
681                 return;
682         }
683
684         TALLOC_FREE(call);
685
686         ldapsrv_call_read_next(conn);
687 }
688
689 struct ldapsrv_process_call_state {
690         struct ldapsrv_call *call;
691 };
692
693 static void ldapsrv_process_call_trigger(struct tevent_req *req,
694                                          void *private_data);
695
696 static struct tevent_req *ldapsrv_process_call_send(TALLOC_CTX *mem_ctx,
697                                                     struct tevent_context *ev,
698                                                     struct tevent_queue *call_queue,
699                                                     struct ldapsrv_call *call)
700 {
701         struct tevent_req *req;
702         struct ldapsrv_process_call_state *state;
703         bool ok;
704
705         req = tevent_req_create(mem_ctx, &state,
706                                 struct ldapsrv_process_call_state);
707         if (req == NULL) {
708                 return req;
709         }
710
711         state->call = call;
712
713         ok = tevent_queue_add(call_queue, ev, req,
714                               ldapsrv_process_call_trigger, NULL);
715         if (!ok) {
716                 tevent_req_nomem(NULL, req);
717                 return tevent_req_post(req, ev);
718         }
719
720         return req;
721 }
722
723 static void ldapsrv_process_call_trigger(struct tevent_req *req,
724                                          void *private_data)
725 {
726         struct ldapsrv_process_call_state *state =
727                 tevent_req_data(req,
728                 struct ldapsrv_process_call_state);
729         NTSTATUS status;
730
731         /* make the call */
732         status = ldapsrv_do_call(state->call);
733         if (!NT_STATUS_IS_OK(status)) {
734                 tevent_req_nterror(req, status);
735                 return;
736         }
737
738         tevent_req_done(req);
739 }
740
741 static NTSTATUS ldapsrv_process_call_recv(struct tevent_req *req)
742 {
743         NTSTATUS status;
744
745         if (tevent_req_is_nterror(req, &status)) {
746                 tevent_req_received(req);
747                 return status;
748         }
749
750         tevent_req_received(req);
751         return NT_STATUS_OK;
752 }
753
754 static void ldapsrv_accept_nonpriv(struct stream_connection *c)
755 {
756         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
757                 c->private_data, struct ldapsrv_service);
758         struct auth_session_info *session_info;
759         NTSTATUS status;
760
761         status = auth_anonymous_session_info(
762                 c, ldapsrv_service->task->lp_ctx, &session_info);
763         if (!NT_STATUS_IS_OK(status)) {
764                 stream_terminate_connection(c, "failed to setup anonymous "
765                                             "session info");
766                 return;
767         }
768         ldapsrv_accept(c, session_info);
769 }
770
771 static const struct stream_server_ops ldap_stream_nonpriv_ops = {
772         .name                   = "ldap",
773         .accept_connection      = ldapsrv_accept_nonpriv,
774         .recv_handler           = ldapsrv_recv,
775         .send_handler           = ldapsrv_send,
776 };
777
778 /* The feature removed behind an #ifdef until we can do it properly
779  * with an EXTERNAL bind. */
780
781 #define WITH_LDAPI_PRIV_SOCKET
782
783 #ifdef WITH_LDAPI_PRIV_SOCKET
784 static void ldapsrv_accept_priv(struct stream_connection *c)
785 {
786         struct ldapsrv_service *ldapsrv_service = talloc_get_type_abort(
787                 c->private_data, struct ldapsrv_service);
788         struct auth_session_info *session_info;
789
790         session_info = system_session(ldapsrv_service->task->lp_ctx);
791         if (!session_info) {
792                 stream_terminate_connection(c, "failed to setup system "
793                                             "session info");
794                 return;
795         }
796         ldapsrv_accept(c, session_info);
797 }
798
799 static const struct stream_server_ops ldap_stream_priv_ops = {
800         .name                   = "ldap",
801         .accept_connection      = ldapsrv_accept_priv,
802         .recv_handler           = ldapsrv_recv,
803         .send_handler           = ldapsrv_send,
804 };
805
806 #endif
807 /*
808   add a socket address to the list of events, one event per port
809 */
810 static NTSTATUS add_socket(struct tevent_context *event_context,
811                            struct loadparm_context *lp_ctx,
812                            const struct model_ops *model_ops,
813                            const char *address, struct ldapsrv_service *ldap_service)
814 {
815         uint16_t port = 389;
816         NTSTATUS status;
817         struct ldb_context *ldb;
818
819         status = stream_setup_socket(event_context, lp_ctx,
820                                      model_ops, &ldap_stream_nonpriv_ops,
821                                      "ipv4", address, &port, 
822                                      lpcfg_socket_options(lp_ctx),
823                                      ldap_service);
824         if (!NT_STATUS_IS_OK(status)) {
825                 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
826                          address, port, nt_errstr(status)));
827                 return status;
828         }
829
830         if (tstream_tls_params_enabled(ldap_service->tls_params)) {
831                 /* add ldaps server */
832                 port = 636;
833                 status = stream_setup_socket(event_context, lp_ctx,
834                                              model_ops,
835                                              &ldap_stream_nonpriv_ops,
836                                              "ipv4", address, &port, 
837                                              lpcfg_socket_options(lp_ctx),
838                                              ldap_service);
839                 if (!NT_STATUS_IS_OK(status)) {
840                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
841                                  address, port, nt_errstr(status)));
842                         return status;
843                 }
844         }
845
846         /* Load LDAP database, but only to read our settings */
847         ldb = samdb_connect(ldap_service, ldap_service->task->event_ctx, 
848                             lp_ctx, system_session(lp_ctx));
849         if (!ldb) {
850                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
851         }
852
853         if (samdb_is_gc(ldb)) {
854                 port = 3268;
855                 status = stream_setup_socket(event_context, lp_ctx,
856                                              model_ops,
857                                              &ldap_stream_nonpriv_ops,
858                                              "ipv4", address, &port, 
859                                              lpcfg_socket_options(lp_ctx),
860                                              ldap_service);
861                 if (!NT_STATUS_IS_OK(status)) {
862                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
863                                  address, port, nt_errstr(status)));
864                         return status;
865                 }
866         }
867
868         /* And once we are bound, free the tempoary ldb, it will
869          * connect again on each incoming LDAP connection */
870         talloc_unlink(ldap_service, ldb);
871
872         return NT_STATUS_OK;
873 }
874
875 /*
876   open the ldap server sockets
877 */
878 static void ldapsrv_task_init(struct task_server *task)
879 {       
880         char *ldapi_path;
881 #ifdef WITH_LDAPI_PRIV_SOCKET
882         char *priv_dir;
883 #endif
884         const char *dns_host_name;
885         struct ldapsrv_service *ldap_service;
886         NTSTATUS status;
887         const struct model_ops *model_ops;
888
889         switch (lpcfg_server_role(task->lp_ctx)) {
890         case ROLE_STANDALONE:
891                 task_server_terminate(task, "ldap_server: no LDAP server required in standalone configuration", 
892                                       false);
893                 return;
894         case ROLE_DOMAIN_MEMBER:
895                 task_server_terminate(task, "ldap_server: no LDAP server required in member server configuration", 
896                                       false);
897                 return;
898         case ROLE_DOMAIN_CONTROLLER:
899                 /* Yes, we want an LDAP server */
900                 break;
901         }
902
903         task_server_set_title(task, "task[ldapsrv]");
904
905         /* run the ldap server as a single process */
906         model_ops = process_model_startup(task->event_ctx, "single");
907         if (!model_ops) goto failed;
908
909         ldap_service = talloc_zero(task, struct ldapsrv_service);
910         if (ldap_service == NULL) goto failed;
911
912         ldap_service->task = task;
913
914         dns_host_name = talloc_asprintf(ldap_service, "%s.%s",
915                                         lpcfg_netbios_name(task->lp_ctx),
916                                         lpcfg_dnsdomain(task->lp_ctx));
917         if (dns_host_name == NULL) goto failed;
918
919         status = tstream_tls_params_server(ldap_service,
920                                            dns_host_name,
921                                            lpcfg_tls_enabled(task->lp_ctx),
922                                            lpcfg_tls_keyfile(ldap_service, task->lp_ctx),
923                                            lpcfg_tls_certfile(ldap_service, task->lp_ctx),
924                                            lpcfg_tls_cafile(ldap_service, task->lp_ctx),
925                                            lpcfg_tls_crlfile(ldap_service, task->lp_ctx),
926                                            lpcfg_tls_dhpfile(ldap_service, task->lp_ctx),
927                                            &ldap_service->tls_params);
928         if (!NT_STATUS_IS_OK(status)) {
929                 DEBUG(0,("ldapsrv failed tstream_tls_patams_server - %s\n",
930                          nt_errstr(status)));
931                 goto failed;
932         }
933
934         ldap_service->call_queue = tevent_queue_create(ldap_service, "ldapsrv_call_queue");
935         if (ldap_service->call_queue == NULL) goto failed;
936
937         if (lpcfg_interfaces(task->lp_ctx) && lpcfg_bind_interfaces_only(task->lp_ctx)) {
938                 struct interface *ifaces;
939                 int num_interfaces;
940                 int i;
941
942                 load_interfaces(task, lpcfg_interfaces(task->lp_ctx), &ifaces);
943                 num_interfaces = iface_count(ifaces);
944
945                 /* We have been given an interfaces line, and been 
946                    told to only bind to those interfaces. Create a
947                    socket per interface and bind to only these.
948                 */
949                 for(i = 0; i < num_interfaces; i++) {
950                         const char *address = iface_n_ip(ifaces, i);
951                         status = add_socket(task->event_ctx, task->lp_ctx, model_ops, address, ldap_service);
952                         if (!NT_STATUS_IS_OK(status)) goto failed;
953                 }
954         } else {
955                 status = add_socket(task->event_ctx, task->lp_ctx, model_ops,
956                                     lpcfg_socket_address(task->lp_ctx), ldap_service);
957                 if (!NT_STATUS_IS_OK(status)) goto failed;
958         }
959
960         ldapi_path = private_path(ldap_service, task->lp_ctx, "ldapi");
961         if (!ldapi_path) {
962                 goto failed;
963         }
964
965         status = stream_setup_socket(task->event_ctx, task->lp_ctx,
966                                      model_ops, &ldap_stream_nonpriv_ops,
967                                      "unix", ldapi_path, NULL, 
968                                      lpcfg_socket_options(task->lp_ctx),
969                                      ldap_service);
970         talloc_free(ldapi_path);
971         if (!NT_STATUS_IS_OK(status)) {
972                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
973                          ldapi_path, nt_errstr(status)));
974         }
975
976 #ifdef WITH_LDAPI_PRIV_SOCKET
977         priv_dir = private_path(ldap_service, task->lp_ctx, "ldap_priv");
978         if (priv_dir == NULL) {
979                 goto failed;
980         }
981         /*
982          * Make sure the directory for the privileged ldapi socket exists, and
983          * is of the correct permissions
984          */
985         if (!directory_create_or_exist(priv_dir, geteuid(), 0750)) {
986                 task_server_terminate(task, "Cannot create ldap "
987                                       "privileged ldapi directory", true);
988                 return;
989         }
990         ldapi_path = talloc_asprintf(ldap_service, "%s/ldapi", priv_dir);
991         talloc_free(priv_dir);
992         if (ldapi_path == NULL) {
993                 goto failed;
994         }
995
996         status = stream_setup_socket(task->event_ctx, task->lp_ctx,
997                                      model_ops, &ldap_stream_priv_ops,
998                                      "unix", ldapi_path, NULL,
999                                      lpcfg_socket_options(task->lp_ctx),
1000                                      ldap_service);
1001         talloc_free(ldapi_path);
1002         if (!NT_STATUS_IS_OK(status)) {
1003                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
1004                          ldapi_path, nt_errstr(status)));
1005         }
1006
1007 #endif
1008         return;
1009
1010 failed:
1011         task_server_terminate(task, "Failed to startup ldap server task", true);
1012 }
1013
1014
1015 NTSTATUS server_service_ldap_init(void)
1016 {
1017         return register_server_service("ldap", ldapsrv_task_init);
1018 }