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