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