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