s4-ldapserver: support controls on ldap add and rename
[ddiss/samba.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 = ldb_wrap_connect(conn, 
198                                      conn->connection->event.ctx,
199                                      conn->lp_ctx,
200                                      lpcfg_sam_url(conn->lp_ctx),
201                                      conn->session_info,
202                                      samdb_credentials(conn->connection->event.ctx, conn->lp_ctx),
203                                      conn->global_catalog ? LDB_FLG_RDONLY : 0);
204         if (conn->ldb == NULL) {
205                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
206         }
207
208         if (conn->server_credentials) {
209                 char **sasl_mechs = NULL;
210                 struct gensec_security_ops **backends = gensec_security_all();
211                 struct gensec_security_ops **ops
212                         = gensec_use_kerberos_mechs(conn, backends, conn->server_credentials);
213                 unsigned int i, j = 0;
214                 for (i = 0; ops && ops[i]; i++) {
215                         if (!lpcfg_parm_bool(conn->lp_ctx,  NULL, "gensec", ops[i]->name, ops[i]->enabled))
216                                 continue;
217
218                         if (ops[i]->sasl_name && ops[i]->server_start) {
219                                 char *sasl_name = talloc_strdup(conn, ops[i]->sasl_name);
220
221                                 if (!sasl_name) {
222                                         return NT_STATUS_NO_MEMORY;
223                                 }
224                                 sasl_mechs = talloc_realloc(conn, sasl_mechs, char *, j + 2);
225                                 if (!sasl_mechs) {
226                                         return NT_STATUS_NO_MEMORY;
227                                 }
228                                 sasl_mechs[j] = sasl_name;
229                                 talloc_steal(sasl_mechs, sasl_name);
230                                 sasl_mechs[j+1] = NULL;
231                                 j++;
232                         }
233                 }
234                 talloc_unlink(conn, ops);
235
236                 /* ldb can have a different lifetime to conn, so we
237                    need to ensure that sasl_mechs lives as long as the
238                    ldb does */
239                 talloc_steal(conn->ldb, sasl_mechs);
240
241                 ldb_set_opaque(conn->ldb, "supportedSASLMechanisms", sasl_mechs);
242         }
243
244         return NT_STATUS_OK;
245 }
246
247 struct ldapsrv_reply *ldapsrv_init_reply(struct ldapsrv_call *call, uint8_t type)
248 {
249         struct ldapsrv_reply *reply;
250
251         reply = talloc(call, struct ldapsrv_reply);
252         if (!reply) {
253                 return NULL;
254         }
255         reply->msg = talloc(reply, struct ldap_message);
256         if (reply->msg == NULL) {
257                 talloc_free(reply);
258                 return NULL;
259         }
260
261         reply->msg->messageid = call->request->messageid;
262         reply->msg->type = type;
263         reply->msg->controls = NULL;
264
265         return reply;
266 }
267
268 void ldapsrv_queue_reply(struct ldapsrv_call *call, struct ldapsrv_reply *reply)
269 {
270         DLIST_ADD_END(call->replies, reply, struct ldapsrv_reply *);
271 }
272
273 static NTSTATUS ldapsrv_unwilling(struct ldapsrv_call *call, int error)
274 {
275         struct ldapsrv_reply *reply;
276         struct ldap_ExtendedResponse *r;
277
278         DEBUG(10,("Unwilling type[%d] id[%d]\n", call->request->type, call->request->messageid));
279
280         reply = ldapsrv_init_reply(call, LDAP_TAG_ExtendedResponse);
281         if (!reply) {
282                 return NT_STATUS_NO_MEMORY;
283         }
284
285         r = &reply->msg->r.ExtendedResponse;
286         r->response.resultcode = error;
287         r->response.dn = NULL;
288         r->response.errormessage = NULL;
289         r->response.referral = NULL;
290         r->oid = NULL;
291         r->value = NULL;
292
293         ldapsrv_queue_reply(call, reply);
294         return NT_STATUS_OK;
295 }
296
297 static int ldb_add_with_controls(struct ldb_context *ldb,
298                                  const struct ldb_message *message,
299                                  struct ldb_control **controls,
300                                  void *context)
301 {
302         struct ldb_request *req;
303         int ret;
304
305         ret = ldb_msg_sanity_check(ldb, message);
306         if (ret != LDB_SUCCESS) {
307                 return ret;
308         }
309
310         ret = ldb_build_add_req(&req, ldb, ldb,
311                                         message,
312                                         controls,
313                                         context,
314                                         ldb_modify_default_callback,
315                                         NULL);
316
317         if (ret != LDB_SUCCESS) return ret;
318
319         ret = ldb_transaction_start(ldb);
320         if (ret != LDB_SUCCESS) {
321                 return ret;
322         }
323
324         ret = ldb_request(ldb, req);
325         if (ret == LDB_SUCCESS) {
326                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
327         }
328
329         if (ret == LDB_SUCCESS) {
330                 ret = ldb_transaction_commit(ldb);
331         }
332         else {
333                 ldb_transaction_cancel(ldb);
334         }
335
336         talloc_free(req);
337         return ret;
338 }
339
340 /* create and execute a modify request */
341 static int ldb_mod_req_with_controls(struct ldb_context *ldb,
342                                      const struct ldb_message *message,
343                                      struct ldb_control **controls,
344                                      void *context)
345 {
346         struct ldb_request *req;
347         int ret;
348
349         ret = ldb_msg_sanity_check(ldb, message);
350         if (ret != LDB_SUCCESS) {
351                 return ret;
352         }
353
354         ret = ldb_build_mod_req(&req, ldb, ldb,
355                                         message,
356                                         controls,
357                                         context,
358                                         ldb_modify_default_callback,
359                                         NULL);
360
361         if (ret != LDB_SUCCESS) {
362                 return ret;
363         }
364
365         ret = ldb_transaction_start(ldb);
366         if (ret != LDB_SUCCESS) {
367                 return ret;
368         }
369
370         ret = ldb_request(ldb, req);
371         if (ret == LDB_SUCCESS) {
372                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
373         }
374
375         if (ret == LDB_SUCCESS) {
376                 ret = ldb_transaction_commit(ldb);
377         }
378         else {
379                 ldb_transaction_cancel(ldb);
380         }
381
382         talloc_free(req);
383         return ret;
384 }
385
386 /* create and execute a delete request */
387 static int ldb_del_req_with_controls(struct ldb_context *ldb,
388                                      struct ldb_dn *dn,
389                                      struct ldb_control **controls,
390                                      void *context)
391 {
392         struct ldb_request *req;
393         int ret;
394
395         ret = ldb_build_del_req(&req, ldb, ldb,
396                                         dn,
397                                         controls,
398                                         context,
399                                         ldb_modify_default_callback,
400                                         NULL);
401
402         if (ret != LDB_SUCCESS) return ret;
403
404         ret = ldb_transaction_start(ldb);
405         if (ret != LDB_SUCCESS) {
406                 return ret;
407         }
408
409         ret = ldb_request(ldb, req);
410         if (ret == LDB_SUCCESS) {
411                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
412         }
413
414         if (ret == LDB_SUCCESS) {
415                 ret = ldb_transaction_commit(ldb);
416         }
417         else {
418                 ldb_transaction_cancel(ldb);
419         }
420
421         talloc_free(req);
422         return ret;
423 }
424
425 int ldb_rename_with_controls(struct ldb_context *ldb,
426                              struct ldb_dn *olddn,
427                              struct ldb_dn *newdn,
428                              struct ldb_control **controls,
429                              void *context)
430 {
431         struct ldb_request *req;
432         int ret;
433
434         ret = ldb_build_rename_req(&req, ldb, ldb,
435                                         olddn,
436                                         newdn,
437                                         NULL,
438                                         context,
439                                         ldb_modify_default_callback,
440                                         NULL);
441
442         if (ret != LDB_SUCCESS) return ret;
443
444         ret = ldb_transaction_start(ldb);
445         if (ret != LDB_SUCCESS) {
446                 return ret;
447         }
448
449         ret = ldb_request(ldb, req);
450         if (ret == LDB_SUCCESS) {
451                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
452         }
453
454         if (ret == LDB_SUCCESS) {
455                 ret = ldb_transaction_commit(ldb);
456         }
457         else {
458                 ldb_transaction_cancel(ldb);
459         }
460
461         talloc_free(req);
462         return ret;
463 }
464
465 static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call)
466 {
467         struct ldap_SearchRequest *req = &call->request->r.SearchRequest;
468         struct ldap_SearchResEntry *ent;
469         struct ldap_Result *done;
470         struct ldapsrv_reply *ent_r, *done_r;
471         TALLOC_CTX *local_ctx;
472         struct ldb_context *samdb = talloc_get_type(call->conn->ldb, struct ldb_context);
473         struct ldb_dn *basedn;
474         struct ldb_result *res = NULL;
475         struct ldb_request *lreq;
476         struct ldb_control *search_control;
477         struct ldb_search_options_control *search_options;
478         struct ldb_control *extended_dn_control;
479         struct ldb_extended_dn_control *extended_dn_decoded = NULL;
480         enum ldb_scope scope = LDB_SCOPE_DEFAULT;
481         const char **attrs = NULL;
482         const char *scope_str, *errstr = NULL;
483         int success_limit = 1;
484         int result = -1;
485         int ldb_ret = -1;
486         unsigned int i, j;
487         int extended_type = 1;
488
489         DEBUG(10, ("SearchRequest"));
490         DEBUGADD(10, (" basedn: %s", req->basedn));
491         DEBUGADD(10, (" filter: %s\n", ldb_filter_from_tree(call, req->tree)));
492
493         local_ctx = talloc_new(call);
494         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
495
496         basedn = ldb_dn_new(local_ctx, samdb, req->basedn);
497         VALID_DN_SYNTAX(basedn);
498
499         DEBUG(10, ("SearchRequest: basedn: [%s]\n", req->basedn));
500         DEBUG(10, ("SearchRequest: filter: [%s]\n", ldb_filter_from_tree(call, req->tree)));
501
502         switch (req->scope) {
503                 case LDAP_SEARCH_SCOPE_BASE:
504                         scope_str = "BASE";
505                         scope = LDB_SCOPE_BASE;
506                         success_limit = 0;
507                         break;
508                 case LDAP_SEARCH_SCOPE_SINGLE:
509                         scope_str = "ONE";
510                         scope = LDB_SCOPE_ONELEVEL;
511                         success_limit = 0;
512                         break;
513                 case LDAP_SEARCH_SCOPE_SUB:
514                         scope_str = "SUB";
515                         scope = LDB_SCOPE_SUBTREE;
516                         success_limit = 0;
517                         break;
518                 default:
519                         result = LDAP_PROTOCOL_ERROR;
520                         map_ldb_error(local_ctx, LDB_ERR_PROTOCOL_ERROR, NULL,
521                                 &errstr);
522                         errstr = talloc_asprintf(local_ctx,
523                                 "%s. Invalid scope", errstr);
524                         goto reply;
525         }
526         DEBUG(10,("SearchRequest: scope: [%s]\n", scope_str));
527
528         if (req->num_attributes >= 1) {
529                 attrs = talloc_array(local_ctx, const char *, req->num_attributes+1);
530                 NT_STATUS_HAVE_NO_MEMORY(attrs);
531
532                 for (i=0; i < req->num_attributes; i++) {
533                         DEBUG(10,("SearchRequest: attrs: [%s]\n",req->attributes[i]));
534                         attrs[i] = req->attributes[i];
535                 }
536                 attrs[i] = NULL;
537         }
538
539         DEBUG(5,("ldb_request %s dn=%s filter=%s\n", 
540                  scope_str, req->basedn, ldb_filter_from_tree(call, req->tree)));
541
542         res = talloc_zero(local_ctx, struct ldb_result);
543         NT_STATUS_HAVE_NO_MEMORY(res);
544
545         ldb_ret = ldb_build_search_req_ex(&lreq, samdb, local_ctx,
546                                           basedn, scope,
547                                           req->tree, attrs,
548                                           call->request->controls,
549                                           res, ldb_search_default_callback,
550                                           NULL);
551
552         if (ldb_ret != LDB_SUCCESS) {
553                 goto reply;
554         }
555
556         if (call->conn->global_catalog) {
557                 search_control = ldb_request_get_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID);
558
559                 search_options = NULL;
560                 if (search_control) {
561                         search_options = talloc_get_type(search_control->data, struct ldb_search_options_control);
562                         search_options->search_options |= LDB_SEARCH_OPTION_PHANTOM_ROOT;
563                 } else {
564                         search_options = talloc(lreq, struct ldb_search_options_control);
565                         NT_STATUS_HAVE_NO_MEMORY(search_options);
566                         search_options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
567                         ldb_request_add_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID, false, search_options);
568                 }
569         }
570
571         extended_dn_control = ldb_request_get_control(lreq, LDB_CONTROL_EXTENDED_DN_OID);
572
573         if (extended_dn_control) {
574                 if (extended_dn_control->data) {
575                         extended_dn_decoded = talloc_get_type(extended_dn_control->data, struct ldb_extended_dn_control);
576                         extended_type = extended_dn_decoded->type;
577                 } else {
578                         extended_type = 0;
579                 }
580         }
581
582         ldb_set_timeout(samdb, lreq, req->timelimit);
583
584         ldb_ret = ldb_request(samdb, lreq);
585
586         if (ldb_ret != LDB_SUCCESS) {
587                 goto reply;
588         }
589
590         ldb_ret = ldb_wait(lreq->handle, LDB_WAIT_ALL);
591
592         if (ldb_ret == LDB_SUCCESS) {
593                 for (i = 0; i < res->count; i++) {
594                         ent_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultEntry);
595                         NT_STATUS_HAVE_NO_MEMORY(ent_r);
596
597                         /* Better to have the whole message kept here,
598                          * than to find someone further up didn't put
599                          * a value in the right spot in the talloc tree */
600                         talloc_steal(ent_r, res->msgs[i]);
601                         
602                         ent = &ent_r->msg->r.SearchResultEntry;
603                         ent->dn = ldb_dn_get_extended_linearized(ent_r, res->msgs[i]->dn, extended_type);
604                         ent->num_attributes = 0;
605                         ent->attributes = NULL;
606                         if (res->msgs[i]->num_elements == 0) {
607                                 goto queue_reply;
608                         }
609                         ent->num_attributes = res->msgs[i]->num_elements;
610                         ent->attributes = talloc_array(ent_r, struct ldb_message_element, ent->num_attributes);
611                         NT_STATUS_HAVE_NO_MEMORY(ent->attributes);
612                         for (j=0; j < ent->num_attributes; j++) {
613                                 ent->attributes[j].name = res->msgs[i]->elements[j].name;
614                                 ent->attributes[j].num_values = 0;
615                                 ent->attributes[j].values = NULL;
616                                 if (req->attributesonly && (res->msgs[i]->elements[j].num_values == 0)) {
617                                         continue;
618                                 }
619                                 ent->attributes[j].num_values = res->msgs[i]->elements[j].num_values;
620                                 ent->attributes[j].values = res->msgs[i]->elements[j].values;
621                         }
622 queue_reply:
623                         ldapsrv_queue_reply(call, ent_r);
624                 }
625
626                 /* Send back referrals if they do exist (search operations) */
627                 if (res->refs != NULL) {
628                         char **ref;
629                         struct ldap_SearchResRef *ent_ref;
630
631                         for (ref = res->refs; *ref != NULL; ++ref) {
632                                 ent_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultReference);
633                                 NT_STATUS_HAVE_NO_MEMORY(ent_r);
634
635                                 /* Better to have the whole referrals kept here,
636                                  * than to find someone further up didn't put
637                                  * a value in the right spot in the talloc tree
638                                  */
639                                 talloc_steal(ent_r, *ref);
640
641                                 ent_ref = &ent_r->msg->r.SearchResultReference;
642                                 ent_ref->referral = *ref;
643
644                                 ldapsrv_queue_reply(call, ent_r);
645                         }
646                 }
647         }
648
649 reply:
650         done_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultDone);
651         NT_STATUS_HAVE_NO_MEMORY(done_r);
652
653         done = &done_r->msg->r.SearchResultDone;
654         done->dn = NULL;
655         done->referral = NULL;
656
657         if (result != -1) {
658         } else if (ldb_ret == LDB_SUCCESS) {
659                 if (res->count >= success_limit) {
660                         DEBUG(10,("SearchRequest: results: [%d]\n", res->count));
661                         result = LDAP_SUCCESS;
662                         errstr = NULL;
663                 }
664                 if (res->controls) {
665                         done_r->msg->controls = res->controls;
666                         talloc_steal(done_r, res->controls);
667                 }
668         } else {
669                 DEBUG(10,("SearchRequest: error\n"));
670                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
671                                        &errstr);
672         }
673
674         done->resultcode = result;
675         done->errormessage = (errstr?talloc_strdup(done_r, errstr):NULL);
676
677         talloc_free(local_ctx);
678
679         ldapsrv_queue_reply(call, done_r);
680         return NT_STATUS_OK;
681 }
682
683 static NTSTATUS ldapsrv_ModifyRequest(struct ldapsrv_call *call)
684 {
685         struct ldap_ModifyRequest *req = &call->request->r.ModifyRequest;
686         struct ldap_Result *modify_result;
687         struct ldapsrv_reply *modify_reply;
688         TALLOC_CTX *local_ctx;
689         struct ldb_context *samdb = call->conn->ldb;
690         struct ldb_message *msg = NULL;
691         struct ldb_dn *dn;
692         const char *errstr = NULL;
693         int result = LDAP_SUCCESS;
694         int ldb_ret;
695         unsigned int i,j;
696         struct ldb_result *res = NULL;
697
698         DEBUG(10, ("ModifyRequest"));
699         DEBUGADD(10, (" dn: %s\n", req->dn));
700
701         local_ctx = talloc_named(call, 0, "ModifyRequest local memory context");
702         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
703
704         dn = ldb_dn_new(local_ctx, samdb, req->dn);
705         VALID_DN_SYNTAX(dn);
706
707         DEBUG(10, ("ModifyRequest: dn: [%s]\n", req->dn));
708
709         msg = talloc(local_ctx, struct ldb_message);
710         NT_STATUS_HAVE_NO_MEMORY(msg);
711
712         msg->dn = dn;
713         msg->num_elements = 0;
714         msg->elements = NULL;
715
716         if (req->num_mods > 0) {
717                 msg->num_elements = req->num_mods;
718                 msg->elements = talloc_array(msg, struct ldb_message_element, req->num_mods);
719                 NT_STATUS_HAVE_NO_MEMORY(msg->elements);
720
721                 for (i=0; i < msg->num_elements; i++) {
722                         msg->elements[i].name = discard_const_p(char, req->mods[i].attrib.name);
723                         msg->elements[i].num_values = 0;
724                         msg->elements[i].values = NULL;
725
726                         switch (req->mods[i].type) {
727                         default:
728                                 result = LDAP_PROTOCOL_ERROR;
729                                 map_ldb_error(local_ctx,
730                                         LDB_ERR_PROTOCOL_ERROR, NULL, &errstr);
731                                 errstr = talloc_asprintf(local_ctx,
732                                         "%s. Invalid LDAP_MODIFY_* type", errstr);
733                                 goto reply;
734                         case LDAP_MODIFY_ADD:
735                                 msg->elements[i].flags = LDB_FLAG_MOD_ADD;
736                                 break;
737                         case LDAP_MODIFY_DELETE:
738                                 msg->elements[i].flags = LDB_FLAG_MOD_DELETE;
739                                 break;
740                         case LDAP_MODIFY_REPLACE:
741                                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
742                                 break;
743                         }
744
745                         msg->elements[i].num_values = req->mods[i].attrib.num_values;
746                         if (msg->elements[i].num_values > 0) {
747                                 msg->elements[i].values = talloc_array(msg->elements, struct ldb_val,
748                                                                        msg->elements[i].num_values);
749                                 NT_STATUS_HAVE_NO_MEMORY(msg->elements[i].values);
750
751                                 for (j=0; j < msg->elements[i].num_values; j++) {
752                                         msg->elements[i].values[j].length = req->mods[i].attrib.values[j].length;
753                                         msg->elements[i].values[j].data = req->mods[i].attrib.values[j].data;                   
754                                 }
755                         }
756                 }
757         }
758
759 reply:
760         modify_reply = ldapsrv_init_reply(call, LDAP_TAG_ModifyResponse);
761         NT_STATUS_HAVE_NO_MEMORY(modify_reply);
762
763         if (result == LDAP_SUCCESS) {
764                 res = talloc_zero(local_ctx, struct ldb_result);
765                 NT_STATUS_HAVE_NO_MEMORY(res);
766                 ldb_ret = ldb_mod_req_with_controls(samdb, msg, call->request->controls, res);
767                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
768                                        &errstr);
769         }
770
771         modify_result = &modify_reply->msg->r.ModifyResponse;
772         modify_result->dn = NULL;
773         if ((res != NULL) && (res->refs != NULL)) {
774                 modify_result->resultcode = map_ldb_error(local_ctx,
775                                                           LDB_ERR_REFERRAL,
776                                                           NULL, &errstr);
777                 modify_result->errormessage = (errstr?talloc_strdup(modify_reply, errstr):NULL);
778                 modify_result->referral = talloc_strdup(call, *res->refs);
779         } else {
780                 modify_result->resultcode = result;
781                 modify_result->errormessage = (errstr?talloc_strdup(modify_reply, errstr):NULL);
782                 modify_result->referral = NULL;
783         }
784         talloc_free(local_ctx);
785
786         ldapsrv_queue_reply(call, modify_reply);
787         return NT_STATUS_OK;
788
789 }
790
791 static NTSTATUS ldapsrv_AddRequest(struct ldapsrv_call *call)
792 {
793         struct ldap_AddRequest *req = &call->request->r.AddRequest;
794         struct ldap_Result *add_result;
795         struct ldapsrv_reply *add_reply;
796         TALLOC_CTX *local_ctx;
797         struct ldb_context *samdb = call->conn->ldb;
798         struct ldb_message *msg = NULL;
799         struct ldb_dn *dn;
800         const char *errstr = NULL;
801         int result = LDAP_SUCCESS;
802         int ldb_ret;
803         unsigned int i,j;
804         struct ldb_result *res = NULL;
805
806         DEBUG(10, ("AddRequest"));
807         DEBUGADD(10, (" dn: %s\n", req->dn));
808
809         local_ctx = talloc_named(call, 0, "AddRequest local memory context");
810         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
811
812         dn = ldb_dn_new(local_ctx, samdb, req->dn);
813         VALID_DN_SYNTAX(dn);
814
815         DEBUG(10, ("AddRequest: dn: [%s]\n", req->dn));
816
817         msg = talloc(local_ctx, struct ldb_message);
818         NT_STATUS_HAVE_NO_MEMORY(msg);
819
820         msg->dn = dn;
821         msg->num_elements = 0;
822         msg->elements = NULL;
823
824         if (req->num_attributes > 0) {
825                 msg->num_elements = req->num_attributes;
826                 msg->elements = talloc_array(msg, struct ldb_message_element, msg->num_elements);
827                 NT_STATUS_HAVE_NO_MEMORY(msg->elements);
828
829                 for (i=0; i < msg->num_elements; i++) {
830                         msg->elements[i].name = discard_const_p(char, req->attributes[i].name);
831                         msg->elements[i].flags = 0;
832                         msg->elements[i].num_values = 0;
833                         msg->elements[i].values = NULL;
834                         
835                         if (req->attributes[i].num_values > 0) {
836                                 msg->elements[i].num_values = req->attributes[i].num_values;
837                                 msg->elements[i].values = talloc_array(msg->elements, struct ldb_val,
838                                                                        msg->elements[i].num_values);
839                                 NT_STATUS_HAVE_NO_MEMORY(msg->elements[i].values);
840
841                                 for (j=0; j < msg->elements[i].num_values; j++) {
842                                         msg->elements[i].values[j].length = req->attributes[i].values[j].length;
843                                         msg->elements[i].values[j].data = req->attributes[i].values[j].data;                    
844                                 }
845                         }
846                 }
847         }
848
849 reply:
850         add_reply = ldapsrv_init_reply(call, LDAP_TAG_AddResponse);
851         NT_STATUS_HAVE_NO_MEMORY(add_reply);
852
853         if (result == LDAP_SUCCESS) {
854                 res = talloc_zero(local_ctx, struct ldb_result);
855                 NT_STATUS_HAVE_NO_MEMORY(res);
856                 ldb_ret = ldb_add_with_controls(samdb, msg, call->request->controls, res);
857                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
858                                        &errstr);
859         }
860
861         add_result = &add_reply->msg->r.AddResponse;
862         add_result->dn = NULL;
863         if ((res != NULL) && (res->refs != NULL)) {
864                 add_result->resultcode =  map_ldb_error(local_ctx,
865                                                         LDB_ERR_REFERRAL, NULL,
866                                                         &errstr);
867                 add_result->errormessage = (errstr?talloc_strdup(add_reply,errstr):NULL);
868                 add_result->referral = talloc_strdup(call, *res->refs);
869         } else {
870                 add_result->resultcode = result;
871                 add_result->errormessage = (errstr?talloc_strdup(add_reply,errstr):NULL);
872                 add_result->referral = NULL;
873         }
874         talloc_free(local_ctx);
875
876         ldapsrv_queue_reply(call, add_reply);
877         return NT_STATUS_OK;
878
879 }
880
881 static NTSTATUS ldapsrv_DelRequest(struct ldapsrv_call *call)
882 {
883         struct ldap_DelRequest *req = &call->request->r.DelRequest;
884         struct ldap_Result *del_result;
885         struct ldapsrv_reply *del_reply;
886         TALLOC_CTX *local_ctx;
887         struct ldb_context *samdb = call->conn->ldb;
888         struct ldb_dn *dn;
889         const char *errstr = NULL;
890         int result = LDAP_SUCCESS;
891         int ldb_ret;
892         struct ldb_result *res = NULL;
893
894         DEBUG(10, ("DelRequest"));
895         DEBUGADD(10, (" dn: %s\n", req->dn));
896
897         local_ctx = talloc_named(call, 0, "DelRequest local memory context");
898         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
899
900         dn = ldb_dn_new(local_ctx, samdb, req->dn);
901         VALID_DN_SYNTAX(dn);
902
903         DEBUG(10, ("DelRequest: dn: [%s]\n", req->dn));
904
905 reply:
906         del_reply = ldapsrv_init_reply(call, LDAP_TAG_DelResponse);
907         NT_STATUS_HAVE_NO_MEMORY(del_reply);
908
909         if (result == LDAP_SUCCESS) {
910                 res = talloc_zero(local_ctx, struct ldb_result);
911                 NT_STATUS_HAVE_NO_MEMORY(res);
912                 ldb_ret = ldb_del_req_with_controls(samdb, dn, call->request->controls, res);
913                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
914                                        &errstr);
915         }
916
917         del_result = &del_reply->msg->r.DelResponse;
918         del_result->dn = NULL;
919         if ((res != NULL) && (res->refs != NULL)) {
920                 del_result->resultcode = map_ldb_error(local_ctx,
921                                                        LDB_ERR_REFERRAL, NULL,
922                                                        &errstr);
923                 del_result->errormessage = (errstr?talloc_strdup(del_reply,errstr):NULL);
924                 del_result->referral = talloc_strdup(call, *res->refs);
925         } else {
926                 del_result->resultcode = result;
927                 del_result->errormessage = (errstr?talloc_strdup(del_reply,errstr):NULL);
928                 del_result->referral = NULL;
929         }
930
931         talloc_free(local_ctx);
932
933         ldapsrv_queue_reply(call, del_reply);
934         return NT_STATUS_OK;
935 }
936
937 static NTSTATUS ldapsrv_ModifyDNRequest(struct ldapsrv_call *call)
938 {
939         struct ldap_ModifyDNRequest *req = &call->request->r.ModifyDNRequest;
940         struct ldap_Result *modifydn;
941         struct ldapsrv_reply *modifydn_r;
942         TALLOC_CTX *local_ctx;
943         struct ldb_context *samdb = call->conn->ldb;
944         struct ldb_dn *olddn, *newdn=NULL, *newrdn;
945         struct ldb_dn *parentdn = NULL;
946         const char *errstr = NULL;
947         int result = LDAP_SUCCESS;
948         int ldb_ret;
949         struct ldb_result *res = NULL;
950
951         DEBUG(10, ("ModifyDNRequest"));
952         DEBUGADD(10, (" dn: %s", req->dn));
953         DEBUGADD(10, (" newrdn: %s\n", req->newrdn));
954
955         local_ctx = talloc_named(call, 0, "ModifyDNRequest local memory context");
956         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
957
958         olddn = ldb_dn_new(local_ctx, samdb, req->dn);
959         VALID_DN_SYNTAX(olddn);
960
961         newrdn = ldb_dn_new(local_ctx, samdb, req->newrdn);
962         VALID_DN_SYNTAX(newrdn);
963
964         DEBUG(10, ("ModifyDNRequest: olddn: [%s]\n", req->dn));
965         DEBUG(10, ("ModifyDNRequest: newrdn: [%s]\n", req->newrdn));
966
967         if (ldb_dn_get_comp_num(newrdn) == 0) {
968                 result = LDAP_PROTOCOL_ERROR;
969                 map_ldb_error(local_ctx, LDB_ERR_PROTOCOL_ERROR, NULL,
970                               &errstr);
971                 goto reply;
972         }
973
974         if (ldb_dn_get_comp_num(newrdn) > 1) {
975                 result = LDAP_NAMING_VIOLATION;
976                 map_ldb_error(local_ctx, LDB_ERR_NAMING_VIOLATION, NULL,
977                               &errstr);
978                 goto reply;
979         }
980
981         /* we can't handle the rename if we should not remove the old dn */
982         if (!req->deleteolddn) {
983                 result = LDAP_UNWILLING_TO_PERFORM;
984                 map_ldb_error(local_ctx, LDB_ERR_UNWILLING_TO_PERFORM, NULL,
985                               &errstr);
986                 errstr = talloc_asprintf(local_ctx,
987                         "%s. Old RDN must be deleted", errstr);
988                 goto reply;
989         }
990
991         if (req->newsuperior) {
992                 parentdn = ldb_dn_new(local_ctx, samdb, req->newsuperior);
993                 VALID_DN_SYNTAX(parentdn);
994                 DEBUG(10, ("ModifyDNRequest: newsuperior: [%s]\n", req->newsuperior));
995         }
996
997         if (!parentdn) {
998                 parentdn = ldb_dn_get_parent(local_ctx, olddn);
999         }
1000         if (!parentdn) {
1001                 result = LDAP_NO_SUCH_OBJECT;
1002                 map_ldb_error(local_ctx, LDB_ERR_NO_SUCH_OBJECT, NULL, &errstr);
1003                 goto reply;
1004         }
1005
1006         if ( ! ldb_dn_add_child(parentdn, newrdn)) {
1007                 result = LDAP_OTHER;
1008                 map_ldb_error(local_ctx, LDB_ERR_OTHER, NULL, &errstr);
1009                 goto reply;
1010         }
1011         newdn = parentdn;
1012
1013 reply:
1014         modifydn_r = ldapsrv_init_reply(call, LDAP_TAG_ModifyDNResponse);
1015         NT_STATUS_HAVE_NO_MEMORY(modifydn_r);
1016
1017         if (result == LDAP_SUCCESS) {
1018                 res = talloc_zero(local_ctx, struct ldb_result);
1019                 NT_STATUS_HAVE_NO_MEMORY(res);
1020                 ldb_ret = ldb_rename_with_controls(samdb, olddn, newdn, call->request->controls, res);
1021                 result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
1022                                        &errstr);
1023         }
1024
1025         modifydn = &modifydn_r->msg->r.ModifyDNResponse;
1026         modifydn->dn = NULL;
1027         if ((res != NULL) && (res->refs != NULL)) {
1028                 modifydn->resultcode = map_ldb_error(local_ctx,
1029                                                      LDB_ERR_REFERRAL, NULL,
1030                                                      &errstr);;
1031                 modifydn->errormessage = (errstr?talloc_strdup(modifydn_r,errstr):NULL);
1032                 modifydn->referral = talloc_strdup(call, *res->refs);
1033         } else {
1034                 modifydn->resultcode = result;
1035                 modifydn->errormessage = (errstr?talloc_strdup(modifydn_r,errstr):NULL);
1036                 modifydn->referral = NULL;
1037         }
1038
1039         talloc_free(local_ctx);
1040
1041         ldapsrv_queue_reply(call, modifydn_r);
1042         return NT_STATUS_OK;
1043 }
1044
1045 static NTSTATUS ldapsrv_CompareRequest(struct ldapsrv_call *call)
1046 {
1047         struct ldap_CompareRequest *req = &call->request->r.CompareRequest;
1048         struct ldap_Result *compare;
1049         struct ldapsrv_reply *compare_r;
1050         TALLOC_CTX *local_ctx;
1051         struct ldb_context *samdb = call->conn->ldb;
1052         struct ldb_result *res = NULL;
1053         struct ldb_dn *dn;
1054         const char *attrs[1];
1055         const char *errstr = NULL;
1056         const char *filter = NULL;
1057         int result = LDAP_SUCCESS;
1058         int ldb_ret;
1059
1060         DEBUG(10, ("CompareRequest"));
1061         DEBUGADD(10, (" dn: %s\n", req->dn));
1062
1063         local_ctx = talloc_named(call, 0, "CompareRequest local_memory_context");
1064         NT_STATUS_HAVE_NO_MEMORY(local_ctx);
1065
1066         dn = ldb_dn_new(local_ctx, samdb, req->dn);
1067         VALID_DN_SYNTAX(dn);
1068
1069         DEBUG(10, ("CompareRequest: dn: [%s]\n", req->dn));
1070         filter = talloc_asprintf(local_ctx, "(%s=%*s)", req->attribute, 
1071                                  (int)req->value.length, req->value.data);
1072         NT_STATUS_HAVE_NO_MEMORY(filter);
1073
1074         DEBUGADD(10, ("CompareRequest: attribute: [%s]\n", filter));
1075
1076         attrs[0] = NULL;
1077
1078 reply:
1079         compare_r = ldapsrv_init_reply(call, LDAP_TAG_CompareResponse);
1080         NT_STATUS_HAVE_NO_MEMORY(compare_r);
1081
1082         if (result == LDAP_SUCCESS) {
1083                 ldb_ret = ldb_search(samdb, local_ctx, &res,
1084                                      dn, LDB_SCOPE_BASE, attrs, "%s", filter);
1085                 if (ldb_ret != LDB_SUCCESS) {
1086                         result = map_ldb_error(local_ctx, ldb_ret,
1087                                                ldb_errstring(samdb), &errstr);
1088                         DEBUG(10,("CompareRequest: error: %s\n", errstr));
1089                 } else if (res->count == 0) {
1090                         DEBUG(10,("CompareRequest: doesn't matched\n"));
1091                         result = LDAP_COMPARE_FALSE;
1092                         errstr = NULL;
1093                 } else if (res->count == 1) {
1094                         DEBUG(10,("CompareRequest: matched\n"));
1095                         result = LDAP_COMPARE_TRUE;
1096                         errstr = NULL;
1097                 } else if (res->count > 1) {
1098                         result = LDAP_OTHER;
1099                         map_ldb_error(local_ctx, LDB_ERR_OTHER, NULL, &errstr);
1100                         errstr = talloc_asprintf(local_ctx,
1101                                 "%s. Too many objects match!", errstr);
1102                         DEBUG(10,("CompareRequest: %d results: %s\n", res->count, errstr));
1103                 }
1104         }
1105
1106         compare = &compare_r->msg->r.CompareResponse;
1107         compare->dn = NULL;
1108         compare->resultcode = result;
1109         compare->errormessage = (errstr?talloc_strdup(compare_r,errstr):NULL);
1110         compare->referral = NULL;
1111
1112         talloc_free(local_ctx);
1113
1114         ldapsrv_queue_reply(call, compare_r);
1115         return NT_STATUS_OK;
1116 }
1117
1118 static NTSTATUS ldapsrv_AbandonRequest(struct ldapsrv_call *call)
1119 {
1120 /*      struct ldap_AbandonRequest *req = &call->request.r.AbandonRequest;*/
1121         DEBUG(10, ("AbandonRequest\n"));
1122         return NT_STATUS_OK;
1123 }
1124
1125 NTSTATUS ldapsrv_do_call(struct ldapsrv_call *call)
1126 {
1127         unsigned int i;
1128         struct ldap_message *msg = call->request;
1129         /* Check for undecoded critical extensions */
1130         for (i=0; msg->controls && msg->controls[i]; i++) {
1131                 if (!msg->controls_decoded[i] && 
1132                     msg->controls[i]->critical) {
1133                         DEBUG(3, ("ldapsrv_do_call: Critical extension %s is not known to this server\n",
1134                                   msg->controls[i]->oid));
1135                         return ldapsrv_unwilling(call, LDAP_UNAVAILABLE_CRITICAL_EXTENSION);
1136                 }
1137         }
1138
1139         switch(call->request->type) {
1140         case LDAP_TAG_BindRequest:
1141                 return ldapsrv_BindRequest(call);
1142         case LDAP_TAG_UnbindRequest:
1143                 return ldapsrv_UnbindRequest(call);
1144         case LDAP_TAG_SearchRequest:
1145                 return ldapsrv_SearchRequest(call);
1146         case LDAP_TAG_ModifyRequest:
1147                 return ldapsrv_ModifyRequest(call);
1148         case LDAP_TAG_AddRequest:
1149                 return ldapsrv_AddRequest(call);
1150         case LDAP_TAG_DelRequest:
1151                 return ldapsrv_DelRequest(call);
1152         case LDAP_TAG_ModifyDNRequest:
1153                 return ldapsrv_ModifyDNRequest(call);
1154         case LDAP_TAG_CompareRequest:
1155                 return ldapsrv_CompareRequest(call);
1156         case LDAP_TAG_AbandonRequest:
1157                 return ldapsrv_AbandonRequest(call);
1158         case LDAP_TAG_ExtendedRequest:
1159                 return ldapsrv_ExtendedRequest(call);
1160         default:
1161                 return ldapsrv_unwilling(call, 2);
1162         }
1163 }