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