aboutsummaryrefslogtreecommitdiffstats
path: root/lualdap/src/lualdap.c
blob: 8972c42e695f79ea8b3e2d58442ddbce28e5938c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/*
** LuaLDAP
** $Id: lualdap.c,v 1.5 2003-06-18 16:01:55 tomas Exp $
*/

#include <stdlib.h>
#include <string.h>

#include <ldap.h>

#include <lua.h>
#include <lauxlib.h>


#define LUALDAP_PREFIX "LuaLDAP: "
#define LUALDAP_TABLENAME "lualdap"
#define LUALDAP_CONNECTION_METATABLE "LuaLDAP connection"
#define LUALDAP_SEARCH_METATABLE "LuaLDAP search"

/* Maximum number of attributes managed in an operation */
#ifndef LUALDAP_MAX_ATTRS
#define LUALDAP_MAX_ATTRS 100
#endif

/* Size of buffer of NULL-terminated arrays of pointers to struct values */
#ifndef LUALDAP_ARRAY_VALUES_SIZE
#define LUALDAP_ARRAY_VALUES_SIZE (2 * LUALDAP_MAX_ATTRS)
#endif

/* Maximum number of values structures */
#ifndef LUALDAP_MAX_VALUES
#define LUALDAP_MAX_VALUES (LUALDAP_ARRAY_VALUES_SIZE / 2)
#endif


/* LDAP connection information */
typedef struct {
	int        closed;
	int        version; /* LDAP version */
	LDAP      *ld;      /* LDAP connection */
} conn_data;


/* LDAP search context information */
typedef struct {
	int      closed;
	int      conn;        /* conn_data reference */
	int      msgid;
} search_data;


int lualdap_libopen (lua_State *L);


/*
** Typical error situation.
*/
static int faildirect (lua_State *L, const char *errmsg) {
    lua_pushnil (L);
    lua_pushstring (L, errmsg);
    return 2;
}


/*
** Get a connection object from the first stack position.
*/
static conn_data *getconnection (lua_State *L) {
	conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUALDAP_CONNECTION_METATABLE);
	luaL_argcheck(L, conn!=NULL, 1, LUALDAP_PREFIX"LDAP connection expected");
	luaL_argcheck(L,!conn->closed,1,LUALDAP_PREFIX"LDAP connection is closed");
	return conn;
}


/*
** Get a search object from the first upvalue position.
*/
static search_data *getsearch (lua_State *L) {
	search_data *search = (search_data *)luaL_checkudata (L, lua_upvalueindex (1), LUALDAP_SEARCH_METATABLE);
	luaL_argcheck (L, search!=NULL, 1, LUALDAP_PREFIX"LDAP search expected");
	luaL_argcheck (L,!search->closed,1,LUALDAP_PREFIX"LDAP search is closed");
	return search;
}


/*
** Set metatable of userdata on top of the stack.
*/
static void lualdap_setmeta (lua_State *L, char *name) {
	luaL_getmetatable (L, name);
	lua_setmetatable (L, -2);
}


/*
** Copy a Lua string to a C string optionally indicating length.
*/
static char *luastrcpy (lua_State *L, int index, size_t *length) {
	size_t len = lua_strlen (L, index);
	char *str = malloc (len * sizeof(char));
	memcpy (str, lua_tostring (L, index), len);
	if (length)
		*length = len;
	return str;
}


/*
** Create a NULL-terminated array of C-strings from a Lua table.
** It also works for one string (instead of a table with a unique value).
** @param tab stack index of the table (or string).
** @return NULL-terminated array of C-strings.
*/
static char **table2strarray (lua_State *L, int tab) {
	char **array;
	int i;
	int n;
	if (lua_istable (L, tab)) {
		n = luaL_getn (L, tab);
		array = malloc ((n+1) * sizeof(char *));
		for (i = 0; i < n; i++) {
			lua_rawgeti (L, tab, i+1); /* push table element */
			if (lua_isstring (L, -1))
				array[i] = luastrcpy (L, -1, NULL);
			else {
				luaL_error (L, LUALDAP_PREFIX"invalid value");
			}
		}
		lua_pop (L, n);
	} else if (lua_isstring (L, tab)) {
		array = malloc (2 * sizeof(char *));
		array[0] = luastrcpy (L, -1, NULL);
	}
	array[n] = NULL;
	return array;
}


/*
** Free a NULL-terminated array of C-strings.
*/
static void free_strarray (char **array) {
	if (array) {
		int i;
		for (i = 0; array[i] != NULL; i++)
			free (array[i]);
		free (array);
	}
}


/*
** Create a NULL-terminated array of berval strings from a Lua table.
** It also works for one string (instead of a table with a unique value).
** @param tab stack index of the table (or string).
** @return NULL-terminated array of berval strings.
*/
static BerValue **table2bervalarray (lua_State *L, int tab) {
	BerValue **array;
	int i;
	int n;
	if (lua_istable (L, tab)) {
		n = luaL_getn (L, tab);
		array = malloc ((n+1) * sizeof(BerValue *));
		for (i = 0; i < n; i++) {
			lua_rawgeti (L, tab, i+1); /* push table element */
			if (lua_isstring (L, -1)) {
				array[i] = (BerValue *)malloc (sizeof (BerValue));
				array[i]->bv_val = luastrcpy (L, -1, &(array[i]->bv_len));
			} else {
				luaL_error (L, LUALDAP_PREFIX"invalid value");
			}
		}
		lua_pop (L, n);
	} else if (lua_isstring (L, tab)) {
		n = 1;
		array = (BerValue **)malloc (2 * sizeof(BerValue *));
		array[0] = (BerValue *)malloc (sizeof (BerValue));
		array[0]->bv_val = luastrcpy (L, -1, &(array[0]->bv_len));
	}
	array[n] = NULL;
	return array;
}


/*
** Free a NULL-terminated array of bervalstrings.
*/
static void free_bervalarray (BerValue **array) {
	if (array) {
		int i;
		for (i = 0; array[i] != NULL; i++) {
			free (array[i]->bv_val);
			free (array[i]);
		}
		free (array);
	}
}


/*
** Unbind from the directory.
** @param #1 LDAP connection.
** @return 1 in case of success; nothing when already closed.
*/
static int lualdap_close (lua_State *L) {
	conn_data *conn = getconnection (L);
	if (conn->closed)
		return 0;
	conn->closed = 1;
	if (conn->ld) {
		ldap_unbind (conn->ld);
		conn->ld = NULL;
	}
	lua_pushnumber (L, 1);
	return 1;
}


/*
** Counts the number of string keys of a given table.
*/
static size_t nstrkeys (lua_State *L, int tab) {
	int n = 0;
	lua_pushnil (L);
	while (lua_next(L, tab) != 0) {
		lua_pop (L, 1);
		if (lua_isstring (L, -1))
			n++;
	}
	return n;
}


/*
** Convert a pair (string, value) into a LDAPMod structure.
** Assume that string is at index -2 and value at -1.
*/
static LDAPMod *attr2mod (lua_State *L, int op) {
	LDAPMod *mod = (LDAPMod *)malloc (sizeof (LDAPMod));
	mod->mod_op = op;
	mod->mod_type = luastrcpy (L, -2, NULL);
	mod->mod_bvalues = table2bervalarray (L, lua_gettop(L));
	return mod;
}


/*
** Free an LDAPMod structure.
*/
static void free_mod (LDAPMod *mod) {
	if (mod->mod_type)
		free (mod->mod_type);
	free_bervalarray (mod->mod_bvalues);
	free (mod);
}


/*
** Convert a Lua table into an array of attributes.
** An array of attributes is a NULL-terminated array of LDAPMod's.
*/
static LDAPMod **table2attrarray (lua_State *L, int tab) {
	LDAPMod **array;
	size_t n = nstrkeys (L, tab);
	array = (LDAPMod **)malloc ((n+1) * sizeof (LDAPMod *));
	array[n] = NULL;
	n = 0;
	lua_pushnil (L);
	while (lua_next (L, tab) != 0) {
		if (lua_isstring (L, -1)) {
			array[n] = attr2mod (L, LDAP_MOD_ADD);
			n++;
		}
		lua_pop (L, 1);
	}
	return array;
}


/*
** Free an LDAPMod array.
*/
static void free_attrarray (LDAPMod **array) {
	int i;
	for (i = 0; array[i] != NULL; i++)
		free_mod (array[i]);
	free (array);
}


/*
** Add a new entry to the directory.
** @param #1 LDAP connection.
** @param #2 String with new entry's DN.
** @param #3 Table with new entry's attributes and values.
** @return ??
*/
static int lualdap_add (lua_State *L) {
	conn_data *conn = getconnection (L);
	const char *dn = luaL_check_string (L, 2);
	LDAPMod **attrs = table2attrarray (L, 3);
	int rc = ldap_add_ext_s (conn->ld, dn, attrs, NULL, NULL);
	free_attrarray (attrs);
	if (rc == LDAP_SUCCESS) {
		lua_pushboolean (L, 1);
		return 1;
	} else
		return faildirect (L, ldap_err2string (rc));
}


/*
** Compare a value against an entry.
** @param #1 LDAP connection.
** @param #2 String with entry's DN.
** @param #3 String with attribute's name.
** @param #4 String with attribute's value.
** @return Boolean.
*/
static int lualdap_compare (lua_State *L) {
	conn_data *conn = getconnection (L);
	const char *dn = luaL_check_string (L, 2);
	const char *attr = luaL_check_string (L, 3);
	BerValue bvalue;
	int rc;

	/* Perform the comparison operation */
	bvalue.bv_val = (char *)luaL_check_string (L, 4);
	bvalue.bv_len = lua_strlen (L, 4);
	rc = ldap_compare_ext_s (conn->ld, dn, attr, &bvalue, NULL, NULL);
	if (rc == LDAP_COMPARE_TRUE) {
		lua_pushboolean (L, 1);
		return 1;
	} else if (rc == LDAP_COMPARE_FALSE) {
		lua_pushboolean (L, 0);
		return 1;
	} else
		return faildirect (L, ldap_err2string (rc));
}


/*
** Delete an entry.
** @param #1 LDAP connection.
** @param #2 String with entry's DN.
** @return Boolean.
*/
static int lualdap_delete (lua_State *L) {
	conn_data *conn = getconnection (L);
	const char *dn = luaL_check_string (L, 2);
	int rc = ldap_delete_ext_s (conn->ld, dn, NULL, NULL);
	if (rc == LDAP_SUCCESS) {
		lua_pushboolean (L, 1);
		return 1;
	} else
		return faildirect (L, ldap_err2string (rc));
}


/*
** Convert a string into an internal LDAP_MOD operation code.
*/
static int op2code (const char *s) {
	switch (*s) {
		case 'a':
			return LDAP_MOD_ADD | LDAP_MOD_BVALUES;
		case 'd':
			return LDAP_MOD_DELETE | LDAP_MOD_BVALUES;
		case 'r':
			return LDAP_MOD_REPLACE | LDAP_MOD_BVALUES;
		default:
			return 0; /* never reached */
	}
}


/*
** Convert a table into a NULL-terminated array of berval.
*/
static BerValue **table2bervals (lua_State *L, int tab) {
	BerValue **values;
	int i;
	int n = luaL_getn (L, tab);
	values = (BerValue **)malloc ((n+1) * sizeof(BerValue *));
	for (i = 0; i < n; i++) {
		const char *s;
		size_t len;
		lua_rawgeti (L, tab, i+1);
		s = luaL_checklstring (L, -1, &len);
		values[i]->bv_val = malloc (len);
		memcpy (values[i]->bv_val, lua_tostring (L, -1), len);
		values[i]->bv_len = len;
	}
	values[n] = NULL;
	lua_pop (L, n);
	return values;
}


/*
** Convert a table into an LDAPMod structure.
*/
static LDAPMod *table2ldapmod (lua_State *L, int tab, int i) {
	const char *s;
	size_t len;
	LDAPMod *mod;
	/* check table */
	lua_rawgeti (L, tab, i);
	luaL_checktype (L, -1, LUA_TTABLE);
	tab = lua_gettop (L);
	mod = (LDAPMod *)malloc (sizeof (LDAPMod));
	/* get modification operation */
	lua_pushstring (L, "op");
	lua_rawget (L, tab);
	s = luaL_checklstring (L, -1, &len);
	mod->mod_op = op2code (s);
	/* get type of the attribute to modify */
	lua_pushstring (L, "type");
	lua_rawget (L, tab);
	s = luaL_checklstring (L, -1, &len);
	mod->mod_type = malloc (len);
	memcpy (mod->mod_type, s, len);
	/* get the values to add, delete or replace. */
	lua_pushstring (L, "values");
	lua_rawget (L, tab);
	if (lua_istable (L, -1))
		/* a set of values */
		mod->mod_bvalues = table2bervals (L, lua_gettop (L));
	else {
		/* just one value */
		size_t len;
		const char *s = luaL_checklstring (L, -1, &len);
		mod->mod_bvalues = (BerValue **)malloc (2 * sizeof (BerValue *));
		mod->mod_bvalues[0] = (BerValue *)malloc (sizeof (BerValue));
		mod->mod_bvalues[0]->bv_val = (char *)malloc (len * sizeof (char));
		memcpy (mod->mod_bvalues[0]->bv_val, s, len);
		mod->mod_bvalues[0]->bv_len = len;
		mod->mod_bvalues[1] = NULL;
	}
	lua_pop (L, 4);
	return mod;
}


/*
** Build an array of modifications.
*/
static LDAPMod **getmods (lua_State *L, int tab) {
	LDAPMod **mods;
	int i, n;
	luaL_checktype (L, tab, LUA_TTABLE);
	n = luaL_getn (L, tab);
	mods = (LDAPMod **)malloc ((n+1) * sizeof (LDAPMod **));
	for (i = 0; i < n; i++) {
		mods[i] = table2ldapmod (L, tab, i+1);
	}
	mods[n] = NULL;
	return mods;
}


/*
** Free modifications array.
*/
static void freemods (LDAPMod **mods) {
	int i;
	for (i = 0; mods[i] != NULL; i++) {
		int j;
		for (j = 0; mods[i]->mod_bvalues[j] != NULL; j++)
			free (mods[i]->mod_bvalues[j]->bv_val);
			free (mods[i]->mod_bvalues[j]);
		free (mods[i]->mod_type);
		free (mods[i]->mod_bvalues);
		free (mods[i]);
	}
	free (mods);
}


/*
** Modify an entry.
** @param #1 LDAP connection.
** @param #2 String with entry's DN.
** @param #3 Table with modifications to apply.
** @return Boolean.
*/
static int lualdap_modify (lua_State *L) {
	conn_data *conn = getconnection (L);
	const char *dn = luaL_check_string (L, 2);
	LDAPMod **mods = getmods (L, 3);
	int rc = ldap_modify_ext_s (conn->ld, dn, mods, NULL, NULL);
	freemods (mods);
	if (rc == LDAP_SUCCESS) {
		lua_pushboolean (L, 1);
		return 1;
	} else
		return faildirect (L, ldap_err2string (rc));
}


/*
** Push an attribute value (or a table of values) on top of the stack.
** @param entry Current entry.
** @param attr Name of entry's attribute to get values from.
** @return 1 in case of success.
*/
static int pushvalues (lua_State *L, LDAP *ld, LDAPMessage *entry, char *attr) {
	int i, n;
	BerValue **vals = ldap_get_values_len (ld, entry, attr);
	if ((n = ldap_count_values_len (vals)) == 1)
		lua_pushlstring (L, vals[0]->bv_val, vals[0]->bv_len);
	else { /* Multiple values */
		lua_newtable (L);
		for (i = 0; i < n; i++) {
			lua_pushlstring (L, vals[i]->bv_val, vals[i]->bv_len);
			lua_rawseti (L, -2, i);
		}
	}
	ldap_value_free_len (vals);
	return 1;
}


/*
** Store entry's distinguished name at the given table.
** @param entry Current entry.
** @param tab Absolute stack index of the table.
*/
static void setdn (lua_State *L, LDAP *ld, LDAPMessage *entry, int tab) {
	char *dn = ldap_get_dn (ld, entry);
	lua_pushstring (L, "dn");
	lua_pushstring (L, dn);
	lua_rawset (L, tab);
	ldap_memfree (dn);
}


/*
** Store entry's attributes and values at the given table.
** @param entry Current entry.
** @param tab Absolute stack index of the table.
*/
static void setattribs (lua_State *L, LDAP *ld, LDAPMessage *entry, int tab) {
	char *attr;
	BerElement *ber = NULL;
	for (attr = ldap_first_attribute (ld, entry, &ber);
		attr != NULL;
		attr = ldap_next_attribute (ld, entry, ber))
	{
		lua_pushstring (L, attr);
		pushvalues (L, ld, entry, attr);
		lua_rawset (L, tab); /* tab[attr] = vals */
		ldap_memfree (attr);
	}
	if (ber)
		ber_free (ber, 0);
}


/*
** Retrieve next message...
** @return #1 current entry (or nil if no more entries).
** @return #2 table with entry's attributes and values.
*/
static int next_message (lua_State *L) {
	search_data *search = getsearch (L);
	conn_data *conn;
	struct timeval *timeout = NULL; /* ??? function parameter ??? */
	LDAPMessage *res;
	int rc;

	lua_rawgeti (L, LUA_REGISTRYINDEX, search->conn);
	conn = (conn_data *)lua_touserdata (L, -1); /* get connection */

	rc = ldap_result (conn->ld, search->msgid, LDAP_MSG_ONE, timeout, &res);
	if (rc == 0)
		return faildirect (L, LUALDAP_PREFIX"result timeout expired");
	else if (rc == -1)
		return faildirect (L, LUALDAP_PREFIX"result error");

	if (rc == LDAP_RES_SEARCH_RESULT) /* last message => nil */
		lua_pushnil (L);
	else {
		LDAPMessage *msg = ldap_first_message (conn->ld, res);
		switch (ldap_msgtype (msg)) {
			case LDAP_RES_SEARCH_ENTRY: {
				int tab;
				LDAPMessage *entry = ldap_first_entry (conn->ld, msg);

				lua_newtable (L);
				tab = lua_gettop (L);
				setdn (L, conn->ld, entry, tab);
				setattribs (L, conn->ld, entry, tab);
				break;
			}
			case LDAP_RES_SEARCH_REFERENCE: {
				/*LDAPMessage *ref = ldap_first_reference (conn->ld, msg);*/
				break;
			}
			case LDAP_RES_SEARCH_RESULT:
				lua_pushnil (L);
				break;
			default:
				luaL_error (L, LUALDAP_PREFIX"error on search result chain");
		}
	
		ldap_msgfree (res);
	}
	return 1;
}




/*
** Convert a string to one of the possible scopes of the search.
*/
static int string2scope (const char *s) {
	switch (*s) {
		case 'b':
			return LDAP_SCOPE_BASE;
		case 'o':
			return LDAP_SCOPE_ONELEVEL;
		case 's':
			return LDAP_SCOPE_SUBTREE;
		default:
			return LDAP_SCOPE_DEFAULT;
	}
}


/*
**
*/
static int lualdap_search_close (lua_State *L) {
	search_data *search = getsearch (L);
	if (search->closed)
		return 0;
	luaL_unref (L, LUA_REGISTRYINDEX, search->conn);
	lua_pushnumber (L, 1);
	return 1;
}


/*
** Create a search object.
*/
static void create_search (lua_State *L, int conn_index, int msgid) {
	search_data *search = (search_data *)lua_newuserdata (L, sizeof (search_data));
	lualdap_setmeta (L, LUALDAP_SEARCH_METATABLE);
	search->closed = 0;
	search->conn = LUA_NOREF;
	search->msgid = msgid;
	lua_pushvalue (L, conn_index);
	search->conn = luaL_ref (L, LUA_REGISTRYINDEX);
}


/*
** Perform a search operation.
** @param #1 LDAP connection.
** @param #2 String with base entry's DN.
** @param #3 String with search scope.
** @param #4 String with search filter.
** @param #5 Table with names of attributes to retrieve.
** @return #1 Function to iterate over the result entries.
** @return #2 LDAP connection.
** @return #3 nil as first entry.
** The search result is defined as an upvalue of the iterator.
*/
static int lualdap_search (lua_State *L) {
	conn_data *conn = getconnection (L);
	const char *base = luaL_check_string (L, 2);
	int scope = string2scope (luaL_check_string (L, 3));
	const char *filter = luaL_check_string (L, 4);
	char **attrs = NULL;
	int attrsonly = 0;	/* types and values. parameter? */
	int msgid;
	int rc;
	struct timeval *timeout = NULL; /* ??? function parameter ??? */
	int sizelimit = LDAP_NO_LIMIT; /* ??? function parameter ??? */

	if (lua_istable (L, 5))
		attrs = table2strarray (L, 5);
	rc = ldap_search_ext (conn->ld, base, scope, filter, attrs, attrsonly,
		NULL, NULL, timeout, sizelimit, &msgid);
	free_strarray (attrs);
	if (rc != LDAP_SUCCESS)
		return faildirect (L, ldap_err2string (rc));

	create_search (L, 1, msgid);
	lua_pushcclosure (L, next_message, 1);
	lua_pushnil (L);
	lua_pushnil (L);
	return 3;
}


/*
** Create a metatable.
*/
static int lualdap_createmeta (lua_State *L) {
	const luaL_reg methods[] = {
		{"close", lualdap_close},
		{"add", lualdap_add},
		{"compare", lualdap_compare},
		{"delete", lualdap_delete},
		{"modify", lualdap_modify},
		{"search", lualdap_search},
		{NULL, NULL}
	};

	if (!luaL_newmetatable (L, LUALDAP_CONNECTION_METATABLE))
		return 0;

	/* define methods */
	luaL_openlib (L, NULL, methods, 0);

	/* define metamethods */
	lua_pushliteral (L, "__gc");
	lua_pushcfunction (L, lualdap_close);
	lua_settable (L, -3);

	lua_pushliteral (L, "__index");
	lua_pushvalue (L, -2);
	lua_settable (L, -3);

	lua_pushliteral (L, "__metatable");
	lua_pushliteral(L,LUALDAP_PREFIX"you're not allowed to get this metatable");
	lua_settable (L, -3);

	if (!luaL_newmetatable (L, LUALDAP_SEARCH_METATABLE))
		return 0;

	lua_pushliteral (L, "__gc");
	lua_pushcfunction (L, lualdap_search_close);
	lua_settable (L, -3);

	lua_pushliteral (L, "__metatable");
	lua_pushliteral(L,LUALDAP_PREFIX"you're not allowed to get this metatable");
	lua_settable (L, -3);

	return 0;
}


/*
** Open and initialize a connection to a server.
** @param #1 String with hostname.
** @param #2 String with username.
** @param #3 String with password.
** @return #1 Userdata with connection structure.
*/
static int lualdap_open_simple (lua_State *L) {
	const char *host = luaL_check_string (L, 1);
	/*const char *who = luaL_check_string (L, 2);*/
	const char *who = luaL_optstring (L, 2, NULL);
	const char *password = luaL_optstring (L, 3, NULL);
	conn_data *conn = (conn_data *)lua_newuserdata (L, sizeof(conn_data));
	int err;

	/* Initialize */
	lualdap_setmeta (L, LUALDAP_CONNECTION_METATABLE);
	conn->version = 0;
	conn->closed = 0;
	conn->ld = ldap_init (host, LDAP_PORT);
	if (!conn->ld)
		return faildirect(L,LUALDAP_PREFIX"Error connecting to server");
	/* Set protocol version */
	conn->version = LDAP_VERSION3;
	if (ldap_set_option (conn->ld, LDAP_OPT_PROTOCOL_VERSION, &conn->version)
		!= LDAP_OPT_SUCCESS)
		return faildirect(L, LUALDAP_PREFIX"Error setting LDAP version");
	/* Bind to a server */
	err = ldap_bind_s (conn->ld, who, password, LDAP_AUTH_SIMPLE);
	if (err != LDAP_SUCCESS)
		return faildirect (L, ldap_err2string (err));

	return 1;
}


/*
** Create ldap table and register the open method.
*/
int lualdap_libopen (lua_State *L) {
	lualdap_createmeta (L);

	lua_newtable (L);
	lua_pushliteral (L, "open_simple");
	lua_pushcfunction (L, lualdap_open_simple);
	lua_rawset (L, -3);
	lua_setglobal (L, LUALDAP_TABLENAME);
	
	return 0;
}