samdb: Add flags argument to samdb_connect().
[bbaumbach/samba-autobuild/.git] / source4 / ldap_server / ldap_backend.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP server
4    Copyright (C) Stefan Metzmacher 2004
5    Copyright (C) Matthias Dieter Wallnöfer 2009
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "ldap_server/ldap_server.h"
23 #include "../lib/util/dlinklist.h"
24 #include "auth/credentials/credentials.h"
25 #include "auth/gensec/gensec.h"
26 #include "param/param.h"
27 #include "smbd/service_stream.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "lib/ldb/include/ldb_errors.h"
30 #include "ldb_wrap.h"
31
32 #define VALID_DN_SYNTAX(dn) do {\
33         if (!(dn)) {\
34                 return NT_STATUS_NO_MEMORY;\
35         } else if ( ! ldb_dn_validate(dn)) {\
36                 result = LDAP_INVALID_DN_SYNTAX;\
37                 map_ldb_error(local_ctx, LDB_ERR_INVALID_DN_SYNTAX, NULL,\
38                               &errstr);\
39                 goto reply;\
40         }\
41 } while(0)
42
43 static int map_ldb_error(TALLOC_CTX *mem_ctx, int ldb_err,
44         const char *add_err_string, const char **errstring)
45 {
46         WERROR err;
47
48         /* Certain LDB modules need to return very special WERROR codes. Proof
49          * for them here and if they exist skip the rest of the mapping. */
50         if (add_err_string != NULL) {
51                 char *endptr;
52                 strtol(add_err_string, &endptr, 16);
53                 if (endptr != add_err_string) {
54                         *errstring = add_err_string;
55                         return ldb_err;
56                 }
57         }
58
59         /* Otherwise we calculate here a generic, but appropriate WERROR. */
60
61         switch (ldb_err) {
62         case LDB_SUCCESS:
63                 err = WERR_OK;
64         break;
65         case LDB_ERR_OPERATIONS_ERROR:
66                 err = WERR_DS_OPERATIONS_ERROR;
67         break;
68         case LDB_ERR_PROTOCOL_ERROR:
69                 err = WERR_DS_PROTOCOL_ERROR;
70         break;
71         case LDB_ERR_TIME_LIMIT_EXCEEDED:
72                 err = WERR_DS_TIMELIMIT_EXCEEDED;
73         break;
74         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
75                 err = WERR_DS_SIZELIMIT_EXCEEDED;
76         break;
77         case LDB_ERR_COMPARE_FALSE:
78                 err = WERR_DS_COMPARE_FALSE;
79         break;
80         case LDB_ERR_COMPARE_TRUE:
81                 err = WERR_DS_COMPARE_TRUE;
82         break;
83         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
84                 err = WERR_DS_AUTH_METHOD_NOT_SUPPORTED;
85         break;
86         case LDB_ERR_STRONG_AUTH_REQUIRED:
87                 err = WERR_DS_STRONG_AUTH_REQUIRED;
88         break;
89         case LDB_ERR_REFERRAL:
90                 err = WERR_DS_REFERRAL;
91         break;
92         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
93                 err = WERR_DS_ADMIN_LIMIT_EXCEEDED;
94         break;
95         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
96                 err = WERR_DS_UNAVAILABLE_CRIT_EXTENSION;
97         break;
98         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
99                 err = WERR_DS_CONFIDENTIALITY_REQUIRED;
100         break;
101         case LDB_ERR_SASL_BIND_IN_PROGRESS:
102                 err = WERR_DS_BUSY;
103         break;
104         case LDB_ERR_NO_SUCH_ATTRIBUTE:
105                 err = WERR_DS_NO_ATTRIBUTE_OR_VALUE;
106         break;
107         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
108                 err = WERR_DS_ATTRIBUTE_TYPE_UNDEFINED;
109         break;
110         case LDB_ERR_INAPPROPRIATE_MATCHING:
111                 err = WERR_DS_INAPPROPRIATE_MATCHING;
112         break;
113         case LDB_ERR_CONSTRAINT_VIOLATION:
114                 err = WERR_DS_CONSTRAINT_VIOLATION;
115         break;
116         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
117                 err = WERR_DS_ATTRIBUTE_OR_VALUE_EXISTS;
118         break;
119         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
120                 err = WERR_DS_INVALID_ATTRIBUTE_SYNTAX;
121         break;
122         case LDB_ERR_NO_SUCH_OBJECT:
123                 err = WERR_DS_NO_SUCH_OBJECT;
124         break;
125         case LDB_ERR_ALIAS_PROBLEM:
126                 err = WERR_DS_ALIAS_PROBLEM;
127         break;
128         case LDB_ERR_INVALID_DN_SYNTAX:
129                 err = WERR_DS_INVALID_DN_SYNTAX;
130         break;
131         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
132                 err = WERR_DS_ALIAS_DEREF_PROBLEM;
133         break;
134         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
135                 err = WERR_DS_INAPPROPRIATE_AUTH;
136         break;
137         case LDB_ERR_INVALID_CREDENTIALS:
138                 err = WERR_ACCESS_DENIED;
139         break;
140         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
141                 err = WERR_DS_INSUFF_ACCESS_RIGHTS;
142         break;
143         case LDB_ERR_BUSY:
144                 err = WERR_DS_BUSY;
145         break;
146         case LDB_ERR_UNAVAILABLE:
147                 err = WERR_DS_UNAVAILABLE;
148         break;
149         case LDB_ERR_UNWILLING_TO_PERFORM:
150                 err = WERR_DS_UNWILLING_TO_PERFORM;
151         break;
152         case LDB_ERR_LOOP_DETECT:
153                 err = WERR_DS_LOOP_DETECT;
154         break;
155         case LDB_ERR_NAMING_VIOLATION:
156                 err = WERR_DS_NAMING_VIOLATION;
157         break;
158         case LDB_ERR_OBJECT_CLASS_VIOLATION:
159                 err = WERR_DS_OBJ_CLASS_VIOLATION;
160         break;
161         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
162                 err = WERR_DS_CANT_ON_NON_LEAF;
163         break;
164         case LDB_ERR_NOT_ALLOWED_ON_RDN:
165                 err = WERR_DS_CANT_ON_RDN;
166         break;
167         case LDB_ERR_ENTRY_ALREADY_EXISTS:
168                 err = WERR_DS_OBJ_STRING_NAME_EXISTS;
169         break;
170         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
171                 err = WERR_DS_CANT_MOD_OBJ_CLASS;
172         break;
173         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
174                 err = WERR_DS_AFFECTS_MULTIPLE_DSAS;
175         break;
176         default:
177                 err = WERR_DS_GENERIC_ERROR;
178         break;
179         }
180
181         *errstring = talloc_asprintf(mem_ctx, "%08X: %s", W_ERROR_V(err),
182                 ldb_strerror(ldb_err));
183         if (add_err_string != NULL) {
184                 *errstring = talloc_asprintf(mem_ctx, "%s - %s", *errstring,
185                                              add_err_string);
186         }
187         
188         /* result is 1:1 for now */
189         return ldb_err;
190 }
191
192 /*
193   connect to the sam database
194 */
195 NTSTATUS ldapsrv_backend_Init(struct ldapsrv_connection *conn) 
196 {
197         conn->ldb = samdb_connect(conn, 
198                                      conn->connection->event.ctx,
199                                      conn->lp_ctx,
200                                      conn->session_info,
201                                      conn->global_catalog ? LDB_FLG_RDONLY : 0);
202         if (conn->ldb == NULL) {
203                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
204         }
205
206         if (conn->server_credentials) {
207                 char **sasl_mechs = NULL;
208                 struct gensec_security_ops **backends = gensec_security_all();
209                 struct gensec_security_ops **ops
210                         = gensec_use_kerberos_mechs(conn, backends, conn->server_credentials);
211                 unsigned int i, j = 0;
212                 for (i = 0; ops && ops[i]; i++) {
213                         if (!lpcfg_parm_bool(conn->lp_ctx,  NULL, "gensec", ops[i]->name, ops[i]->enabled))
214                                 continue;
215
216                         if (ops[i]->sasl_name && ops[i]->server_start) {
217                                 char *sasl_name = talloc_strdup(conn, ops[i]->sasl_name);
218
219                                 if (!sasl_name) {
220                                         return NT_STATUS_NO_MEMORY;
221                                 }
222                                 sasl_mechs = talloc_realloc(conn, sasl_mechs, char *, j + 2);
223                                 if (!sasl_mechs) {
224                                         return NT_STATUS_NO_MEMORY;
225                                 }
226                                 sasl_mechs[j] = sasl_name;
227                                 talloc_steal(sasl_mechs, sasl_name);
228                                 sasl_mechs[j+1] = NULL;
229                                 j++;
230                         }
231                 }
232                 talloc_unlink(conn, ops);
233
234                 /* ldb can have a different lifetime to conn, so we
235                    need to ensure that sasl_mechs lives as long as the
236                    ldb does */
237                 talloc_steal(conn->ldb, sasl_mechs);
238
239                 ldb_set_opaque(conn->ldb, "supportedSASLMechanisms", sasl_mechs);
240         }
241
242         return NT_STATUS_OK;
243 }
244
245 struct ldapsrv_reply *ldapsrv_init_reply(struct ldapsrv_call *call, uint8_t type)
246 {
247         struct ldapsrv_reply *reply;
248
249         reply = talloc(call, struct ldapsrv_reply);
250         if (!reply) {
251                 return NULL;
252         }
253         reply->msg = talloc(reply, struct ldap_message);
254         if (reply->msg == NULL) {
255                 talloc_free(reply);
256                 return NULL;
257         }
258
259         reply->msg->messageid = call->request->messageid;
260         reply->msg->type = type;
261         reply->msg->controls = NULL;
262
263         return reply;
264 }
265
266 void ldapsrv_queue_reply(struct ldapsrv_call *call, struct ldapsrv_reply *reply)
267 {
268         DLIST_ADD_END(call->replies, reply, struct ldapsrv_reply *);
269 }
270
271 static NTSTATUS ldapsrv_unwilling(struct ldapsrv_call *call, int error)
272 {
273         struct ldapsrv_reply *reply;
274         struct ldap_ExtendedResponse *r;
275
276         DEBUG(10,("Unwilling type[%d] id[%d]\n", call->request->type, call->request->messageid));
277
278         reply = ldapsrv_init_reply(call, LDAP_TAG_ExtendedResponse);
279         if (!reply) {
280                 return NT_STATUS_NO_MEMORY;
281         }
282
283         r = &reply->msg->r.ExtendedResponse;
284         r->response.resultcode = error;
285         r->response.dn = NULL;
286         r->response.errormessage = NULL;
287         r->response.referral = NULL;
288         r->oid = NULL;
289         r->value = NULL;
290
291         ldapsrv_queue_reply(call, reply);
292         return NT_STATUS_OK;
293 }
294
295 static int ldb_add_with_controls(struct ldb_context *ldb,
296                                  const struct ldb_message *message,
297                                  struct ldb_control **controls,
298                                  void *context)
299 {
300         struct ldb_request *req;
301         int ret;
302
303         ret = ldb_msg_sanity_check(ldb, message);
304         if (ret != LDB_SUCCESS) {
305                 return ret;
306         }
307
308         ret = ldb_build_add_req(&req, ldb, ldb,
309                                         message,
310                                         controls,
311                                         context,
312                                         ldb_modify_default_callback,
313                                         NULL);
314
315         if (ret != LDB_SUCCESS) return ret;
316
317         ret = ldb_transaction_start(ldb);
318         if (ret != LDB_SUCCESS) {
319                 return ret;
320         }
321
322         ret = ldb_request(ldb, req);
323         if (ret == LDB_SUCCESS) {
324                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
325         }
326
327         if (ret == LDB_SUCCESS) {
328                 ret = ldb_transaction_commit(ldb);
329         }
330         else {
331                 ldb_transaction_cancel(ldb);
332         }
333
334         talloc_free(req);
335         return ret;
336 }
337
338 /* create and execute a modify request */
339 static int ldb_mod_req_with_controls(struct ldb_context *ldb,
340                                      const struct ldb_message *message,
341                                      struct ldb_control **controls,
342                                      void *context)
343 {
344         struct ldb_request *req;
345         int ret;
346
347         ret = ldb_msg_sanity_check(ldb, message);
348         if (ret != LDB_SUCCESS) {
349                 return ret;
350         }
351
352         ret = ldb_build_mod_req(&req, ldb, ldb,
353                                         message,
354                                         controls,
355                                         context,
356                                         ldb_modify_default_callback,
357                                         NULL);
358
359         if (ret != LDB_SUCCESS) {
360                 return ret;
361         }
362
363         ret = ldb_transaction_start(ldb);
364         if (ret != LDB_SUCCESS) {
365                 return ret;
366         }
367
368         ret = ldb_request(ldb, req);
369         if (ret == LDB_SUCCESS) {
370                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
371         }
372
373         if (ret == LDB_SUCCESS) {
374                 ret = ldb_transaction_commit(ldb);
375         }
376         else {
377                 ldb_transaction_cancel(ldb);
378         }
379
380         talloc_free(req);
381         return ret;
382 }
383
384 /* create and execute a delete request */
385 static int ldb_del_req_with_controls(struct ldb_context *ldb,
386                                      struct ldb_dn *dn,
387                                      struct ldb_control **controls,
388                                      void *context)
389 {
390         struct ldb_request *req;
391         int ret;
392
393         ret = ldb_build_del_req(&req, ldb, ldb,
394                                         dn,
395                                         controls,
396                                         context,
397                                         ldb_modify_default_callback,
398                                         NULL);
399
400         if (ret != LDB_SUCCESS) return ret;
401
402         ret = ldb_transaction_start(ldb);
403         if (ret != LDB_SUCCESS) {
404                 return ret;
405         }
406
407         ret = ldb_request(ldb, req);
408         if (ret == LDB_SUCCESS) {
409                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
410         }
411
412         if (ret == LDB_SUCCESS) {
413                 ret = ldb_transaction_commit(ldb);
414         }
415         else {
416                 ldb_transaction_cancel(ldb);
417         }
418
419         talloc_free(req);
420         return ret;
421 }
422
423 int ldb_rename_with_controls(struct ldb_context *ldb,
424                              struct ldb_dn *olddn,
425                              struct ldb_dn *newdn,
426                              struct ldb_control **controls,
427                              void *context)
428 {
429         struct ldb_request *req;
430         int ret;
431
432         ret = ldb_build_rename_req(&req, ldb, ldb,
433                                         olddn,
434                                         newdn,
435                                         NULL,
436                                         context,
437                                         ldb_modify_default_callback,
438                                         NULL);
439
440         if (ret != LDB_SUCCESS) return ret;
441
442         ret = ldb_transaction_start(ldb);
443         if (ret != LDB_SUCCESS) {
444                 return ret;
445         }
446
447         ret = ldb_request(ldb, req);
448         if (ret == LDB_SUCCESS) {
449                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
450         }
451
452         if (ret == LDB_SUCCESS) {
453                 ret = ldb_transaction_commit(ldb);
454         }
455         else {
456                 ldb_transaction_cancel(ldb);
457         }
458
459         talloc_free(req);
460         return ret;
461 }
462
463 static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call)
464 {
465         struct ldap_SearchRequest *req = &call->request->r.SearchRequest;
466         struct ldap_SearchResEntry *ent;
467         struct ldap_Result *done;
468         struct ldapsrv_reply *ent_r, *done_r;
469         TALLOC_CTX *local_ctx;
470         struct ldb_context *samdb = talloc_get_type(call->conn->ldb, struct ldb_context);
471         struct ldb_dn *basedn;
472         struct ldb_result *res = NULL;
473         struct ldb_request *lreq;
474         struct ldb_control *search_control;
475         struct ldb_search_options_control *search_options;
476         struct ldb_control *extended_dn_control;
477         struct ldb_extended_dn_control *extended_dn_decoded = NULL;
478         enum ldb_scope scope = LDB_SCOPE_DEFAULT;
479         const char **attrs = NULL;
480         const char *scope_str, *errstr = NULL;
481         int success_limit = 1;
482         int result = -1;
483         int ldb_ret = -1;
484         unsigned int i, j;
485         int extended_type = 1;
486
487         DEBUG(10, ("SearchRequest"));
488         DEBUGADD(10, (" basedn: %s", req->basedn));
489         DEBUGADD(10, (" filter: %s\n", ldb_filter_from_tree(call, req->tree)));
490
491         local_ctx = talloc_new(call);
492         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
493
494         basedn = ldb_dn_new(local_ctx, samdb, req->basedn);
495         VALID_DN_SYNTAX(basedn);
496
497         DEBUG(10, ("SearchRequest: basedn: [%s]\n", req->basedn));
498         DEBUG(10, ("SearchRequest: filter: [%s]\n", ldb_filter_from_tree(call, req->tree)));
499
500         switch (req->scope) {
501                 case LDAP_SEARCH_SCOPE_BASE:
502                         scope_str = "BASE";
503                         scope = LDB_SCOPE_BASE;
504                         success_limit = 0;
505                         break;
506                 case LDAP_SEARCH_SCOPE_SINGLE:
507                         scope_str = "ONE";
508                         scope = LDB_SCOPE_ONELEVEL;
509                         success_limit = 0;
510                         break;
511                 case LDAP_SEARCH_SCOPE_SUB:
512                         scope_str = "SUB";
513                         scope = LDB_SCOPE_SUBTREE;
514                         success_limit = 0;
515                         break;
516                 default:
517                         result = LDAP_PROTOCOL_ERROR;
518                         map_ldb_error(local_ctx, LDB_ERR_PROTOCOL_ERROR, NULL,
519                                 &errstr);
520                         errstr = talloc_asprintf(local_ctx,
521                                 "%s. Invalid scope", errstr);
522                         goto reply;
523         }
524         DEBUG(10,("SearchRequest: scope: [%s]\n", scope_str));
525
526         if (req->num_attributes >= 1) {
527                 attrs = talloc_array(local_ctx, const char *, req->num_attributes+1);
528                 NT_STATUS_HAVE_NO_MEMORY(attrs);
529
530                 for (i=0; i < req->num_attributes; i++) {
531                         DEBUG(10,("SearchRequest: attrs: [%s]\n",req->attributes[i]));
532                         attrs[i] = req->attributes[i];
533                 }
534                 attrs[i] = NULL;
535         }
536
537         DEBUG(5,("ldb_request %s dn=%s filter=%s\n", 
538                  scope_str, req->basedn, ldb_filter_from_tree(call, req->tree)));
539
540         res = talloc_zero(local_ctx, struct ldb_result);
541         NT_STATUS_HAVE_NO_MEMORY(res);
542
543         ldb_ret = ldb_build_search_req_ex(&lreq, samdb, local_ctx,
544                                           basedn, scope,
545                                           req->tree, attrs,
546                                           call->request->controls,
547                                           res, ldb_search_default_callback,
548                                           NULL);
549
550         if (ldb_ret != LDB_SUCCESS) {
551                 goto reply;
552         }
553
554         if (call->conn->global_catalog) {
555                 search_control = ldb_request_get_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID);
556
557                 search_options = NULL;
558                 if (search_control) {
559                         search_options = talloc_get_type(search_control->data, struct ldb_search_options_control);
560                         search_options->search_options |= LDB_SEARCH_OPTION_PHANTOM_ROOT;
561                 } else {
562                         search_options = talloc(lreq, struct ldb_search_options_control);
563                         NT_STATUS_HAVE_NO_MEMORY(search_options);
564                         search_options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
565                         ldb_request_add_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID, false, search_options);
566                 }
567         }
568
569         extended_dn_control = ldb_request_get_control(lreq, LDB_CONTROL_EXTENDED_DN_OID);
570
571         if (extended_dn_control) {
572                 if (extended_dn_control->data) {
573                         extended_dn_decoded = talloc_get_type(extended_dn_control->data, struct ldb_extended_dn_control);
574                         extended_type = extended_dn_decoded->type;
575                 } else {
576                         extended_type = 0;
577                 }
578         }
579
580         ldb_request_add_control(lreq, DSDB_CONTROL_SEARCH_APPLY_ACCESS, false, NULL);
581         ldb_set_timeout(samdb, lreq, req->timelimit);
582
583         ldb_ret = ldb_request(samdb, lreq);
584
585         if (ldb_ret != LDB_SUCCESS) {
586                 goto reply;
587         }
588
589         ldb_ret = ldb_wait(lreq->handle, LDB_WAIT_ALL);
590
591         if (ldb_ret == LDB_SUCCESS) {
592                 for (i = 0; i < res->count; i++) {
593                         ent_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultEntry);
594                         NT_STATUS_HAVE_NO_MEMORY(ent_r);
595
596                         /* Better to have the whole message kept here,
597                          * than to find someone further up didn't put
598                          * a value in the right spot in the talloc tree */
599                         talloc_steal(ent_r, res->msgs[i]);
600                         
601                         ent = &ent_r->msg->r.SearchResultEntry;
602                         ent->dn = ldb_dn_get_extended_linearized(ent_r, res->msgs[i]->dn, extended_type);
603                         ent->num_attributes = 0;
604                         ent->attributes = NULL;
605                         if (res->msgs[i]->num_elements == 0) {
606                                 goto queue_reply;
607                         }
608                         ent->num_attributes = res->msgs[i]->num_elements;
609                         ent->attributes = talloc_array(ent_r, struct ldb_message_element, ent->num_attributes);
610                         NT_STATUS_HAVE_NO_MEMORY(ent->attributes);
611                         for (j=0; j < ent->num_attributes; j++) {
612                                 ent->attributes[j].name = res->msgs[i]->elements[j].name;
613                                 ent->attributes[j].num_values = 0;
614                                 ent->attributes[j].values = NULL;
615                                 if (req->attributesonly && (res->msgs[i]->elements[j].num_values == 0)) {
616                                         continue;
617                                 }
618                                 ent->attributes[j].num_values = res->msgs[i]->elements[j].num_values;
619                                 ent->attributes[j].values = res->msgs[i]->elements[j].values;
620                         }
621 queue_reply:
622                         ldapsrv_queue_reply(call, ent_r);
623                 }
624
625                 /* Send back referrals if they do exist (search operations) */
626                 if (res->refs != NULL) {
627                         char **ref;
628                         struct ldap_SearchResRef *ent_ref;
629
630                         for (ref = res->refs; *ref != NULL; ++ref) {
631                                 ent_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultReference);
632                                 NT_STATUS_HAVE_NO_MEMORY(ent_r);
633
634                                 /* Better to have the whole referrals kept here,
635                                  * than to find someone further up didn't put
636                                  * a value in the right spot in the talloc tree
637                                  */
638                                 talloc_steal(ent_r, *ref);
639
640                                 ent_ref = &ent_r->msg->r.SearchResultReference;
641                                 ent_ref->referral = *ref;
642
643                                 ldapsrv_queue_reply(call, ent_r);
644                         }
645                 }
646         }
647
648 reply:
649         done_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultDone);
650         NT_STATUS_HAVE_NO_MEMORY(done_r);
651
652         done = &done_r->msg->r.SearchResultDone;
653         done->dn = NULL;
654         done->referral = NULL;
655
656         if (result != -1) {
657         } else if (ldb_ret == LDB_SUCCESS) {
658                 if (res->count >= success_limit) {
659                         DEBUG(10,("SearchRequest: results: [%d]\n", res->count));
660                         result = LDAP_SUCCESS;
661                         errstr = NULL;
662                 }
663                 if (res->controls) {
664                         done_r->msg->controls = res->controls;
665                         talloc_steal(done_r, res->controls);
666                 }
667         } else {
668                 DEBUG(10,("SearchRequest: error\n"));
669                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
670                                        &errstr);
671         }
672
673         done->resultcode = result;
674         done->errormessage = (errstr?talloc_strdup(done_r, errstr):NULL);
675
676         talloc_free(local_ctx);
677
678         ldapsrv_queue_reply(call, done_r);
679         return NT_STATUS_OK;
680 }
681
682 static NTSTATUS ldapsrv_ModifyRequest(struct ldapsrv_call *call)
683 {
684         struct ldap_ModifyRequest *req = &call->request->r.ModifyRequest;
685         struct ldap_Result *modify_result;
686         struct ldapsrv_reply *modify_reply;
687         TALLOC_CTX *local_ctx;
688         struct ldb_context *samdb = call->conn->ldb;
689         struct ldb_message *msg = NULL;
690         struct ldb_dn *dn;
691         const char *errstr = NULL;
692         int result = LDAP_SUCCESS;
693         int ldb_ret;
694         unsigned int i,j;
695         struct ldb_result *res = NULL;
696
697         DEBUG(10, ("ModifyRequest"));
698         DEBUGADD(10, (" dn: %s\n", req->dn));
699
700         local_ctx = talloc_named(call, 0, "ModifyRequest local memory context");
701         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
702
703         dn = ldb_dn_new(local_ctx, samdb, req->dn);
704         VALID_DN_SYNTAX(dn);
705
706         DEBUG(10, ("ModifyRequest: dn: [%s]\n", req->dn));
707
708         msg = talloc(local_ctx, struct ldb_message);
709         NT_STATUS_HAVE_NO_MEMORY(msg);
710
711         msg->dn = dn;
712         msg->num_elements = 0;
713         msg->elements = NULL;
714
715         if (req->num_mods > 0) {
716                 msg->num_elements = req->num_mods;
717                 msg->elements = talloc_array(msg, struct ldb_message_element, req->num_mods);
718                 NT_STATUS_HAVE_NO_MEMORY(msg->elements);
719
720                 for (i=0; i < msg->num_elements; i++) {
721                         msg->elements[i].name = discard_const_p(char, req->mods[i].attrib.name);
722                         msg->elements[i].num_values = 0;
723                         msg->elements[i].values = NULL;
724
725                         switch (req->mods[i].type) {
726                         default:
727                                 result = LDAP_PROTOCOL_ERROR;
728                                 map_ldb_error(local_ctx,
729                                         LDB_ERR_PROTOCOL_ERROR, NULL, &errstr);
730                                 errstr = talloc_asprintf(local_ctx,
731                                         "%s. Invalid LDAP_MODIFY_* type", errstr);
732                                 goto reply;
733                         case LDAP_MODIFY_ADD:
734                                 msg->elements[i].flags = LDB_FLAG_MOD_ADD;
735                                 break;
736                         case LDAP_MODIFY_DELETE:
737                                 msg->elements[i].flags = LDB_FLAG_MOD_DELETE;
738                                 break;
739                         case LDAP_MODIFY_REPLACE:
740                                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
741                                 break;
742                         }
743
744                         msg->elements[i].num_values = req->mods[i].attrib.num_values;
745                         if (msg->elements[i].num_values > 0) {
746                                 msg->elements[i].values = talloc_array(msg->elements, struct ldb_val,
747                                                                        msg->elements[i].num_values);
748                                 NT_STATUS_HAVE_NO_MEMORY(msg->elements[i].values);
749
750                                 for (j=0; j < msg->elements[i].num_values; j++) {
751                                         msg->elements[i].values[j].length = req->mods[i].attrib.values[j].length;
752                                         msg->elements[i].values[j].data = req->mods[i].attrib.values[j].data;                   
753                                 }
754                         }
755                 }
756         }
757
758 reply:
759         modify_reply = ldapsrv_init_reply(call, LDAP_TAG_ModifyResponse);
760         NT_STATUS_HAVE_NO_MEMORY(modify_reply);
761
762         if (result == LDAP_SUCCESS) {
763                 res = talloc_zero(local_ctx, struct ldb_result);
764                 NT_STATUS_HAVE_NO_MEMORY(res);
765                 ldb_ret = ldb_mod_req_with_controls(samdb, msg, call->request->controls, res);
766                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
767                                        &errstr);
768         }
769
770         modify_result = &modify_reply->msg->r.ModifyResponse;
771         modify_result->dn = NULL;
772         if ((res != NULL) && (res->refs != NULL)) {
773                 modify_result->resultcode = map_ldb_error(local_ctx,
774                                                           LDB_ERR_REFERRAL,
775                                                           NULL, &errstr);
776                 modify_result->errormessage = (errstr?talloc_strdup(modify_reply, errstr):NULL);
777                 modify_result->referral = talloc_strdup(call, *res->refs);
778         } else {
779                 modify_result->resultcode = result;
780                 modify_result->errormessage = (errstr?talloc_strdup(modify_reply, errstr):NULL);
781                 modify_result->referral = NULL;
782         }
783         talloc_free(local_ctx);
784
785         ldapsrv_queue_reply(call, modify_reply);
786         return NT_STATUS_OK;
787
788 }
789
790 static NTSTATUS ldapsrv_AddRequest(struct ldapsrv_call *call)
791 {
792         struct ldap_AddRequest *req = &call->request->r.AddRequest;
793         struct ldap_Result *add_result;
794         struct ldapsrv_reply *add_reply;
795         TALLOC_CTX *local_ctx;
796         struct ldb_context *samdb = call->conn->ldb;
797         struct ldb_message *msg = NULL;
798         struct ldb_dn *dn;
799         const char *errstr = NULL;
800         int result = LDAP_SUCCESS;
801         int ldb_ret;
802         unsigned int i,j;
803         struct ldb_result *res = NULL;
804
805         DEBUG(10, ("AddRequest"));
806         DEBUGADD(10, (" dn: %s\n", req->dn));
807
808         local_ctx = talloc_named(call, 0, "AddRequest local memory context");
809         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
810
811         dn = ldb_dn_new(local_ctx, samdb, req->dn);
812         VALID_DN_SYNTAX(dn);
813
814         DEBUG(10, ("AddRequest: dn: [%s]\n", req->dn));
815
816         msg = talloc(local_ctx, struct ldb_message);
817         NT_STATUS_HAVE_NO_MEMORY(msg);
818
819         msg->dn = dn;
820         msg->num_elements = 0;
821         msg->elements = NULL;
822
823         if (req->num_attributes > 0) {
824                 msg->num_elements = req->num_attributes;
825                 msg->elements = talloc_array(msg, struct ldb_message_element, msg->num_elements);
826                 NT_STATUS_HAVE_NO_MEMORY(msg->elements);
827
828                 for (i=0; i < msg->num_elements; i++) {
829                         msg->elements[i].name = discard_const_p(char, req->attributes[i].name);
830                         msg->elements[i].flags = 0;
831                         msg->elements[i].num_values = 0;
832                         msg->elements[i].values = NULL;
833                         
834                         if (req->attributes[i].num_values > 0) {
835                                 msg->elements[i].num_values = req->attributes[i].num_values;
836                                 msg->elements[i].values = talloc_array(msg->elements, struct ldb_val,
837                                                                        msg->elements[i].num_values);
838                                 NT_STATUS_HAVE_NO_MEMORY(msg->elements[i].values);
839
840                                 for (j=0; j < msg->elements[i].num_values; j++) {
841                                         msg->elements[i].values[j].length = req->attributes[i].values[j].length;
842                                         msg->elements[i].values[j].data = req->attributes[i].values[j].data;                    
843                                 }
844                         }
845                 }
846         }
847
848 reply:
849         add_reply = ldapsrv_init_reply(call, LDAP_TAG_AddResponse);
850         NT_STATUS_HAVE_NO_MEMORY(add_reply);
851
852         if (result == LDAP_SUCCESS) {
853                 res = talloc_zero(local_ctx, struct ldb_result);
854                 NT_STATUS_HAVE_NO_MEMORY(res);
855                 ldb_ret = ldb_add_with_controls(samdb, msg, call->request->controls, res);
856                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
857                                        &errstr);
858         }
859
860         add_result = &add_reply->msg->r.AddResponse;
861         add_result->dn = NULL;
862         if ((res != NULL) && (res->refs != NULL)) {
863                 add_result->resultcode =  map_ldb_error(local_ctx,
864                                                         LDB_ERR_REFERRAL, NULL,
865                                                         &errstr);
866                 add_result->errormessage = (errstr?talloc_strdup(add_reply,errstr):NULL);
867                 add_result->referral = talloc_strdup(call, *res->refs);
868         } else {
869                 add_result->resultcode = result;
870                 add_result->errormessage = (errstr?talloc_strdup(add_reply,errstr):NULL);
871                 add_result->referral = NULL;
872         }
873         talloc_free(local_ctx);
874
875         ldapsrv_queue_reply(call, add_reply);
876         return NT_STATUS_OK;
877
878 }
879
880 static NTSTATUS ldapsrv_DelRequest(struct ldapsrv_call *call)
881 {
882         struct ldap_DelRequest *req = &call->request->r.DelRequest;
883         struct ldap_Result *del_result;
884         struct ldapsrv_reply *del_reply;
885         TALLOC_CTX *local_ctx;
886         struct ldb_context *samdb = call->conn->ldb;
887         struct ldb_dn *dn;
888         const char *errstr = NULL;
889         int result = LDAP_SUCCESS;
890         int ldb_ret;
891         struct ldb_result *res = NULL;
892
893         DEBUG(10, ("DelRequest"));
894         DEBUGADD(10, (" dn: %s\n", req->dn));
895
896         local_ctx = talloc_named(call, 0, "DelRequest local memory context");
897         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
898
899         dn = ldb_dn_new(local_ctx, samdb, req->dn);
900         VALID_DN_SYNTAX(dn);
901
902         DEBUG(10, ("DelRequest: dn: [%s]\n", req->dn));
903
904 reply:
905         del_reply = ldapsrv_init_reply(call, LDAP_TAG_DelResponse);
906         NT_STATUS_HAVE_NO_MEMORY(del_reply);
907
908         if (result == LDAP_SUCCESS) {
909                 res = talloc_zero(local_ctx, struct ldb_result);
910                 NT_STATUS_HAVE_NO_MEMORY(res);
911                 ldb_ret = ldb_del_req_with_controls(samdb, dn, call->request->controls, res);
912                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
913                                        &errstr);
914         }
915
916         del_result = &del_reply->msg->r.DelResponse;
917         del_result->dn = NULL;
918         if ((res != NULL) && (res->refs != NULL)) {
919                 del_result->resultcode = map_ldb_error(local_ctx,
920                                                        LDB_ERR_REFERRAL, NULL,
921                                                        &errstr);
922                 del_result->errormessage = (errstr?talloc_strdup(del_reply,errstr):NULL);
923                 del_result->referral = talloc_strdup(call, *res->refs);
924         } else {
925                 del_result->resultcode = result;
926                 del_result->errormessage = (errstr?talloc_strdup(del_reply,errstr):NULL);
927                 del_result->referral = NULL;
928         }
929
930         talloc_free(local_ctx);
931
932         ldapsrv_queue_reply(call, del_reply);
933         return NT_STATUS_OK;
934 }
935
936 static NTSTATUS ldapsrv_ModifyDNRequest(struct ldapsrv_call *call)
937 {
938         struct ldap_ModifyDNRequest *req = &call->request->r.ModifyDNRequest;
939         struct ldap_Result *modifydn;
940         struct ldapsrv_reply *modifydn_r;
941         TALLOC_CTX *local_ctx;
942         struct ldb_context *samdb = call->conn->ldb;
943         struct ldb_dn *olddn, *newdn=NULL, *newrdn;
944         struct ldb_dn *parentdn = NULL;
945         const char *errstr = NULL;
946         int result = LDAP_SUCCESS;
947         int ldb_ret;
948         struct ldb_result *res = NULL;
949
950         DEBUG(10, ("ModifyDNRequest"));
951         DEBUGADD(10, (" dn: %s", req->dn));
952         DEBUGADD(10, (" newrdn: %s\n", req->newrdn));
953
954         local_ctx = talloc_named(call, 0, "ModifyDNRequest local memory context");
955         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
956
957         olddn = ldb_dn_new(local_ctx, samdb, req->dn);
958         VALID_DN_SYNTAX(olddn);
959
960         newrdn = ldb_dn_new(local_ctx, samdb, req->newrdn);
961         VALID_DN_SYNTAX(newrdn);
962
963         DEBUG(10, ("ModifyDNRequest: olddn: [%s]\n", req->dn));
964         DEBUG(10, ("ModifyDNRequest: newrdn: [%s]\n", req->newrdn));
965
966         if (ldb_dn_get_comp_num(newrdn) == 0) {
967                 result = LDAP_PROTOCOL_ERROR;
968                 map_ldb_error(local_ctx, LDB_ERR_PROTOCOL_ERROR, NULL,
969                               &errstr);
970                 goto reply;
971         }
972
973         if (ldb_dn_get_comp_num(newrdn) > 1) {
974                 result = LDAP_NAMING_VIOLATION;
975                 map_ldb_error(local_ctx, LDB_ERR_NAMING_VIOLATION, NULL,
976                               &errstr);
977                 goto reply;
978         }
979
980         /* we can't handle the rename if we should not remove the old dn */
981         if (!req->deleteolddn) {
982                 result = LDAP_UNWILLING_TO_PERFORM;
983                 map_ldb_error(local_ctx, LDB_ERR_UNWILLING_TO_PERFORM, NULL,
984                               &errstr);
985                 errstr = talloc_asprintf(local_ctx,
986                         "%s. Old RDN must be deleted", errstr);
987                 goto reply;
988         }
989
990         if (req->newsuperior) {
991                 parentdn = ldb_dn_new(local_ctx, samdb, req->newsuperior);
992                 VALID_DN_SYNTAX(parentdn);
993                 DEBUG(10, ("ModifyDNRequest: newsuperior: [%s]\n", req->newsuperior));
994         }
995
996         if (!parentdn) {
997                 parentdn = ldb_dn_get_parent(local_ctx, olddn);
998         }
999         if (!parentdn) {
1000                 result = LDAP_NO_SUCH_OBJECT;
1001                 map_ldb_error(local_ctx, LDB_ERR_NO_SUCH_OBJECT, NULL, &errstr);
1002                 goto reply;
1003         }
1004
1005         if ( ! ldb_dn_add_child(parentdn, newrdn)) {
1006                 result = LDAP_OTHER;
1007                 map_ldb_error(local_ctx, LDB_ERR_OTHER, NULL, &errstr);
1008                 goto reply;
1009         }
1010         newdn = parentdn;
1011
1012 reply:
1013         modifydn_r = ldapsrv_init_reply(call, LDAP_TAG_ModifyDNResponse);
1014         NT_STATUS_HAVE_NO_MEMORY(modifydn_r);
1015
1016         if (result == LDAP_SUCCESS) {
1017                 res = talloc_zero(local_ctx, struct ldb_result);
1018                 NT_STATUS_HAVE_NO_MEMORY(res);
1019                 ldb_ret = ldb_rename_with_controls(samdb, olddn, newdn, call->request->controls, res);
1020                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
1021                                        &errstr);
1022         }
1023
1024         modifydn = &modifydn_r->msg->r.ModifyDNResponse;
1025         modifydn->dn = NULL;
1026         if ((res != NULL) && (res->refs != NULL)) {
1027                 modifydn->resultcode = map_ldb_error(local_ctx,
1028                                                      LDB_ERR_REFERRAL, NULL,
1029                                                      &errstr);;
1030                 modifydn->errormessage = (errstr?talloc_strdup(modifydn_r,errstr):NULL);
1031                 modifydn->referral = talloc_strdup(call, *res->refs);
1032         } else {
1033                 modifydn->resultcode = result;
1034                 modifydn->errormessage = (errstr?talloc_strdup(modifydn_r,errstr):NULL);
1035                 modifydn->referral = NULL;
1036         }
1037
1038         talloc_free(local_ctx);
1039
1040         ldapsrv_queue_reply(call, modifydn_r);
1041         return NT_STATUS_OK;
1042 }
1043
1044 static NTSTATUS ldapsrv_CompareRequest(struct ldapsrv_call *call)
1045 {
1046         struct ldap_CompareRequest *req = &call->request->r.CompareRequest;
1047         struct ldap_Result *compare;
1048         struct ldapsrv_reply *compare_r;
1049         TALLOC_CTX *local_ctx;
1050         struct ldb_context *samdb = call->conn->ldb;
1051         struct ldb_result *res = NULL;
1052         struct ldb_dn *dn;
1053         const char *attrs[1];
1054         const char *errstr = NULL;
1055         const char *filter = NULL;
1056         int result = LDAP_SUCCESS;
1057         int ldb_ret;
1058
1059         DEBUG(10, ("CompareRequest"));
1060         DEBUGADD(10, (" dn: %s\n", req->dn));
1061
1062         local_ctx = talloc_named(call, 0, "CompareRequest local_memory_context");
1063         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
1064
1065         dn = ldb_dn_new(local_ctx, samdb, req->dn);
1066         VALID_DN_SYNTAX(dn);
1067
1068         DEBUG(10, ("CompareRequest: dn: [%s]\n", req->dn));
1069         filter = talloc_asprintf(local_ctx, "(%s=%*s)", req->attribute, 
1070                                  (int)req->value.length, req->value.data);
1071         NT_STATUS_HAVE_NO_MEMORY(filter);
1072
1073         DEBUGADD(10, ("CompareRequest: attribute: [%s]\n", filter));
1074
1075         attrs[0] = NULL;
1076
1077 reply:
1078         compare_r = ldapsrv_init_reply(call, LDAP_TAG_CompareResponse);
1079         NT_STATUS_HAVE_NO_MEMORY(compare_r);
1080
1081         if (result == LDAP_SUCCESS) {
1082                 ldb_ret = ldb_search(samdb, local_ctx, &res,
1083                                      dn, LDB_SCOPE_BASE, attrs, "%s", filter);
1084                 if (ldb_ret != LDB_SUCCESS) {
1085                         result = map_ldb_error(local_ctx, ldb_ret,
1086                                                ldb_errstring(samdb), &errstr);
1087                         DEBUG(10,("CompareRequest: error: %s\n", errstr));
1088                 } else if (res->count == 0) {
1089                         DEBUG(10,("CompareRequest: doesn't matched\n"));
1090                         result = LDAP_COMPARE_FALSE;
1091                         errstr = NULL;
1092                 } else if (res->count == 1) {
1093                         DEBUG(10,("CompareRequest: matched\n"));
1094                         result = LDAP_COMPARE_TRUE;
1095                         errstr = NULL;
1096                 } else if (res->count > 1) {
1097                         result = LDAP_OTHER;
1098                         map_ldb_error(local_ctx, LDB_ERR_OTHER, NULL, &errstr);
1099                         errstr = talloc_asprintf(local_ctx,
1100                                 "%s. Too many objects match!", errstr);
1101                         DEBUG(10,("CompareRequest: %d results: %s\n", res->count, errstr));
1102                 }
1103         }
1104
1105         compare = &compare_r->msg->r.CompareResponse;
1106         compare->dn = NULL;
1107         compare->resultcode = result;
1108         compare->errormessage = (errstr?talloc_strdup(compare_r,errstr):NULL);
1109         compare->referral = NULL;
1110
1111         talloc_free(local_ctx);
1112
1113         ldapsrv_queue_reply(call, compare_r);
1114         return NT_STATUS_OK;
1115 }
1116
1117 static NTSTATUS ldapsrv_AbandonRequest(struct ldapsrv_call *call)
1118 {
1119 /*      struct ldap_AbandonRequest *req = &call->request.r.AbandonRequest;*/
1120         DEBUG(10, ("AbandonRequest\n"));
1121         return NT_STATUS_OK;
1122 }
1123
1124 NTSTATUS ldapsrv_do_call(struct ldapsrv_call *call)
1125 {
1126         unsigned int i;
1127         struct ldap_message *msg = call->request;
1128         /* Check for undecoded critical extensions */
1129         for (i=0; msg->controls && msg->controls[i]; i++) {
1130                 if (!msg->controls_decoded[i] && 
1131                     msg->controls[i]->critical) {
1132                         DEBUG(3, ("ldapsrv_do_call: Critical extension %s is not known to this server\n",
1133                                   msg->controls[i]->oid));
1134                         return ldapsrv_unwilling(call, LDAP_UNAVAILABLE_CRITICAL_EXTENSION);
1135                 }
1136         }
1137
1138         switch(call->request->type) {
1139         case LDAP_TAG_BindRequest:
1140                 return ldapsrv_BindRequest(call);
1141         case LDAP_TAG_UnbindRequest:
1142                 return ldapsrv_UnbindRequest(call);
1143         case LDAP_TAG_SearchRequest:
1144                 return ldapsrv_SearchRequest(call);
1145         case LDAP_TAG_ModifyRequest:
1146                 return ldapsrv_ModifyRequest(call);
1147         case LDAP_TAG_AddRequest:
1148                 return ldapsrv_AddRequest(call);
1149         case LDAP_TAG_DelRequest:
1150                 return ldapsrv_DelRequest(call);
1151         case LDAP_TAG_ModifyDNRequest:
1152                 return ldapsrv_ModifyDNRequest(call);
1153         case LDAP_TAG_CompareRequest:
1154                 return ldapsrv_CompareRequest(call);
1155         case LDAP_TAG_AbandonRequest:
1156                 return ldapsrv_AbandonRequest(call);
1157         case LDAP_TAG_ExtendedRequest:
1158                 return ldapsrv_ExtendedRequest(call);
1159         default:
1160                 return ldapsrv_unwilling(call, 2);
1161         }
1162 }