s4-ldap_server Don't DEBUG() at level 2 every time a caller disconnects
[sfrench/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 "lib/ldb/include/ldb.h"
40 #include "lib/ldb/include/ldb_errors.h"
41 #include "libcli/ldap/ldap_proto.h"
42 #include "system/network.h"
43 #include "lib/socket/netif.h"
44 #include "dsdb/samdb/samdb.h"
45 #include "param/param.h"
46 #include "../lib/tsocket/tsocket.h"
47 #include "../lib/util/tevent_ntstatus.h"
48 #include "../libcli/util/tstream.h"
49
50 static void ldapsrv_terminate_connection_done(struct tevent_req *subreq);
51
52 /*
53   close the socket and shutdown a server_context
54 */
55 static void ldapsrv_terminate_connection(struct ldapsrv_connection *conn,
56                                          const char *reason)
57 {
58         struct tevent_req *subreq;
59
60         if (conn->limits.reason) {
61                 return;
62         }
63
64         conn->limits.endtime = timeval_current_ofs(0, 500);
65
66         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 ( ! ldb_dn_validate(basedn)) {
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 {
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
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) /* 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 = talloc_move(conn, &session_info);
334
335         if (!NT_STATUS_IS_OK(ldapsrv_backend_Init(conn))) {
336                 ldapsrv_terminate_connection(conn, "backend Init failed");
337                 return;
338         }
339
340         /* load limits from the conf partition */
341         ldapsrv_load_limits(conn); /* should we fail on error ? */
342
343         /* register the server */       
344         irpc_add_name(c->msg_ctx, "ldap_server");
345
346         conn->sockets.active = conn->sockets.raw;
347
348         if (port != 636) {
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_nomem(NULL, 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);
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);
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   add a socket address to the list of events, one event per port
802 */
803 static NTSTATUS add_socket(struct tevent_context *event_context,
804                            struct loadparm_context *lp_ctx,
805                            const struct model_ops *model_ops,
806                            const char *address, struct ldapsrv_service *ldap_service)
807 {
808         uint16_t port = 389;
809         NTSTATUS status;
810         struct ldb_context *ldb;
811
812         status = stream_setup_socket(event_context, lp_ctx,
813                                      model_ops, &ldap_stream_nonpriv_ops,
814                                      "ipv4", address, &port, 
815                                      lpcfg_socket_options(lp_ctx),
816                                      ldap_service);
817         if (!NT_STATUS_IS_OK(status)) {
818                 DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
819                          address, port, nt_errstr(status)));
820                 return status;
821         }
822
823         if (tstream_tls_params_enabled(ldap_service->tls_params)) {
824                 /* add ldaps server */
825                 port = 636;
826                 status = stream_setup_socket(event_context, lp_ctx,
827                                              model_ops,
828                                              &ldap_stream_nonpriv_ops,
829                                              "ipv4", address, &port, 
830                                              lpcfg_socket_options(lp_ctx),
831                                              ldap_service);
832                 if (!NT_STATUS_IS_OK(status)) {
833                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
834                                  address, port, nt_errstr(status)));
835                         return status;
836                 }
837         }
838
839         /* Load LDAP database, but only to read our settings */
840         ldb = samdb_connect(ldap_service, ldap_service->task->event_ctx, 
841                             lp_ctx, system_session(lp_ctx), 0);
842         if (!ldb) {
843                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
844         }
845
846         if (samdb_is_gc(ldb)) {
847                 port = 3268;
848                 status = stream_setup_socket(event_context, lp_ctx,
849                                              model_ops,
850                                              &ldap_stream_nonpriv_ops,
851                                              "ipv4", address, &port, 
852                                              lpcfg_socket_options(lp_ctx),
853                                              ldap_service);
854                 if (!NT_STATUS_IS_OK(status)) {
855                         DEBUG(0,("ldapsrv failed to bind to %s:%u - %s\n",
856                                  address, port, nt_errstr(status)));
857                         return status;
858                 }
859         }
860
861         /* And once we are bound, free the tempoary ldb, it will
862          * connect again on each incoming LDAP connection */
863         talloc_unlink(ldap_service, ldb);
864
865         return NT_STATUS_OK;
866 }
867
868 /*
869   open the ldap server sockets
870 */
871 static void ldapsrv_task_init(struct task_server *task)
872 {       
873         char *ldapi_path;
874 #ifdef WITH_LDAPI_PRIV_SOCKET
875         char *priv_dir;
876 #endif
877         const char *dns_host_name;
878         struct ldapsrv_service *ldap_service;
879         NTSTATUS status;
880         const struct model_ops *model_ops;
881
882         switch (lpcfg_server_role(task->lp_ctx)) {
883         case ROLE_STANDALONE:
884                 task_server_terminate(task, "ldap_server: no LDAP server required in standalone configuration", 
885                                       false);
886                 return;
887         case ROLE_DOMAIN_MEMBER:
888                 task_server_terminate(task, "ldap_server: no LDAP server required in member server configuration", 
889                                       false);
890                 return;
891         case ROLE_DOMAIN_CONTROLLER:
892                 /* Yes, we want an LDAP server */
893                 break;
894         }
895
896         task_server_set_title(task, "task[ldapsrv]");
897
898         /* run the ldap server as a single process */
899         model_ops = process_model_startup("single");
900         if (!model_ops) goto failed;
901
902         ldap_service = talloc_zero(task, struct ldapsrv_service);
903         if (ldap_service == NULL) goto failed;
904
905         ldap_service->task = task;
906
907         dns_host_name = talloc_asprintf(ldap_service, "%s.%s",
908                                         lpcfg_netbios_name(task->lp_ctx),
909                                         lpcfg_dnsdomain(task->lp_ctx));
910         if (dns_host_name == NULL) goto failed;
911
912         status = tstream_tls_params_server(ldap_service,
913                                            dns_host_name,
914                                            lpcfg_tls_enabled(task->lp_ctx),
915                                            lpcfg_tls_keyfile(ldap_service, task->lp_ctx),
916                                            lpcfg_tls_certfile(ldap_service, task->lp_ctx),
917                                            lpcfg_tls_cafile(ldap_service, task->lp_ctx),
918                                            lpcfg_tls_crlfile(ldap_service, task->lp_ctx),
919                                            lpcfg_tls_dhpfile(ldap_service, task->lp_ctx),
920                                            &ldap_service->tls_params);
921         if (!NT_STATUS_IS_OK(status)) {
922                 DEBUG(0,("ldapsrv failed tstream_tls_patams_server - %s\n",
923                          nt_errstr(status)));
924                 goto failed;
925         }
926
927         ldap_service->call_queue = tevent_queue_create(ldap_service, "ldapsrv_call_queue");
928         if (ldap_service->call_queue == NULL) goto failed;
929
930         if (lpcfg_interfaces(task->lp_ctx) && lpcfg_bind_interfaces_only(task->lp_ctx)) {
931                 struct interface *ifaces;
932                 int num_interfaces;
933                 int i;
934
935                 load_interfaces(task, lpcfg_interfaces(task->lp_ctx), &ifaces);
936                 num_interfaces = iface_count(ifaces);
937
938                 /* We have been given an interfaces line, and been 
939                    told to only bind to those interfaces. Create a
940                    socket per interface and bind to only these.
941                 */
942                 for(i = 0; i < num_interfaces; i++) {
943                         const char *address = iface_n_ip(ifaces, i);
944                         status = add_socket(task->event_ctx, task->lp_ctx, model_ops, address, ldap_service);
945                         if (!NT_STATUS_IS_OK(status)) goto failed;
946                 }
947         } else {
948                 status = add_socket(task->event_ctx, task->lp_ctx, model_ops,
949                                     lpcfg_socket_address(task->lp_ctx), ldap_service);
950                 if (!NT_STATUS_IS_OK(status)) goto failed;
951         }
952
953         ldapi_path = private_path(ldap_service, task->lp_ctx, "ldapi");
954         if (!ldapi_path) {
955                 goto failed;
956         }
957
958         status = stream_setup_socket(task->event_ctx, task->lp_ctx,
959                                      model_ops, &ldap_stream_nonpriv_ops,
960                                      "unix", ldapi_path, NULL, 
961                                      lpcfg_socket_options(task->lp_ctx),
962                                      ldap_service);
963         talloc_free(ldapi_path);
964         if (!NT_STATUS_IS_OK(status)) {
965                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
966                          ldapi_path, nt_errstr(status)));
967         }
968
969 #ifdef WITH_LDAPI_PRIV_SOCKET
970         priv_dir = private_path(ldap_service, task->lp_ctx, "ldap_priv");
971         if (priv_dir == NULL) {
972                 goto failed;
973         }
974         /*
975          * Make sure the directory for the privileged ldapi socket exists, and
976          * is of the correct permissions
977          */
978         if (!directory_create_or_exist(priv_dir, geteuid(), 0750)) {
979                 task_server_terminate(task, "Cannot create ldap "
980                                       "privileged ldapi directory", true);
981                 return;
982         }
983         ldapi_path = talloc_asprintf(ldap_service, "%s/ldapi", priv_dir);
984         talloc_free(priv_dir);
985         if (ldapi_path == NULL) {
986                 goto failed;
987         }
988
989         status = stream_setup_socket(task->event_ctx, task->lp_ctx,
990                                      model_ops, &ldap_stream_priv_ops,
991                                      "unix", ldapi_path, NULL,
992                                      lpcfg_socket_options(task->lp_ctx),
993                                      ldap_service);
994         talloc_free(ldapi_path);
995         if (!NT_STATUS_IS_OK(status)) {
996                 DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
997                          ldapi_path, nt_errstr(status)));
998         }
999
1000 #endif
1001         return;
1002
1003 failed:
1004         task_server_terminate(task, "Failed to startup ldap server task", true);
1005 }
1006
1007
1008 NTSTATUS server_service_ldap_init(void)
1009 {
1010         return register_server_service("ldap", ldapsrv_task_init);
1011 }